three.cjs 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '183';
  8. /**
  9. * Represents mouse buttons and interaction types in context of controls.
  10. *
  11. * @type {ConstantsMouse}
  12. * @constant
  13. */
  14. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  15. /**
  16. * Represents touch interaction types in context of controls.
  17. *
  18. * @type {ConstantsTouch}
  19. * @constant
  20. */
  21. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  22. /**
  23. * Disables face culling.
  24. *
  25. * @type {number}
  26. * @constant
  27. */
  28. const CullFaceNone = 0;
  29. /**
  30. * Culls back faces.
  31. *
  32. * @type {number}
  33. * @constant
  34. */
  35. const CullFaceBack = 1;
  36. /**
  37. * Culls front faces.
  38. *
  39. * @type {number}
  40. * @constant
  41. */
  42. const CullFaceFront = 2;
  43. /**
  44. * Culls both front and back faces.
  45. *
  46. * @type {number}
  47. * @constant
  48. */
  49. const CullFaceFrontBack = 3;
  50. /**
  51. * Gives unfiltered shadow maps - fastest, but lowest quality.
  52. *
  53. * @type {number}
  54. * @constant
  55. */
  56. const BasicShadowMap = 0;
  57. /**
  58. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  59. *
  60. * @type {number}
  61. * @constant
  62. */
  63. const PCFShadowMap = 1;
  64. /**
  65. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  66. * better soft shadows especially when using low-resolution shadow maps.
  67. *
  68. * @type {number}
  69. * @constant
  70. */
  71. const PCFSoftShadowMap = 2;
  72. /**
  73. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  74. * When using VSMShadowMap all shadow receivers will also cast shadows.
  75. *
  76. * @type {number}
  77. * @constant
  78. */
  79. const VSMShadowMap = 3;
  80. /**
  81. * Only front faces are rendered.
  82. *
  83. * @type {number}
  84. * @constant
  85. */
  86. const FrontSide = 0;
  87. /**
  88. * Only back faces are rendered.
  89. *
  90. * @type {number}
  91. * @constant
  92. */
  93. const BackSide = 1;
  94. /**
  95. * Both front and back faces are rendered.
  96. *
  97. * @type {number}
  98. * @constant
  99. */
  100. const DoubleSide = 2;
  101. /**
  102. * No blending is performed which effectively disables
  103. * alpha transparency.
  104. *
  105. * @type {number}
  106. * @constant
  107. */
  108. const NoBlending = 0;
  109. /**
  110. * The default blending.
  111. *
  112. * @type {number}
  113. * @constant
  114. */
  115. const NormalBlending = 1;
  116. /**
  117. * Represents additive blending.
  118. *
  119. * @type {number}
  120. * @constant
  121. */
  122. const AdditiveBlending = 2;
  123. /**
  124. * Represents subtractive blending.
  125. *
  126. * @type {number}
  127. * @constant
  128. */
  129. const SubtractiveBlending = 3;
  130. /**
  131. * Represents multiply blending.
  132. *
  133. * @type {number}
  134. * @constant
  135. */
  136. const MultiplyBlending = 4;
  137. /**
  138. * Represents custom blending.
  139. *
  140. * @type {number}
  141. * @constant
  142. */
  143. const CustomBlending = 5;
  144. /**
  145. * Represents material blending.
  146. *
  147. * @type {number}
  148. * @constant
  149. */
  150. const MaterialBlending = 6;
  151. /**
  152. * A `source + destination` blending equation.
  153. *
  154. * @type {number}
  155. * @constant
  156. */
  157. const AddEquation = 100;
  158. /**
  159. * A `source - destination` blending equation.
  160. *
  161. * @type {number}
  162. * @constant
  163. */
  164. const SubtractEquation = 101;
  165. /**
  166. * A `destination - source` blending equation.
  167. *
  168. * @type {number}
  169. * @constant
  170. */
  171. const ReverseSubtractEquation = 102;
  172. /**
  173. * A blend equation that uses the minimum of source and destination.
  174. *
  175. * @type {number}
  176. * @constant
  177. */
  178. const MinEquation = 103;
  179. /**
  180. * A blend equation that uses the maximum of source and destination.
  181. *
  182. * @type {number}
  183. * @constant
  184. */
  185. const MaxEquation = 104;
  186. /**
  187. * Multiplies all colors by `0`.
  188. *
  189. * @type {number}
  190. * @constant
  191. */
  192. const ZeroFactor = 200;
  193. /**
  194. * Multiplies all colors by `1`.
  195. *
  196. * @type {number}
  197. * @constant
  198. */
  199. const OneFactor = 201;
  200. /**
  201. * Multiplies all colors by the source colors.
  202. *
  203. * @type {number}
  204. * @constant
  205. */
  206. const SrcColorFactor = 202;
  207. /**
  208. * Multiplies all colors by `1` minus each source color.
  209. *
  210. * @type {number}
  211. * @constant
  212. */
  213. const OneMinusSrcColorFactor = 203;
  214. /**
  215. * Multiplies all colors by the source alpha value.
  216. *
  217. * @type {number}
  218. * @constant
  219. */
  220. const SrcAlphaFactor = 204;
  221. /**
  222. * Multiplies all colors by 1 minus the source alpha value.
  223. *
  224. * @type {number}
  225. * @constant
  226. */
  227. const OneMinusSrcAlphaFactor = 205;
  228. /**
  229. * Multiplies all colors by the destination alpha value.
  230. *
  231. * @type {number}
  232. * @constant
  233. */
  234. const DstAlphaFactor = 206;
  235. /**
  236. * Multiplies all colors by `1` minus the destination alpha value.
  237. *
  238. * @type {number}
  239. * @constant
  240. */
  241. const OneMinusDstAlphaFactor = 207;
  242. /**
  243. * Multiplies all colors by the destination color.
  244. *
  245. * @type {number}
  246. * @constant
  247. */
  248. const DstColorFactor = 208;
  249. /**
  250. * Multiplies all colors by `1` minus each destination color.
  251. *
  252. * @type {number}
  253. * @constant
  254. */
  255. const OneMinusDstColorFactor = 209;
  256. /**
  257. * Multiplies the RGB colors by the smaller of either the source alpha
  258. * value or the value of `1` minus the destination alpha value. The alpha
  259. * value is multiplied by `1`.
  260. *
  261. * @type {number}
  262. * @constant
  263. */
  264. const SrcAlphaSaturateFactor = 210;
  265. /**
  266. * Multiplies all colors by a constant color.
  267. *
  268. * @type {number}
  269. * @constant
  270. */
  271. const ConstantColorFactor = 211;
  272. /**
  273. * Multiplies all colors by `1` minus a constant color.
  274. *
  275. * @type {number}
  276. * @constant
  277. */
  278. const OneMinusConstantColorFactor = 212;
  279. /**
  280. * Multiplies all colors by a constant alpha value.
  281. *
  282. * @type {number}
  283. * @constant
  284. */
  285. const ConstantAlphaFactor = 213;
  286. /**
  287. * Multiplies all colors by 1 minus a constant alpha value.
  288. *
  289. * @type {number}
  290. * @constant
  291. */
  292. const OneMinusConstantAlphaFactor = 214;
  293. /**
  294. * Never pass.
  295. *
  296. * @type {number}
  297. * @constant
  298. */
  299. const NeverDepth = 0;
  300. /**
  301. * Always pass.
  302. *
  303. * @type {number}
  304. * @constant
  305. */
  306. const AlwaysDepth = 1;
  307. /**
  308. * Pass if the incoming value is less than the depth buffer value.
  309. *
  310. * @type {number}
  311. * @constant
  312. */
  313. const LessDepth = 2;
  314. /**
  315. * Pass if the incoming value is less than or equal to the depth buffer value.
  316. *
  317. * @type {number}
  318. * @constant
  319. */
  320. const LessEqualDepth = 3;
  321. /**
  322. * Pass if the incoming value equals the depth buffer value.
  323. *
  324. * @type {number}
  325. * @constant
  326. */
  327. const EqualDepth = 4;
  328. /**
  329. * Pass if the incoming value is greater than or equal to the depth buffer value.
  330. *
  331. * @type {number}
  332. * @constant
  333. */
  334. const GreaterEqualDepth = 5;
  335. /**
  336. * Pass if the incoming value is greater than the depth buffer value.
  337. *
  338. * @type {number}
  339. * @constant
  340. */
  341. const GreaterDepth = 6;
  342. /**
  343. * Pass if the incoming value is not equal to the depth buffer value.
  344. *
  345. * @type {number}
  346. * @constant
  347. */
  348. const NotEqualDepth = 7;
  349. /**
  350. * Multiplies the environment map color with the surface color.
  351. *
  352. * @type {number}
  353. * @constant
  354. */
  355. const MultiplyOperation = 0;
  356. /**
  357. * Uses reflectivity to blend between the two colors.
  358. *
  359. * @type {number}
  360. * @constant
  361. */
  362. const MixOperation = 1;
  363. /**
  364. * Adds the two colors.
  365. *
  366. * @type {number}
  367. * @constant
  368. */
  369. const AddOperation = 2;
  370. /**
  371. * No tone mapping is applied.
  372. *
  373. * @type {number}
  374. * @constant
  375. */
  376. const NoToneMapping = 0;
  377. /**
  378. * Linear tone mapping.
  379. *
  380. * @type {number}
  381. * @constant
  382. */
  383. const LinearToneMapping = 1;
  384. /**
  385. * Reinhard tone mapping.
  386. *
  387. * @type {number}
  388. * @constant
  389. */
  390. const ReinhardToneMapping = 2;
  391. /**
  392. * Cineon tone mapping.
  393. *
  394. * @type {number}
  395. * @constant
  396. */
  397. const CineonToneMapping = 3;
  398. /**
  399. * ACES Filmic tone mapping.
  400. *
  401. * @type {number}
  402. * @constant
  403. */
  404. const ACESFilmicToneMapping = 4;
  405. /**
  406. * Custom tone mapping.
  407. *
  408. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  409. *
  410. * @type {number}
  411. * @constant
  412. */
  413. const CustomToneMapping = 5;
  414. /**
  415. * AgX tone mapping.
  416. *
  417. * @type {number}
  418. * @constant
  419. */
  420. const AgXToneMapping = 6;
  421. /**
  422. * Neutral tone mapping.
  423. *
  424. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  425. *
  426. * @type {number}
  427. * @constant
  428. */
  429. const NeutralToneMapping = 7;
  430. /**
  431. * The skinned mesh shares the same world space as the skeleton.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const AttachedBindMode = 'attached';
  437. /**
  438. * The skinned mesh does not share the same world space as the skeleton.
  439. * This is useful when a skeleton is shared across multiple skinned meshes.
  440. *
  441. * @type {string}
  442. * @constant
  443. */
  444. const DetachedBindMode = 'detached';
  445. /**
  446. * Maps textures using the geometry's UV coordinates.
  447. *
  448. * @type {number}
  449. * @constant
  450. */
  451. const UVMapping = 300;
  452. /**
  453. * Reflection mapping for cube textures.
  454. *
  455. * @type {number}
  456. * @constant
  457. */
  458. const CubeReflectionMapping = 301;
  459. /**
  460. * Refraction mapping for cube textures.
  461. *
  462. * @type {number}
  463. * @constant
  464. */
  465. const CubeRefractionMapping = 302;
  466. /**
  467. * Reflection mapping for equirectangular textures.
  468. *
  469. * @type {number}
  470. * @constant
  471. */
  472. const EquirectangularReflectionMapping = 303;
  473. /**
  474. * Refraction mapping for equirectangular textures.
  475. *
  476. * @type {number}
  477. * @constant
  478. */
  479. const EquirectangularRefractionMapping = 304;
  480. /**
  481. * Reflection mapping for PMREM textures.
  482. *
  483. * @type {number}
  484. * @constant
  485. */
  486. const CubeUVReflectionMapping = 306;
  487. /**
  488. * The texture will simply repeat to infinity.
  489. *
  490. * @type {number}
  491. * @constant
  492. */
  493. const RepeatWrapping = 1000;
  494. /**
  495. * The last pixel of the texture stretches to the edge of the mesh.
  496. *
  497. * @type {number}
  498. * @constant
  499. */
  500. const ClampToEdgeWrapping = 1001;
  501. /**
  502. * The texture will repeats to infinity, mirroring on each repeat.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const MirroredRepeatWrapping = 1002;
  508. /**
  509. * Returns the value of the texture element that is nearest (in Manhattan distance)
  510. * to the specified texture coordinates.
  511. *
  512. * @type {number}
  513. * @constant
  514. */
  515. const NearestFilter = 1003;
  516. /**
  517. * Chooses the mipmap that most closely matches the size of the pixel being textured
  518. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  519. * to produce a texture value.
  520. *
  521. * @type {number}
  522. * @constant
  523. */
  524. const NearestMipmapNearestFilter = 1004;
  525. const NearestMipMapNearestFilter = 1004; // legacy
  526. /**
  527. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  528. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  529. * The final texture value is a weighted average of those two values.
  530. *
  531. * @type {number}
  532. * @constant
  533. */
  534. const NearestMipmapLinearFilter = 1005;
  535. const NearestMipMapLinearFilter = 1005; // legacy
  536. /**
  537. * Returns the weighted average of the four texture elements that are closest to the specified
  538. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  539. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  540. *
  541. * @type {number}
  542. * @constant
  543. */
  544. const LinearFilter = 1006;
  545. /**
  546. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  547. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  548. * center of the pixel) to produce a texture value.
  549. *
  550. * @type {number}
  551. * @constant
  552. */
  553. const LinearMipmapNearestFilter = 1007;
  554. const LinearMipMapNearestFilter = 1007; // legacy
  555. /**
  556. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  557. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  558. * is a weighted average of those two values.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const LinearMipmapLinearFilter = 1008;
  564. const LinearMipMapLinearFilter = 1008; // legacy
  565. /**
  566. * An unsigned byte data type for textures.
  567. *
  568. * @type {number}
  569. * @constant
  570. */
  571. const UnsignedByteType = 1009;
  572. /**
  573. * A byte data type for textures.
  574. *
  575. * @type {number}
  576. * @constant
  577. */
  578. const ByteType = 1010;
  579. /**
  580. * A short data type for textures.
  581. *
  582. * @type {number}
  583. * @constant
  584. */
  585. const ShortType = 1011;
  586. /**
  587. * An unsigned short data type for textures.
  588. *
  589. * @type {number}
  590. * @constant
  591. */
  592. const UnsignedShortType = 1012;
  593. /**
  594. * An int data type for textures.
  595. *
  596. * @type {number}
  597. * @constant
  598. */
  599. const IntType = 1013;
  600. /**
  601. * An unsigned int data type for textures.
  602. *
  603. * @type {number}
  604. * @constant
  605. */
  606. const UnsignedIntType = 1014;
  607. /**
  608. * A float data type for textures.
  609. *
  610. * @type {number}
  611. * @constant
  612. */
  613. const FloatType = 1015;
  614. /**
  615. * A half float data type for textures.
  616. *
  617. * @type {number}
  618. * @constant
  619. */
  620. const HalfFloatType = 1016;
  621. /**
  622. * An unsigned short 4_4_4_4 (packed) data type for textures.
  623. *
  624. * @type {number}
  625. * @constant
  626. */
  627. const UnsignedShort4444Type = 1017;
  628. /**
  629. * An unsigned short 5_5_5_1 (packed) data type for textures.
  630. *
  631. * @type {number}
  632. * @constant
  633. */
  634. const UnsignedShort5551Type = 1018;
  635. /**
  636. * An unsigned int 24_8 data type for textures.
  637. *
  638. * @type {number}
  639. * @constant
  640. */
  641. const UnsignedInt248Type = 1020;
  642. /**
  643. * An unsigned int 5_9_9_9 (packed) data type for textures.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const UnsignedInt5999Type = 35902;
  649. /**
  650. * An unsigned int 10_11_11 (packed) data type for textures.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const UnsignedInt101111Type = 35899;
  656. /**
  657. * Discards the red, green and blue components and reads just the alpha component.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const AlphaFormat = 1021;
  663. /**
  664. * Discards the alpha component and reads the red, green and blue component.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const RGBFormat = 1022;
  670. /**
  671. * Reads the red, green, blue and alpha components.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const RGBAFormat = 1023;
  677. /**
  678. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const DepthFormat = 1026;
  684. /**
  685. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  686. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const DepthStencilFormat = 1027;
  692. /**
  693. * Discards the green, blue and alpha components and reads just the red component.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RedFormat = 1028;
  699. /**
  700. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RedIntegerFormat = 1029;
  706. /**
  707. * Discards the alpha, and blue components and reads the red, and green components.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGFormat = 1030;
  713. /**
  714. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGIntegerFormat = 1031;
  720. /**
  721. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGBIntegerFormat = 1032;
  727. /**
  728. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGBAIntegerFormat = 1033;
  734. /**
  735. * A DXT1-compressed image in an RGB image format.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGB_S3TC_DXT1_Format = 33776;
  741. /**
  742. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT1_Format = 33777;
  748. /**
  749. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGBA_S3TC_DXT3_Format = 33778;
  755. /**
  756. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  757. * compression in how the alpha compression is done.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGBA_S3TC_DXT5_Format = 33779;
  763. /**
  764. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGB_PVRTC_4BPPV1_Format = 35840;
  770. /**
  771. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGB_PVRTC_2BPPV1_Format = 35841;
  777. /**
  778. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGBA_PVRTC_4BPPV1_Format = 35842;
  784. /**
  785. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGBA_PVRTC_2BPPV1_Format = 35843;
  791. /**
  792. * ETC1 RGB format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGB_ETC1_Format = 36196;
  798. /**
  799. * ETC2 RGB format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGB_ETC2_Format = 37492;
  805. /**
  806. * ETC2 RGBA format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const RGBA_ETC2_EAC_Format = 37496;
  812. /**
  813. * EAC R11 UNORM format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const R11_EAC_Format = 37488; // 0x9270
  819. /**
  820. * EAC R11 SNORM format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  826. /**
  827. * EAC RG11 UNORM format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const RG11_EAC_Format = 37490; // 0x9272
  833. /**
  834. * EAC RG11 SNORM format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  840. /**
  841. * ASTC RGBA 4x4 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_4x4_Format = 37808;
  847. /**
  848. * ASTC RGBA 5x4 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_5x4_Format = 37809;
  854. /**
  855. * ASTC RGBA 5x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_5x5_Format = 37810;
  861. /**
  862. * ASTC RGBA 6x5 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_6x5_Format = 37811;
  868. /**
  869. * ASTC RGBA 6x6 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_6x6_Format = 37812;
  875. /**
  876. * ASTC RGBA 8x5 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_8x5_Format = 37813;
  882. /**
  883. * ASTC RGBA 8x6 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_8x6_Format = 37814;
  889. /**
  890. * ASTC RGBA 8x8 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_8x8_Format = 37815;
  896. /**
  897. * ASTC RGBA 10x5 format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_ASTC_10x5_Format = 37816;
  903. /**
  904. * ASTC RGBA 10x6 format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGBA_ASTC_10x6_Format = 37817;
  910. /**
  911. * ASTC RGBA 10x8 format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGBA_ASTC_10x8_Format = 37818;
  917. /**
  918. * ASTC RGBA 10x10 format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RGBA_ASTC_10x10_Format = 37819;
  924. /**
  925. * ASTC RGBA 12x10 format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const RGBA_ASTC_12x10_Format = 37820;
  931. /**
  932. * ASTC RGBA 12x12 format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RGBA_ASTC_12x12_Format = 37821;
  938. /**
  939. * BPTC RGBA format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const RGBA_BPTC_Format = 36492;
  945. /**
  946. * BPTC Signed RGB format.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const RGB_BPTC_SIGNED_Format = 36494;
  952. /**
  953. * BPTC Unsigned RGB format.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const RGB_BPTC_UNSIGNED_Format = 36495;
  959. /**
  960. * RGTC1 Red format.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const RED_RGTC1_Format = 36283;
  966. /**
  967. * RGTC1 Signed Red format.
  968. *
  969. * @type {number}
  970. * @constant
  971. */
  972. const SIGNED_RED_RGTC1_Format = 36284;
  973. /**
  974. * RGTC2 Red Green format.
  975. *
  976. * @type {number}
  977. * @constant
  978. */
  979. const RED_GREEN_RGTC2_Format = 36285;
  980. /**
  981. * RGTC2 Signed Red Green format.
  982. *
  983. * @type {number}
  984. * @constant
  985. */
  986. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  987. /**
  988. * Animations are played once.
  989. *
  990. * @type {number}
  991. * @constant
  992. */
  993. const LoopOnce = 2200;
  994. /**
  995. * Animations are played with a chosen number of repetitions, each time jumping from
  996. * the end of the clip directly to its beginning.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const LoopRepeat = 2201;
  1002. /**
  1003. * Animations are played with a chosen number of repetitions, alternately playing forward
  1004. * and backward.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const LoopPingPong = 2202;
  1010. /**
  1011. * Discrete interpolation mode for keyframe tracks.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const InterpolateDiscrete = 2300;
  1017. /**
  1018. * Linear interpolation mode for keyframe tracks.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const InterpolateLinear = 2301;
  1024. /**
  1025. * Smooth interpolation mode for keyframe tracks.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const InterpolateSmooth = 2302;
  1031. /**
  1032. * Bezier interpolation mode for keyframe tracks.
  1033. *
  1034. * Uses cubic Bezier curves with explicit 2D control points.
  1035. * Requires tangent data to be set on the track.
  1036. *
  1037. * @type {number}
  1038. * @constant
  1039. */
  1040. const InterpolateBezier = 2303;
  1041. /**
  1042. * Zero curvature ending for animations.
  1043. *
  1044. * @type {number}
  1045. * @constant
  1046. */
  1047. const ZeroCurvatureEnding = 2400;
  1048. /**
  1049. * Zero slope ending for animations.
  1050. *
  1051. * @type {number}
  1052. * @constant
  1053. */
  1054. const ZeroSlopeEnding = 2401;
  1055. /**
  1056. * Wrap around ending for animations.
  1057. *
  1058. * @type {number}
  1059. * @constant
  1060. */
  1061. const WrapAroundEnding = 2402;
  1062. /**
  1063. * Default animation blend mode.
  1064. *
  1065. * @type {number}
  1066. * @constant
  1067. */
  1068. const NormalAnimationBlendMode = 2500;
  1069. /**
  1070. * Additive animation blend mode. Can be used to layer motions on top of
  1071. * each other to build complex performances from smaller re-usable assets.
  1072. *
  1073. * @type {number}
  1074. * @constant
  1075. */
  1076. const AdditiveAnimationBlendMode = 2501;
  1077. /**
  1078. * For every three vertices draw a single triangle.
  1079. *
  1080. * @type {number}
  1081. * @constant
  1082. */
  1083. const TrianglesDrawMode = 0;
  1084. /**
  1085. * For each vertex draw a triangle from the last three vertices.
  1086. *
  1087. * @type {number}
  1088. * @constant
  1089. */
  1090. const TriangleStripDrawMode = 1;
  1091. /**
  1092. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1093. *
  1094. * @type {number}
  1095. * @constant
  1096. */
  1097. const TriangleFanDrawMode = 2;
  1098. /**
  1099. * The depth value is inverted (1.0 - z) for visualization purposes.
  1100. *
  1101. * @type {number}
  1102. * @constant
  1103. */
  1104. const BasicDepthPacking = 3200;
  1105. /**
  1106. * The depth value is packed into 32 bit RGBA.
  1107. *
  1108. * @type {number}
  1109. * @constant
  1110. */
  1111. const RGBADepthPacking = 3201;
  1112. /**
  1113. * The depth value is packed into 24 bit RGB.
  1114. *
  1115. * @type {number}
  1116. * @constant
  1117. */
  1118. const RGBDepthPacking = 3202;
  1119. /**
  1120. * The depth value is packed into 16 bit RG.
  1121. *
  1122. * @type {number}
  1123. * @constant
  1124. */
  1125. const RGDepthPacking = 3203;
  1126. /**
  1127. * Normal information is relative to the underlying surface.
  1128. *
  1129. * @type {number}
  1130. * @constant
  1131. */
  1132. const TangentSpaceNormalMap = 0;
  1133. /**
  1134. * Normal information is relative to the object orientation.
  1135. *
  1136. * @type {number}
  1137. * @constant
  1138. */
  1139. const ObjectSpaceNormalMap = 1;
  1140. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1141. /**
  1142. * No color space.
  1143. *
  1144. * @type {string}
  1145. * @constant
  1146. */
  1147. const NoColorSpace = '';
  1148. /**
  1149. * sRGB color space.
  1150. *
  1151. * @type {string}
  1152. * @constant
  1153. */
  1154. const SRGBColorSpace = 'srgb';
  1155. /**
  1156. * sRGB-linear color space.
  1157. *
  1158. * @type {string}
  1159. * @constant
  1160. */
  1161. const LinearSRGBColorSpace = 'srgb-linear';
  1162. /**
  1163. * Linear transfer function.
  1164. *
  1165. * @type {string}
  1166. * @constant
  1167. */
  1168. const LinearTransfer = 'linear';
  1169. /**
  1170. * sRGB transfer function.
  1171. *
  1172. * @type {string}
  1173. * @constant
  1174. */
  1175. const SRGBTransfer = 'srgb';
  1176. /**
  1177. * No normal map packing.
  1178. *
  1179. * @type {string}
  1180. * @constant
  1181. */
  1182. const NoNormalPacking = '';
  1183. /**
  1184. * Normal RG packing.
  1185. *
  1186. * @type {string}
  1187. * @constant
  1188. */
  1189. const NormalRGPacking = 'rg';
  1190. /**
  1191. * Normal GA packing.
  1192. *
  1193. * @type {string}
  1194. * @constant
  1195. */
  1196. const NormalGAPacking = 'ga';
  1197. /**
  1198. * Sets the stencil buffer value to `0`.
  1199. *
  1200. * @type {number}
  1201. * @constant
  1202. */
  1203. const ZeroStencilOp = 0;
  1204. /**
  1205. * Keeps the current value.
  1206. *
  1207. * @type {number}
  1208. * @constant
  1209. */
  1210. const KeepStencilOp = 7680;
  1211. /**
  1212. * Sets the stencil buffer value to the specified reference value.
  1213. *
  1214. * @type {number}
  1215. * @constant
  1216. */
  1217. const ReplaceStencilOp = 7681;
  1218. /**
  1219. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1220. *
  1221. * @type {number}
  1222. * @constant
  1223. */
  1224. const IncrementStencilOp = 7682;
  1225. /**
  1226. * Decrements the current stencil buffer value. Clamps to `0`.
  1227. *
  1228. * @type {number}
  1229. * @constant
  1230. */
  1231. const DecrementStencilOp = 7683;
  1232. /**
  1233. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1234. * the maximum representable unsigned value.
  1235. *
  1236. * @type {number}
  1237. * @constant
  1238. */
  1239. const IncrementWrapStencilOp = 34055;
  1240. /**
  1241. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1242. * unsigned value when decrementing a stencil buffer value of `0`.
  1243. *
  1244. * @type {number}
  1245. * @constant
  1246. */
  1247. const DecrementWrapStencilOp = 34056;
  1248. /**
  1249. * Inverts the current stencil buffer value bitwise.
  1250. *
  1251. * @type {number}
  1252. * @constant
  1253. */
  1254. const InvertStencilOp = 5386;
  1255. /**
  1256. * Will never return true.
  1257. *
  1258. * @type {number}
  1259. * @constant
  1260. */
  1261. const NeverStencilFunc = 512;
  1262. /**
  1263. * Will return true if the stencil reference value is less than the current stencil value.
  1264. *
  1265. * @type {number}
  1266. * @constant
  1267. */
  1268. const LessStencilFunc = 513;
  1269. /**
  1270. * Will return true if the stencil reference value is equal to the current stencil value.
  1271. *
  1272. * @type {number}
  1273. * @constant
  1274. */
  1275. const EqualStencilFunc = 514;
  1276. /**
  1277. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1278. *
  1279. * @type {number}
  1280. * @constant
  1281. */
  1282. const LessEqualStencilFunc = 515;
  1283. /**
  1284. * Will return true if the stencil reference value is greater than the current stencil value.
  1285. *
  1286. * @type {number}
  1287. * @constant
  1288. */
  1289. const GreaterStencilFunc = 516;
  1290. /**
  1291. * Will return true if the stencil reference value is not equal to the current stencil value.
  1292. *
  1293. * @type {number}
  1294. * @constant
  1295. */
  1296. const NotEqualStencilFunc = 517;
  1297. /**
  1298. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1299. *
  1300. * @type {number}
  1301. * @constant
  1302. */
  1303. const GreaterEqualStencilFunc = 518;
  1304. /**
  1305. * Will always return true.
  1306. *
  1307. * @type {number}
  1308. * @constant
  1309. */
  1310. const AlwaysStencilFunc = 519;
  1311. /**
  1312. * Never pass.
  1313. *
  1314. * @type {number}
  1315. * @constant
  1316. */
  1317. const NeverCompare = 512;
  1318. /**
  1319. * Pass if the incoming value is less than the texture value.
  1320. *
  1321. * @type {number}
  1322. * @constant
  1323. */
  1324. const LessCompare = 513;
  1325. /**
  1326. * Pass if the incoming value equals the texture value.
  1327. *
  1328. * @type {number}
  1329. * @constant
  1330. */
  1331. const EqualCompare = 514;
  1332. /**
  1333. * Pass if the incoming value is less than or equal to the texture value.
  1334. *
  1335. * @type {number}
  1336. * @constant
  1337. */
  1338. const LessEqualCompare = 515;
  1339. /**
  1340. * Pass if the incoming value is greater than the texture value.
  1341. *
  1342. * @type {number}
  1343. * @constant
  1344. */
  1345. const GreaterCompare = 516;
  1346. /**
  1347. * Pass if the incoming value is not equal to the texture value.
  1348. *
  1349. * @type {number}
  1350. * @constant
  1351. */
  1352. const NotEqualCompare = 517;
  1353. /**
  1354. * Pass if the incoming value is greater than or equal to the texture value.
  1355. *
  1356. * @type {number}
  1357. * @constant
  1358. */
  1359. const GreaterEqualCompare = 518;
  1360. /**
  1361. * Always pass.
  1362. *
  1363. * @type {number}
  1364. * @constant
  1365. */
  1366. const AlwaysCompare = 519;
  1367. /**
  1368. * The contents are intended to be specified once by the application, and used many
  1369. * times as the source for drawing and image specification commands.
  1370. *
  1371. * @type {number}
  1372. * @constant
  1373. */
  1374. const StaticDrawUsage = 35044;
  1375. /**
  1376. * The contents are intended to be respecified repeatedly by the application, and
  1377. * used many times as the source for drawing and image specification commands.
  1378. *
  1379. * @type {number}
  1380. * @constant
  1381. */
  1382. const DynamicDrawUsage = 35048;
  1383. /**
  1384. * The contents are intended to be specified once by the application, and used at most
  1385. * a few times as the source for drawing and image specification commands.
  1386. *
  1387. * @type {number}
  1388. * @constant
  1389. */
  1390. const StreamDrawUsage = 35040;
  1391. /**
  1392. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1393. * many times by the application.
  1394. *
  1395. * @type {number}
  1396. * @constant
  1397. */
  1398. const StaticReadUsage = 35045;
  1399. /**
  1400. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1401. * many times by the application.
  1402. *
  1403. * @type {number}
  1404. * @constant
  1405. */
  1406. const DynamicReadUsage = 35049;
  1407. /**
  1408. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1409. * a few times by the application
  1410. *
  1411. * @type {number}
  1412. * @constant
  1413. */
  1414. const StreamReadUsage = 35041;
  1415. /**
  1416. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1417. * the source for WebGL drawing and image specification commands.
  1418. *
  1419. * @type {number}
  1420. * @constant
  1421. */
  1422. const StaticCopyUsage = 35046;
  1423. /**
  1424. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1425. * as the source for WebGL drawing and image specification commands.
  1426. *
  1427. * @type {number}
  1428. * @constant
  1429. */
  1430. const DynamicCopyUsage = 35050;
  1431. /**
  1432. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1433. * as the source for WebGL drawing and image specification commands.
  1434. *
  1435. * @type {number}
  1436. * @constant
  1437. */
  1438. const StreamCopyUsage = 35042;
  1439. /**
  1440. * GLSL 1 shader code.
  1441. *
  1442. * @type {string}
  1443. * @constant
  1444. */
  1445. const GLSL1 = '100';
  1446. /**
  1447. * GLSL 3 shader code.
  1448. *
  1449. * @type {string}
  1450. * @constant
  1451. */
  1452. const GLSL3 = '300 es';
  1453. /**
  1454. * WebGL coordinate system.
  1455. *
  1456. * @type {number}
  1457. * @constant
  1458. */
  1459. const WebGLCoordinateSystem = 2000;
  1460. /**
  1461. * WebGPU coordinate system.
  1462. *
  1463. * @type {number}
  1464. * @constant
  1465. */
  1466. const WebGPUCoordinateSystem = 2001;
  1467. /**
  1468. * Represents the different timestamp query types.
  1469. *
  1470. * @type {ConstantsTimestampQuery}
  1471. * @constant
  1472. */
  1473. const TimestampQuery = {
  1474. COMPUTE: 'compute',
  1475. RENDER: 'render'
  1476. };
  1477. /**
  1478. * Represents mouse buttons and interaction types in context of controls.
  1479. *
  1480. * @type {ConstantsInterpolationSamplingType}
  1481. * @constant
  1482. */
  1483. const InterpolationSamplingType = {
  1484. PERSPECTIVE: 'perspective',
  1485. LINEAR: 'linear',
  1486. FLAT: 'flat'
  1487. };
  1488. /**
  1489. * Represents the different interpolation sampling modes.
  1490. *
  1491. * @type {ConstantsInterpolationSamplingMode}
  1492. * @constant
  1493. */
  1494. const InterpolationSamplingMode = {
  1495. NORMAL: 'normal',
  1496. CENTROID: 'centroid',
  1497. SAMPLE: 'sample',
  1498. FIRST: 'first',
  1499. EITHER: 'either'
  1500. };
  1501. /**
  1502. * Compatibility flags for features that may not be supported across all platforms.
  1503. *
  1504. * @type {Object}
  1505. * @constant
  1506. */
  1507. const Compatibility = {
  1508. TEXTURE_COMPARE: 'depthTextureCompare'
  1509. };
  1510. /**
  1511. * This type represents mouse buttons and interaction types in context of controls.
  1512. *
  1513. * @typedef {Object} ConstantsMouse
  1514. * @property {number} MIDDLE - The left mouse button.
  1515. * @property {number} LEFT - The middle mouse button.
  1516. * @property {number} RIGHT - The right mouse button.
  1517. * @property {number} ROTATE - A rotate interaction.
  1518. * @property {number} DOLLY - A dolly interaction.
  1519. * @property {number} PAN - A pan interaction.
  1520. **/
  1521. /**
  1522. * This type represents touch interaction types in context of controls.
  1523. *
  1524. * @typedef {Object} ConstantsTouch
  1525. * @property {number} ROTATE - A rotate interaction.
  1526. * @property {number} PAN - A pan interaction.
  1527. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1528. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1529. **/
  1530. /**
  1531. * This type represents the different timestamp query types.
  1532. *
  1533. * @typedef {Object} ConstantsTimestampQuery
  1534. * @property {string} COMPUTE - A `compute` timestamp query.
  1535. * @property {string} RENDER - A `render` timestamp query.
  1536. **/
  1537. /**
  1538. * Represents the different interpolation sampling types.
  1539. *
  1540. * @typedef {Object} ConstantsInterpolationSamplingType
  1541. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1542. * @property {string} LINEAR - Linear interpolation.
  1543. * @property {string} FLAT - Flat interpolation.
  1544. */
  1545. /**
  1546. * Represents the different interpolation sampling modes.
  1547. *
  1548. * @typedef {Object} ConstantsInterpolationSamplingMode
  1549. * @property {string} NORMAL - Normal sampling mode.
  1550. * @property {string} CENTROID - Centroid sampling mode.
  1551. * @property {string} SAMPLE - Sample-specific sampling mode.
  1552. * @property {string} FIRST - Flat interpolation using the first vertex.
  1553. * @property {string} EITHER - Flat interpolation using either vertex.
  1554. */
  1555. /**
  1556. * Checks if an array contains values that require Uint32 representation.
  1557. *
  1558. * This function determines whether the array contains any values >= 65535,
  1559. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1560. * The function iterates from the end of the array, assuming larger values are
  1561. * typically located at the end.
  1562. *
  1563. * @private
  1564. * @param {Array<number>} array - The array to check.
  1565. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1566. */
  1567. function arrayNeedsUint32( array ) {
  1568. // assumes larger values usually on last
  1569. for ( let i = array.length - 1; i >= 0; -- i ) {
  1570. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1571. }
  1572. return false;
  1573. }
  1574. /**
  1575. * Map of typed array constructor names to their constructors.
  1576. * This mapping enables dynamic creation of typed arrays based on string type names.
  1577. *
  1578. * @private
  1579. * @constant
  1580. * @type {Object<string, TypedArrayConstructor>}
  1581. */
  1582. const TYPED_ARRAYS = {
  1583. Int8Array: Int8Array,
  1584. Uint8Array: Uint8Array,
  1585. Uint8ClampedArray: Uint8ClampedArray,
  1586. Int16Array: Int16Array,
  1587. Uint16Array: Uint16Array,
  1588. Int32Array: Int32Array,
  1589. Uint32Array: Uint32Array,
  1590. Float32Array: Float32Array,
  1591. Float64Array: Float64Array
  1592. };
  1593. /**
  1594. * Creates a typed array of the specified type from the given buffer.
  1595. *
  1596. * @private
  1597. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1598. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1599. * @return {TypedArray} A new typed array of the specified type.
  1600. */
  1601. function getTypedArray( type, buffer ) {
  1602. return new TYPED_ARRAYS[ type ]( buffer );
  1603. }
  1604. /**
  1605. * Returns `true` if the given object is a typed array.
  1606. *
  1607. * @param {any} array - The object to check.
  1608. * @return {boolean} Whether the given object is a typed array.
  1609. */
  1610. function isTypedArray( array ) {
  1611. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1612. }
  1613. /**
  1614. * Creates an XHTML element with the specified tag name.
  1615. *
  1616. * This function uses the XHTML namespace to create DOM elements,
  1617. * ensuring proper element creation in XML-based contexts.
  1618. *
  1619. * @private
  1620. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1621. * @return {HTMLElement} The created XHTML element.
  1622. */
  1623. function createElementNS( name ) {
  1624. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1625. }
  1626. /**
  1627. * Creates a canvas element configured for block display.
  1628. *
  1629. * This is a convenience function that creates a canvas element with
  1630. * display style set to 'block', which is commonly used in three.js
  1631. * rendering contexts to avoid inline element spacing issues.
  1632. *
  1633. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1634. */
  1635. function createCanvasElement() {
  1636. const canvas = createElementNS( 'canvas' );
  1637. canvas.style.display = 'block';
  1638. return canvas;
  1639. }
  1640. /**
  1641. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1642. *
  1643. * @private
  1644. * @type {Object<string, boolean>}
  1645. */
  1646. const _cache = {};
  1647. /**
  1648. * Custom console function handler for intercepting log, warn, and error calls.
  1649. *
  1650. * @private
  1651. * @type {Function|null}
  1652. */
  1653. let _setConsoleFunction = null;
  1654. /**
  1655. * Sets a custom function to handle console output.
  1656. *
  1657. * This allows external code to intercept and handle console.log, console.warn,
  1658. * and console.error calls made by three.js, which is useful for custom logging,
  1659. * testing, or debugging workflows.
  1660. *
  1661. * @param {Function} fn - The function to handle console output. Should accept
  1662. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1663. */
  1664. function setConsoleFunction( fn ) {
  1665. _setConsoleFunction = fn;
  1666. }
  1667. /**
  1668. * Gets the currently set custom console function.
  1669. *
  1670. * @return {Function|null} The custom console function, or null if not set.
  1671. */
  1672. function getConsoleFunction() {
  1673. return _setConsoleFunction;
  1674. }
  1675. /**
  1676. * Logs an informational message with the 'THREE.' prefix.
  1677. *
  1678. * If a custom console function is set via setConsoleFunction(), it will be used
  1679. * instead of the native console.log. The first parameter is treated as the
  1680. * method name and is automatically prefixed with 'THREE.'.
  1681. *
  1682. * @param {...any} params - The message components. The first param is used as
  1683. * the method name and prefixed with 'THREE.'.
  1684. */
  1685. function log( ...params ) {
  1686. const message = 'THREE.' + params.shift();
  1687. if ( _setConsoleFunction ) {
  1688. _setConsoleFunction( 'log', message, ...params );
  1689. } else {
  1690. console.log( message, ...params );
  1691. }
  1692. }
  1693. /**
  1694. * Enhances log/warn/error messages related to TSL.
  1695. *
  1696. * @param {Array<any>} params - The original message parameters.
  1697. * @returns {Array<any>} The filtered and enhanced message parameters.
  1698. */
  1699. function enhanceLogMessage( params ) {
  1700. const message = params[ 0 ];
  1701. if ( typeof message === 'string' && message.startsWith( 'TSL:' ) ) {
  1702. const stackTrace = params[ 1 ];
  1703. if ( stackTrace && stackTrace.isStackTrace ) {
  1704. params[ 0 ] += ' ' + stackTrace.getLocation();
  1705. } else {
  1706. params[ 1 ] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.';
  1707. }
  1708. }
  1709. return params;
  1710. }
  1711. /**
  1712. * Logs a warning message with the 'THREE.' prefix.
  1713. *
  1714. * If a custom console function is set via setConsoleFunction(), it will be used
  1715. * instead of the native console.warn. The first parameter is treated as the
  1716. * method name and is automatically prefixed with 'THREE.'.
  1717. *
  1718. * @param {...any} params - The message components. The first param is used as
  1719. * the method name and prefixed with 'THREE.'.
  1720. */
  1721. function warn( ...params ) {
  1722. params = enhanceLogMessage( params );
  1723. const message = 'THREE.' + params.shift();
  1724. if ( _setConsoleFunction ) {
  1725. _setConsoleFunction( 'warn', message, ...params );
  1726. } else {
  1727. const stackTrace = params[ 0 ];
  1728. if ( stackTrace && stackTrace.isStackTrace ) {
  1729. console.warn( stackTrace.getError( message ) );
  1730. } else {
  1731. console.warn( message, ...params );
  1732. }
  1733. }
  1734. }
  1735. /**
  1736. * Logs an error message with the 'THREE.' prefix.
  1737. *
  1738. * If a custom console function is set via setConsoleFunction(), it will be used
  1739. * instead of the native console.error. The first parameter is treated as the
  1740. * method name and is automatically prefixed with 'THREE.'.
  1741. *
  1742. * @param {...any} params - The message components. The first param is used as
  1743. * the method name and prefixed with 'THREE.'.
  1744. */
  1745. function error( ...params ) {
  1746. params = enhanceLogMessage( params );
  1747. const message = 'THREE.' + params.shift();
  1748. if ( _setConsoleFunction ) {
  1749. _setConsoleFunction( 'error', message, ...params );
  1750. } else {
  1751. const stackTrace = params[ 0 ];
  1752. if ( stackTrace && stackTrace.isStackTrace ) {
  1753. console.error( stackTrace.getError( message ) );
  1754. } else {
  1755. console.error( message, ...params );
  1756. }
  1757. }
  1758. }
  1759. /**
  1760. * Logs a warning message only once, preventing duplicate warnings.
  1761. *
  1762. * This function maintains an internal cache of warning messages and will only
  1763. * output each unique warning message once. Useful for warnings that may be
  1764. * triggered repeatedly but should only be shown to the user once.
  1765. *
  1766. * @param {...any} params - The warning message components.
  1767. */
  1768. function warnOnce( ...params ) {
  1769. const message = params.join( ' ' );
  1770. if ( message in _cache ) return;
  1771. _cache[ message ] = true;
  1772. warn( ...params );
  1773. }
  1774. /**
  1775. * Asynchronously probes for WebGL sync object completion.
  1776. *
  1777. * This function creates a promise that resolves when the WebGL sync object
  1778. * signals completion or rejects if the sync operation fails. It uses polling
  1779. * at the specified interval to check the sync status without blocking the
  1780. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1781. *
  1782. * @private
  1783. * @param {WebGL2RenderingContext} gl - The WebGL rendering context.
  1784. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1785. * @param {number} interval - The polling interval in milliseconds.
  1786. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1787. */
  1788. function probeAsync( gl, sync, interval ) {
  1789. return new Promise( function ( resolve, reject ) {
  1790. function probe() {
  1791. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1792. case gl.WAIT_FAILED:
  1793. reject();
  1794. break;
  1795. case gl.TIMEOUT_EXPIRED:
  1796. setTimeout( probe, interval );
  1797. break;
  1798. default:
  1799. resolve();
  1800. }
  1801. }
  1802. setTimeout( probe, interval );
  1803. } );
  1804. }
  1805. /**
  1806. * Used to select the correct depth functions
  1807. * when reversed depth buffer is used.
  1808. *
  1809. * @private
  1810. * @type {Object}
  1811. */
  1812. const ReversedDepthFuncs = {
  1813. [ NeverDepth ]: AlwaysDepth,
  1814. [ LessDepth ]: GreaterDepth,
  1815. [ EqualDepth ]: NotEqualDepth,
  1816. [ LessEqualDepth ]: GreaterEqualDepth,
  1817. [ AlwaysDepth ]: NeverDepth,
  1818. [ GreaterDepth ]: LessDepth,
  1819. [ NotEqualDepth ]: EqualDepth,
  1820. [ GreaterEqualDepth ]: LessEqualDepth,
  1821. };
  1822. /**
  1823. * This modules allows to dispatch event objects on custom JavaScript objects.
  1824. *
  1825. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1826. *
  1827. * Code Example:
  1828. * ```js
  1829. * class Car extends EventDispatcher {
  1830. * start() {
  1831. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1832. * }
  1833. *};
  1834. *
  1835. * // Using events with the custom object
  1836. * const car = new Car();
  1837. * car.addEventListener( 'start', function ( event ) {
  1838. * alert( event.message );
  1839. * } );
  1840. *
  1841. * car.start();
  1842. * ```
  1843. */
  1844. class EventDispatcher {
  1845. /**
  1846. * Adds the given event listener to the given event type.
  1847. *
  1848. * @param {string} type - The type of event to listen to.
  1849. * @param {Function} listener - The function that gets called when the event is fired.
  1850. */
  1851. addEventListener( type, listener ) {
  1852. if ( this._listeners === undefined ) this._listeners = {};
  1853. const listeners = this._listeners;
  1854. if ( listeners[ type ] === undefined ) {
  1855. listeners[ type ] = [];
  1856. }
  1857. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1858. listeners[ type ].push( listener );
  1859. }
  1860. }
  1861. /**
  1862. * Returns `true` if the given event listener has been added to the given event type.
  1863. *
  1864. * @param {string} type - The type of event.
  1865. * @param {Function} listener - The listener to check.
  1866. * @return {boolean} Whether the given event listener has been added to the given event type.
  1867. */
  1868. hasEventListener( type, listener ) {
  1869. const listeners = this._listeners;
  1870. if ( listeners === undefined ) return false;
  1871. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1872. }
  1873. /**
  1874. * Removes the given event listener from the given event type.
  1875. *
  1876. * @param {string} type - The type of event.
  1877. * @param {Function} listener - The listener to remove.
  1878. */
  1879. removeEventListener( type, listener ) {
  1880. const listeners = this._listeners;
  1881. if ( listeners === undefined ) return;
  1882. const listenerArray = listeners[ type ];
  1883. if ( listenerArray !== undefined ) {
  1884. const index = listenerArray.indexOf( listener );
  1885. if ( index !== -1 ) {
  1886. listenerArray.splice( index, 1 );
  1887. }
  1888. }
  1889. }
  1890. /**
  1891. * Dispatches an event object.
  1892. *
  1893. * @param {Object} event - The event that gets fired.
  1894. */
  1895. dispatchEvent( event ) {
  1896. const listeners = this._listeners;
  1897. if ( listeners === undefined ) return;
  1898. const listenerArray = listeners[ event.type ];
  1899. if ( listenerArray !== undefined ) {
  1900. event.target = this;
  1901. // Make a copy, in case listeners are removed while iterating.
  1902. const array = listenerArray.slice( 0 );
  1903. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1904. array[ i ].call( this, event );
  1905. }
  1906. event.target = null;
  1907. }
  1908. }
  1909. }
  1910. 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' ];
  1911. let _seed = 1234567;
  1912. const DEG2RAD = Math.PI / 180;
  1913. const RAD2DEG = 180 / Math.PI;
  1914. /**
  1915. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1916. * (universally unique identifier).
  1917. *
  1918. * @return {string} The UUID.
  1919. */
  1920. function generateUUID() {
  1921. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1922. const d0 = Math.random() * 0xffffffff | 0;
  1923. const d1 = Math.random() * 0xffffffff | 0;
  1924. const d2 = Math.random() * 0xffffffff | 0;
  1925. const d3 = Math.random() * 0xffffffff | 0;
  1926. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1927. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1928. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1929. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1930. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1931. return uuid.toLowerCase();
  1932. }
  1933. /**
  1934. * Clamps the given value between min and max.
  1935. *
  1936. * @param {number} value - The value to clamp.
  1937. * @param {number} min - The min value.
  1938. * @param {number} max - The max value.
  1939. * @return {number} The clamped value.
  1940. */
  1941. function clamp( value, min, max ) {
  1942. return Math.max( min, Math.min( max, value ) );
  1943. }
  1944. /**
  1945. * Computes the Euclidean modulo of the given parameters that
  1946. * is `( ( n % m ) + m ) % m`.
  1947. *
  1948. * @param {number} n - The first parameter.
  1949. * @param {number} m - The second parameter.
  1950. * @return {number} The Euclidean modulo.
  1951. */
  1952. function euclideanModulo( n, m ) {
  1953. // https://en.wikipedia.org/wiki/Modulo_operation
  1954. return ( ( n % m ) + m ) % m;
  1955. }
  1956. /**
  1957. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1958. * for the given value. `a2` must be greater than `a1`.
  1959. *
  1960. * @param {number} x - The value to be mapped.
  1961. * @param {number} a1 - Minimum value for range A.
  1962. * @param {number} a2 - Maximum value for range A.
  1963. * @param {number} b1 - Minimum value for range B.
  1964. * @param {number} b2 - Maximum value for range B.
  1965. * @return {number} The mapped value.
  1966. */
  1967. function mapLinear( x, a1, a2, b1, b2 ) {
  1968. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1969. }
  1970. /**
  1971. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1972. * between the start and end point.
  1973. *
  1974. * @param {number} x - The start point
  1975. * @param {number} y - The end point.
  1976. * @param {number} value - A value between start and end.
  1977. * @return {number} The interpolation factor.
  1978. */
  1979. function inverseLerp( x, y, value ) {
  1980. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1981. if ( x !== y ) {
  1982. return ( value - x ) / ( y - x );
  1983. } else {
  1984. return 0;
  1985. }
  1986. }
  1987. /**
  1988. * Returns a value linearly interpolated from two known points based on the given interval -
  1989. * `t = 0` will return `x` and `t = 1` will return `y`.
  1990. *
  1991. * @param {number} x - The start point
  1992. * @param {number} y - The end point.
  1993. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1994. * @return {number} The interpolated value.
  1995. */
  1996. function lerp( x, y, t ) {
  1997. return ( 1 - t ) * x + t * y;
  1998. }
  1999. /**
  2000. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2001. * time to maintain frame rate independent movement. For details, see
  2002. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2003. *
  2004. * @param {number} x - The current point.
  2005. * @param {number} y - The target point.
  2006. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2007. * and a lower value will make the movement more gradual.
  2008. * @param {number} dt - Delta time in seconds.
  2009. * @return {number} The interpolated value.
  2010. */
  2011. function damp( x, y, lambda, dt ) {
  2012. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  2013. }
  2014. /**
  2015. * Returns a value that alternates between `0` and the given `length` parameter.
  2016. *
  2017. * @param {number} x - The value to pingpong.
  2018. * @param {number} [length=1] - The positive value the function will pingpong to.
  2019. * @return {number} The alternated value.
  2020. */
  2021. function pingpong( x, length = 1 ) {
  2022. // https://www.desmos.com/calculator/vcsjnyz7x4
  2023. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  2024. }
  2025. /**
  2026. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2027. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2028. * the `min` and `max`.
  2029. *
  2030. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2031. *
  2032. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2033. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2034. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2035. * @return {number} The alternated value.
  2036. */
  2037. function smoothstep( x, min, max ) {
  2038. if ( x <= min ) return 0;
  2039. if ( x >= max ) return 1;
  2040. x = ( x - min ) / ( max - min );
  2041. return x * x * ( 3 - 2 * x );
  2042. }
  2043. /**
  2044. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2045. * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`.
  2046. *
  2047. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2048. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2049. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2050. * @return {number} The alternated value.
  2051. */
  2052. function smootherstep( x, min, max ) {
  2053. if ( x <= min ) return 0;
  2054. if ( x >= max ) return 1;
  2055. x = ( x - min ) / ( max - min );
  2056. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2057. }
  2058. /**
  2059. * Returns a random integer from `<low, high>` interval.
  2060. *
  2061. * @param {number} low - The lower value boundary.
  2062. * @param {number} high - The upper value boundary
  2063. * @return {number} A random integer.
  2064. */
  2065. function randInt( low, high ) {
  2066. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2067. }
  2068. /**
  2069. * Returns a random float from `<low, high>` interval.
  2070. *
  2071. * @param {number} low - The lower value boundary.
  2072. * @param {number} high - The upper value boundary
  2073. * @return {number} A random float.
  2074. */
  2075. function randFloat( low, high ) {
  2076. return low + Math.random() * ( high - low );
  2077. }
  2078. /**
  2079. * Returns a random integer from `<-range/2, range/2>` interval.
  2080. *
  2081. * @param {number} range - Defines the value range.
  2082. * @return {number} A random float.
  2083. */
  2084. function randFloatSpread( range ) {
  2085. return range * ( 0.5 - Math.random() );
  2086. }
  2087. /**
  2088. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2089. *
  2090. * @param {number} [s] - The integer seed.
  2091. * @return {number} A random float.
  2092. */
  2093. function seededRandom( s ) {
  2094. if ( s !== undefined ) _seed = s;
  2095. // Mulberry32 generator
  2096. let t = _seed += 0x6D2B79F5;
  2097. t = Math.imul( t ^ t >>> 15, t | 1 );
  2098. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2099. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2100. }
  2101. /**
  2102. * Converts degrees to radians.
  2103. *
  2104. * @param {number} degrees - A value in degrees.
  2105. * @return {number} The converted value in radians.
  2106. */
  2107. function degToRad( degrees ) {
  2108. return degrees * DEG2RAD;
  2109. }
  2110. /**
  2111. * Converts radians to degrees.
  2112. *
  2113. * @param {number} radians - A value in radians.
  2114. * @return {number} The converted value in degrees.
  2115. */
  2116. function radToDeg( radians ) {
  2117. return radians * RAD2DEG;
  2118. }
  2119. /**
  2120. * Returns `true` if the given number is a power of two.
  2121. *
  2122. * @param {number} value - The value to check.
  2123. * @return {boolean} Whether the given number is a power of two or not.
  2124. */
  2125. function isPowerOfTwo( value ) {
  2126. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2127. }
  2128. /**
  2129. * Returns the smallest power of two that is greater than or equal to the given number.
  2130. *
  2131. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2132. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2133. */
  2134. function ceilPowerOfTwo( value ) {
  2135. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2136. }
  2137. /**
  2138. * Returns the largest power of two that is less than or equal to the given number.
  2139. *
  2140. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2141. * @return {number} The largest power of two that is less than or equal to the given number.
  2142. */
  2143. function floorPowerOfTwo( value ) {
  2144. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2145. }
  2146. /**
  2147. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2148. * defined by the given angles and order.
  2149. *
  2150. * Rotations are applied to the axes in the order specified by order:
  2151. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2152. *
  2153. * @param {Quaternion} q - The quaternion to set.
  2154. * @param {number} a - The rotation applied to the first axis, in radians.
  2155. * @param {number} b - The rotation applied to the second axis, in radians.
  2156. * @param {number} c - The rotation applied to the third axis, in radians.
  2157. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2158. */
  2159. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2160. const cos = Math.cos;
  2161. const sin = Math.sin;
  2162. const c2 = cos( b / 2 );
  2163. const s2 = sin( b / 2 );
  2164. const c13 = cos( ( a + c ) / 2 );
  2165. const s13 = sin( ( a + c ) / 2 );
  2166. const c1_3 = cos( ( a - c ) / 2 );
  2167. const s1_3 = sin( ( a - c ) / 2 );
  2168. const c3_1 = cos( ( c - a ) / 2 );
  2169. const s3_1 = sin( ( c - a ) / 2 );
  2170. switch ( order ) {
  2171. case 'XYX':
  2172. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2173. break;
  2174. case 'YZY':
  2175. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2176. break;
  2177. case 'ZXZ':
  2178. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2179. break;
  2180. case 'XZX':
  2181. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2182. break;
  2183. case 'YXY':
  2184. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2185. break;
  2186. case 'ZYZ':
  2187. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2188. break;
  2189. default:
  2190. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2191. }
  2192. }
  2193. /**
  2194. * Denormalizes the given value according to the given typed array.
  2195. *
  2196. * @param {number} value - The value to denormalize.
  2197. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2198. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2199. */
  2200. function denormalize( value, array ) {
  2201. switch ( array.constructor ) {
  2202. case Float32Array:
  2203. return value;
  2204. case Uint32Array:
  2205. return value / 4294967295.0;
  2206. case Uint16Array:
  2207. return value / 65535.0;
  2208. case Uint8Array:
  2209. return value / 255.0;
  2210. case Int32Array:
  2211. return Math.max( value / 2147483647.0, -1 );
  2212. case Int16Array:
  2213. return Math.max( value / 32767.0, -1 );
  2214. case Int8Array:
  2215. return Math.max( value / 127.0, -1 );
  2216. default:
  2217. throw new Error( 'Invalid component type.' );
  2218. }
  2219. }
  2220. /**
  2221. * Normalizes the given value according to the given typed array.
  2222. *
  2223. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2224. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2225. * @return {number} The normalize value.
  2226. */
  2227. function normalize( value, array ) {
  2228. switch ( array.constructor ) {
  2229. case Float32Array:
  2230. return value;
  2231. case Uint32Array:
  2232. return Math.round( value * 4294967295.0 );
  2233. case Uint16Array:
  2234. return Math.round( value * 65535.0 );
  2235. case Uint8Array:
  2236. return Math.round( value * 255.0 );
  2237. case Int32Array:
  2238. return Math.round( value * 2147483647.0 );
  2239. case Int16Array:
  2240. return Math.round( value * 32767.0 );
  2241. case Int8Array:
  2242. return Math.round( value * 127.0 );
  2243. default:
  2244. throw new Error( 'Invalid component type.' );
  2245. }
  2246. }
  2247. /**
  2248. * @class
  2249. * @classdesc A collection of math utility functions.
  2250. * @hideconstructor
  2251. */
  2252. const MathUtils = {
  2253. DEG2RAD: DEG2RAD,
  2254. RAD2DEG: RAD2DEG,
  2255. /**
  2256. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2257. * (universally unique identifier).
  2258. *
  2259. * @static
  2260. * @method
  2261. * @return {string} The UUID.
  2262. */
  2263. generateUUID: generateUUID,
  2264. /**
  2265. * Clamps the given value between min and max.
  2266. *
  2267. * @static
  2268. * @method
  2269. * @param {number} value - The value to clamp.
  2270. * @param {number} min - The min value.
  2271. * @param {number} max - The max value.
  2272. * @return {number} The clamped value.
  2273. */
  2274. clamp: clamp,
  2275. /**
  2276. * Computes the Euclidean modulo of the given parameters that
  2277. * is `( ( n % m ) + m ) % m`.
  2278. *
  2279. * @static
  2280. * @method
  2281. * @param {number} n - The first parameter.
  2282. * @param {number} m - The second parameter.
  2283. * @return {number} The Euclidean modulo.
  2284. */
  2285. euclideanModulo: euclideanModulo,
  2286. /**
  2287. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2288. * for the given value.
  2289. *
  2290. * @static
  2291. * @method
  2292. * @param {number} x - The value to be mapped.
  2293. * @param {number} a1 - Minimum value for range A.
  2294. * @param {number} a2 - Maximum value for range A.
  2295. * @param {number} b1 - Minimum value for range B.
  2296. * @param {number} b2 - Maximum value for range B.
  2297. * @return {number} The mapped value.
  2298. */
  2299. mapLinear: mapLinear,
  2300. /**
  2301. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2302. * between the start and end point.
  2303. *
  2304. * @static
  2305. * @method
  2306. * @param {number} x - The start point
  2307. * @param {number} y - The end point.
  2308. * @param {number} value - A value between start and end.
  2309. * @return {number} The interpolation factor.
  2310. */
  2311. inverseLerp: inverseLerp,
  2312. /**
  2313. * Returns a value linearly interpolated from two known points based on the given interval -
  2314. * `t = 0` will return `x` and `t = 1` will return `y`.
  2315. *
  2316. * @static
  2317. * @method
  2318. * @param {number} x - The start point
  2319. * @param {number} y - The end point.
  2320. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2321. * @return {number} The interpolated value.
  2322. */
  2323. lerp: lerp,
  2324. /**
  2325. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2326. * time to maintain frame rate independent movement. For details, see
  2327. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2328. *
  2329. * @static
  2330. * @method
  2331. * @param {number} x - The current point.
  2332. * @param {number} y - The target point.
  2333. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2334. * and a lower value will make the movement more gradual.
  2335. * @param {number} dt - Delta time in seconds.
  2336. * @return {number} The interpolated value.
  2337. */
  2338. damp: damp,
  2339. /**
  2340. * Returns a value that alternates between `0` and the given `length` parameter.
  2341. *
  2342. * @static
  2343. * @method
  2344. * @param {number} x - The value to pingpong.
  2345. * @param {number} [length=1] - The positive value the function will pingpong to.
  2346. * @return {number} The alternated value.
  2347. */
  2348. pingpong: pingpong,
  2349. /**
  2350. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2351. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2352. * the `min` and `max`.
  2353. *
  2354. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2355. *
  2356. * @static
  2357. * @method
  2358. * @param {number} x - The value to evaluate based on its position between min and max.
  2359. * @param {number} min - The min value. Any x value below min will be `0`.
  2360. * @param {number} max - The max value. Any x value above max will be `1`.
  2361. * @return {number} The alternated value.
  2362. */
  2363. smoothstep: smoothstep,
  2364. /**
  2365. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2366. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2367. *
  2368. * @static
  2369. * @method
  2370. * @param {number} x - The value to evaluate based on its position between min and max.
  2371. * @param {number} min - The min value. Any x value below min will be `0`.
  2372. * @param {number} max - The max value. Any x value above max will be `1`.
  2373. * @return {number} The alternated value.
  2374. */
  2375. smootherstep: smootherstep,
  2376. /**
  2377. * Returns a random integer from `<low, high>` interval.
  2378. *
  2379. * @static
  2380. * @method
  2381. * @param {number} low - The lower value boundary.
  2382. * @param {number} high - The upper value boundary
  2383. * @return {number} A random integer.
  2384. */
  2385. randInt: randInt,
  2386. /**
  2387. * Returns a random float from `<low, high>` interval.
  2388. *
  2389. * @static
  2390. * @method
  2391. * @param {number} low - The lower value boundary.
  2392. * @param {number} high - The upper value boundary
  2393. * @return {number} A random float.
  2394. */
  2395. randFloat: randFloat,
  2396. /**
  2397. * Returns a random integer from `<-range/2, range/2>` interval.
  2398. *
  2399. * @static
  2400. * @method
  2401. * @param {number} range - Defines the value range.
  2402. * @return {number} A random float.
  2403. */
  2404. randFloatSpread: randFloatSpread,
  2405. /**
  2406. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2407. *
  2408. * @static
  2409. * @method
  2410. * @param {number} [s] - The integer seed.
  2411. * @return {number} A random float.
  2412. */
  2413. seededRandom: seededRandom,
  2414. /**
  2415. * Converts degrees to radians.
  2416. *
  2417. * @static
  2418. * @method
  2419. * @param {number} degrees - A value in degrees.
  2420. * @return {number} The converted value in radians.
  2421. */
  2422. degToRad: degToRad,
  2423. /**
  2424. * Converts radians to degrees.
  2425. *
  2426. * @static
  2427. * @method
  2428. * @param {number} radians - A value in radians.
  2429. * @return {number} The converted value in degrees.
  2430. */
  2431. radToDeg: radToDeg,
  2432. /**
  2433. * Returns `true` if the given number is a power of two.
  2434. *
  2435. * @static
  2436. * @method
  2437. * @param {number} value - The value to check.
  2438. * @return {boolean} Whether the given number is a power of two or not.
  2439. */
  2440. isPowerOfTwo: isPowerOfTwo,
  2441. /**
  2442. * Returns the smallest power of two that is greater than or equal to the given number.
  2443. *
  2444. * @static
  2445. * @method
  2446. * @param {number} value - The value to find a POT for.
  2447. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2448. */
  2449. ceilPowerOfTwo: ceilPowerOfTwo,
  2450. /**
  2451. * Returns the largest power of two that is less than or equal to the given number.
  2452. *
  2453. * @static
  2454. * @method
  2455. * @param {number} value - The value to find a POT for.
  2456. * @return {number} The largest power of two that is less than or equal to the given number.
  2457. */
  2458. floorPowerOfTwo: floorPowerOfTwo,
  2459. /**
  2460. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2461. * defined by the given angles and order.
  2462. *
  2463. * Rotations are applied to the axes in the order specified by order:
  2464. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2465. *
  2466. * @static
  2467. * @method
  2468. * @param {Quaternion} q - The quaternion to set.
  2469. * @param {number} a - The rotation applied to the first axis, in radians.
  2470. * @param {number} b - The rotation applied to the second axis, in radians.
  2471. * @param {number} c - The rotation applied to the third axis, in radians.
  2472. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2473. */
  2474. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2475. /**
  2476. * Normalizes the given value according to the given typed array.
  2477. *
  2478. * @static
  2479. * @method
  2480. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2481. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2482. * @return {number} The normalize value.
  2483. */
  2484. normalize: normalize,
  2485. /**
  2486. * Denormalizes the given value according to the given typed array.
  2487. *
  2488. * @static
  2489. * @method
  2490. * @param {number} value - The value to denormalize.
  2491. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2492. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2493. */
  2494. denormalize: denormalize
  2495. };
  2496. /**
  2497. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2498. * (labeled x and y), which can be used to represent a number of things, such as:
  2499. *
  2500. * - A point in 2D space (i.e. a position on a plane).
  2501. * - A direction and length across a plane. In three.js the length will
  2502. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2503. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2504. * - Any arbitrary ordered pair of numbers.
  2505. *
  2506. * There are other things a 2D vector can be used to represent, such as
  2507. * momentum vectors, complex numbers and so on, however these are the most
  2508. * common uses in three.js.
  2509. *
  2510. * Iterating through a vector instance will yield its components `(x, y)` in
  2511. * the corresponding order.
  2512. * ```js
  2513. * const a = new THREE.Vector2( 0, 1 );
  2514. *
  2515. * //no arguments; will be initialised to (0, 0)
  2516. * const b = new THREE.Vector2( );
  2517. *
  2518. * const d = a.distanceTo( b );
  2519. * ```
  2520. */
  2521. class Vector2 {
  2522. /**
  2523. * Constructs a new 2D vector.
  2524. *
  2525. * @param {number} [x=0] - The x value of this vector.
  2526. * @param {number} [y=0] - The y value of this vector.
  2527. */
  2528. constructor( x = 0, y = 0 ) {
  2529. /**
  2530. * This flag can be used for type testing.
  2531. *
  2532. * @type {boolean}
  2533. * @readonly
  2534. * @default true
  2535. */
  2536. Vector2.prototype.isVector2 = true;
  2537. /**
  2538. * The x value of this vector.
  2539. *
  2540. * @type {number}
  2541. */
  2542. this.x = x;
  2543. /**
  2544. * The y value of this vector.
  2545. *
  2546. * @type {number}
  2547. */
  2548. this.y = y;
  2549. }
  2550. /**
  2551. * Alias for {@link Vector2#x}.
  2552. *
  2553. * @type {number}
  2554. */
  2555. get width() {
  2556. return this.x;
  2557. }
  2558. set width( value ) {
  2559. this.x = value;
  2560. }
  2561. /**
  2562. * Alias for {@link Vector2#y}.
  2563. *
  2564. * @type {number}
  2565. */
  2566. get height() {
  2567. return this.y;
  2568. }
  2569. set height( value ) {
  2570. this.y = value;
  2571. }
  2572. /**
  2573. * Sets the vector components.
  2574. *
  2575. * @param {number} x - The value of the x component.
  2576. * @param {number} y - The value of the y component.
  2577. * @return {Vector2} A reference to this vector.
  2578. */
  2579. set( x, y ) {
  2580. this.x = x;
  2581. this.y = y;
  2582. return this;
  2583. }
  2584. /**
  2585. * Sets the vector components to the same value.
  2586. *
  2587. * @param {number} scalar - The value to set for all vector components.
  2588. * @return {Vector2} A reference to this vector.
  2589. */
  2590. setScalar( scalar ) {
  2591. this.x = scalar;
  2592. this.y = scalar;
  2593. return this;
  2594. }
  2595. /**
  2596. * Sets the vector's x component to the given value
  2597. *
  2598. * @param {number} x - The value to set.
  2599. * @return {Vector2} A reference to this vector.
  2600. */
  2601. setX( x ) {
  2602. this.x = x;
  2603. return this;
  2604. }
  2605. /**
  2606. * Sets the vector's y component to the given value
  2607. *
  2608. * @param {number} y - The value to set.
  2609. * @return {Vector2} A reference to this vector.
  2610. */
  2611. setY( y ) {
  2612. this.y = y;
  2613. return this;
  2614. }
  2615. /**
  2616. * Allows to set a vector component with an index.
  2617. *
  2618. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2619. * @param {number} value - The value to set.
  2620. * @return {Vector2} A reference to this vector.
  2621. */
  2622. setComponent( index, value ) {
  2623. switch ( index ) {
  2624. case 0: this.x = value; break;
  2625. case 1: this.y = value; break;
  2626. default: throw new Error( 'index is out of range: ' + index );
  2627. }
  2628. return this;
  2629. }
  2630. /**
  2631. * Returns the value of the vector component which matches the given index.
  2632. *
  2633. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2634. * @return {number} A vector component value.
  2635. */
  2636. getComponent( index ) {
  2637. switch ( index ) {
  2638. case 0: return this.x;
  2639. case 1: return this.y;
  2640. default: throw new Error( 'index is out of range: ' + index );
  2641. }
  2642. }
  2643. /**
  2644. * Returns a new vector with copied values from this instance.
  2645. *
  2646. * @return {Vector2} A clone of this instance.
  2647. */
  2648. clone() {
  2649. return new this.constructor( this.x, this.y );
  2650. }
  2651. /**
  2652. * Copies the values of the given vector to this instance.
  2653. *
  2654. * @param {Vector2} v - The vector to copy.
  2655. * @return {Vector2} A reference to this vector.
  2656. */
  2657. copy( v ) {
  2658. this.x = v.x;
  2659. this.y = v.y;
  2660. return this;
  2661. }
  2662. /**
  2663. * Adds the given vector to this instance.
  2664. *
  2665. * @param {Vector2} v - The vector to add.
  2666. * @return {Vector2} A reference to this vector.
  2667. */
  2668. add( v ) {
  2669. this.x += v.x;
  2670. this.y += v.y;
  2671. return this;
  2672. }
  2673. /**
  2674. * Adds the given scalar value to all components of this instance.
  2675. *
  2676. * @param {number} s - The scalar to add.
  2677. * @return {Vector2} A reference to this vector.
  2678. */
  2679. addScalar( s ) {
  2680. this.x += s;
  2681. this.y += s;
  2682. return this;
  2683. }
  2684. /**
  2685. * Adds the given vectors and stores the result in this instance.
  2686. *
  2687. * @param {Vector2} a - The first vector.
  2688. * @param {Vector2} b - The second vector.
  2689. * @return {Vector2} A reference to this vector.
  2690. */
  2691. addVectors( a, b ) {
  2692. this.x = a.x + b.x;
  2693. this.y = a.y + b.y;
  2694. return this;
  2695. }
  2696. /**
  2697. * Adds the given vector scaled by the given factor to this instance.
  2698. *
  2699. * @param {Vector2} v - The vector.
  2700. * @param {number} s - The factor that scales `v`.
  2701. * @return {Vector2} A reference to this vector.
  2702. */
  2703. addScaledVector( v, s ) {
  2704. this.x += v.x * s;
  2705. this.y += v.y * s;
  2706. return this;
  2707. }
  2708. /**
  2709. * Subtracts the given vector from this instance.
  2710. *
  2711. * @param {Vector2} v - The vector to subtract.
  2712. * @return {Vector2} A reference to this vector.
  2713. */
  2714. sub( v ) {
  2715. this.x -= v.x;
  2716. this.y -= v.y;
  2717. return this;
  2718. }
  2719. /**
  2720. * Subtracts the given scalar value from all components of this instance.
  2721. *
  2722. * @param {number} s - The scalar to subtract.
  2723. * @return {Vector2} A reference to this vector.
  2724. */
  2725. subScalar( s ) {
  2726. this.x -= s;
  2727. this.y -= s;
  2728. return this;
  2729. }
  2730. /**
  2731. * Subtracts the given vectors and stores the result in this instance.
  2732. *
  2733. * @param {Vector2} a - The first vector.
  2734. * @param {Vector2} b - The second vector.
  2735. * @return {Vector2} A reference to this vector.
  2736. */
  2737. subVectors( a, b ) {
  2738. this.x = a.x - b.x;
  2739. this.y = a.y - b.y;
  2740. return this;
  2741. }
  2742. /**
  2743. * Multiplies the given vector with this instance.
  2744. *
  2745. * @param {Vector2} v - The vector to multiply.
  2746. * @return {Vector2} A reference to this vector.
  2747. */
  2748. multiply( v ) {
  2749. this.x *= v.x;
  2750. this.y *= v.y;
  2751. return this;
  2752. }
  2753. /**
  2754. * Multiplies the given scalar value with all components of this instance.
  2755. *
  2756. * @param {number} scalar - The scalar to multiply.
  2757. * @return {Vector2} A reference to this vector.
  2758. */
  2759. multiplyScalar( scalar ) {
  2760. this.x *= scalar;
  2761. this.y *= scalar;
  2762. return this;
  2763. }
  2764. /**
  2765. * Divides this instance by the given vector.
  2766. *
  2767. * @param {Vector2} v - The vector to divide.
  2768. * @return {Vector2} A reference to this vector.
  2769. */
  2770. divide( v ) {
  2771. this.x /= v.x;
  2772. this.y /= v.y;
  2773. return this;
  2774. }
  2775. /**
  2776. * Divides this vector by the given scalar.
  2777. *
  2778. * @param {number} scalar - The scalar to divide.
  2779. * @return {Vector2} A reference to this vector.
  2780. */
  2781. divideScalar( scalar ) {
  2782. return this.multiplyScalar( 1 / scalar );
  2783. }
  2784. /**
  2785. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2786. * the given 3x3 matrix.
  2787. *
  2788. * @param {Matrix3} m - The matrix to apply.
  2789. * @return {Vector2} A reference to this vector.
  2790. */
  2791. applyMatrix3( m ) {
  2792. const x = this.x, y = this.y;
  2793. const e = m.elements;
  2794. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2795. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2796. return this;
  2797. }
  2798. /**
  2799. * If this vector's x or y value is greater than the given vector's x or y
  2800. * value, replace that value with the corresponding min value.
  2801. *
  2802. * @param {Vector2} v - The vector.
  2803. * @return {Vector2} A reference to this vector.
  2804. */
  2805. min( v ) {
  2806. this.x = Math.min( this.x, v.x );
  2807. this.y = Math.min( this.y, v.y );
  2808. return this;
  2809. }
  2810. /**
  2811. * If this vector's x or y value is less than the given vector's x or y
  2812. * value, replace that value with the corresponding max value.
  2813. *
  2814. * @param {Vector2} v - The vector.
  2815. * @return {Vector2} A reference to this vector.
  2816. */
  2817. max( v ) {
  2818. this.x = Math.max( this.x, v.x );
  2819. this.y = Math.max( this.y, v.y );
  2820. return this;
  2821. }
  2822. /**
  2823. * If this vector's x or y value is greater than the max vector's x or y
  2824. * value, it is replaced by the corresponding value.
  2825. * If this vector's x or y value is less than the min vector's x or y value,
  2826. * it is replaced by the corresponding value.
  2827. *
  2828. * @param {Vector2} min - The minimum x and y values.
  2829. * @param {Vector2} max - The maximum x and y values in the desired range.
  2830. * @return {Vector2} A reference to this vector.
  2831. */
  2832. clamp( min, max ) {
  2833. // assumes min < max, componentwise
  2834. this.x = clamp( this.x, min.x, max.x );
  2835. this.y = clamp( this.y, min.y, max.y );
  2836. return this;
  2837. }
  2838. /**
  2839. * If this vector's x or y values are greater than the max value, they are
  2840. * replaced by the max value.
  2841. * If this vector's x or y values are less than the min value, they are
  2842. * replaced by the min value.
  2843. *
  2844. * @param {number} minVal - The minimum value the components will be clamped to.
  2845. * @param {number} maxVal - The maximum value the components will be clamped to.
  2846. * @return {Vector2} A reference to this vector.
  2847. */
  2848. clampScalar( minVal, maxVal ) {
  2849. this.x = clamp( this.x, minVal, maxVal );
  2850. this.y = clamp( this.y, minVal, maxVal );
  2851. return this;
  2852. }
  2853. /**
  2854. * If this vector's length is greater than the max value, it is replaced by
  2855. * the max value.
  2856. * If this vector's length is less than the min value, it is replaced by the
  2857. * min value.
  2858. *
  2859. * @param {number} min - The minimum value the vector length will be clamped to.
  2860. * @param {number} max - The maximum value the vector length will be clamped to.
  2861. * @return {Vector2} A reference to this vector.
  2862. */
  2863. clampLength( min, max ) {
  2864. const length = this.length();
  2865. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2866. }
  2867. /**
  2868. * The components of this vector are rounded down to the nearest integer value.
  2869. *
  2870. * @return {Vector2} A reference to this vector.
  2871. */
  2872. floor() {
  2873. this.x = Math.floor( this.x );
  2874. this.y = Math.floor( this.y );
  2875. return this;
  2876. }
  2877. /**
  2878. * The components of this vector are rounded up to the nearest integer value.
  2879. *
  2880. * @return {Vector2} A reference to this vector.
  2881. */
  2882. ceil() {
  2883. this.x = Math.ceil( this.x );
  2884. this.y = Math.ceil( this.y );
  2885. return this;
  2886. }
  2887. /**
  2888. * The components of this vector are rounded to the nearest integer value
  2889. *
  2890. * @return {Vector2} A reference to this vector.
  2891. */
  2892. round() {
  2893. this.x = Math.round( this.x );
  2894. this.y = Math.round( this.y );
  2895. return this;
  2896. }
  2897. /**
  2898. * The components of this vector are rounded towards zero (up if negative,
  2899. * down if positive) to an integer value.
  2900. *
  2901. * @return {Vector2} A reference to this vector.
  2902. */
  2903. roundToZero() {
  2904. this.x = Math.trunc( this.x );
  2905. this.y = Math.trunc( this.y );
  2906. return this;
  2907. }
  2908. /**
  2909. * Inverts this vector - i.e. sets x = -x and y = -y.
  2910. *
  2911. * @return {Vector2} A reference to this vector.
  2912. */
  2913. negate() {
  2914. this.x = - this.x;
  2915. this.y = - this.y;
  2916. return this;
  2917. }
  2918. /**
  2919. * Calculates the dot product of the given vector with this instance.
  2920. *
  2921. * @param {Vector2} v - The vector to compute the dot product with.
  2922. * @return {number} The result of the dot product.
  2923. */
  2924. dot( v ) {
  2925. return this.x * v.x + this.y * v.y;
  2926. }
  2927. /**
  2928. * Calculates the cross product of the given vector with this instance.
  2929. *
  2930. * @param {Vector2} v - The vector to compute the cross product with.
  2931. * @return {number} The result of the cross product.
  2932. */
  2933. cross( v ) {
  2934. return this.x * v.y - this.y * v.x;
  2935. }
  2936. /**
  2937. * Computes the square of the Euclidean length (straight-line length) from
  2938. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2939. * compare the length squared instead as it is slightly more efficient to calculate.
  2940. *
  2941. * @return {number} The square length of this vector.
  2942. */
  2943. lengthSq() {
  2944. return this.x * this.x + this.y * this.y;
  2945. }
  2946. /**
  2947. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2948. *
  2949. * @return {number} The length of this vector.
  2950. */
  2951. length() {
  2952. return Math.sqrt( this.x * this.x + this.y * this.y );
  2953. }
  2954. /**
  2955. * Computes the Manhattan length of this vector.
  2956. *
  2957. * @return {number} The length of this vector.
  2958. */
  2959. manhattanLength() {
  2960. return Math.abs( this.x ) + Math.abs( this.y );
  2961. }
  2962. /**
  2963. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2964. * with the same direction as this one, but with a vector length of `1`.
  2965. *
  2966. * @return {Vector2} A reference to this vector.
  2967. */
  2968. normalize() {
  2969. return this.divideScalar( this.length() || 1 );
  2970. }
  2971. /**
  2972. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2973. *
  2974. * @return {number} The angle in radians.
  2975. */
  2976. angle() {
  2977. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2978. return angle;
  2979. }
  2980. /**
  2981. * Returns the angle between the given vector and this instance in radians.
  2982. *
  2983. * @param {Vector2} v - The vector to compute the angle with.
  2984. * @return {number} The angle in radians.
  2985. */
  2986. angleTo( v ) {
  2987. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2988. if ( denominator === 0 ) return Math.PI / 2;
  2989. const theta = this.dot( v ) / denominator;
  2990. // clamp, to handle numerical problems
  2991. return Math.acos( clamp( theta, -1, 1 ) );
  2992. }
  2993. /**
  2994. * Computes the distance from the given vector to this instance.
  2995. *
  2996. * @param {Vector2} v - The vector to compute the distance to.
  2997. * @return {number} The distance.
  2998. */
  2999. distanceTo( v ) {
  3000. return Math.sqrt( this.distanceToSquared( v ) );
  3001. }
  3002. /**
  3003. * Computes the squared distance from the given vector to this instance.
  3004. * If you are just comparing the distance with another distance, you should compare
  3005. * the distance squared instead as it is slightly more efficient to calculate.
  3006. *
  3007. * @param {Vector2} v - The vector to compute the squared distance to.
  3008. * @return {number} The squared distance.
  3009. */
  3010. distanceToSquared( v ) {
  3011. const dx = this.x - v.x, dy = this.y - v.y;
  3012. return dx * dx + dy * dy;
  3013. }
  3014. /**
  3015. * Computes the Manhattan distance from the given vector to this instance.
  3016. *
  3017. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  3018. * @return {number} The Manhattan distance.
  3019. */
  3020. manhattanDistanceTo( v ) {
  3021. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  3022. }
  3023. /**
  3024. * Sets this vector to a vector with the same direction as this one, but
  3025. * with the specified length.
  3026. *
  3027. * @param {number} length - The new length of this vector.
  3028. * @return {Vector2} A reference to this vector.
  3029. */
  3030. setLength( length ) {
  3031. return this.normalize().multiplyScalar( length );
  3032. }
  3033. /**
  3034. * Linearly interpolates between the given vector and this instance, where
  3035. * alpha is the percent distance along the line - alpha = 0 will be this
  3036. * vector, and alpha = 1 will be the given one.
  3037. *
  3038. * @param {Vector2} v - The vector to interpolate towards.
  3039. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3040. * @return {Vector2} A reference to this vector.
  3041. */
  3042. lerp( v, alpha ) {
  3043. this.x += ( v.x - this.x ) * alpha;
  3044. this.y += ( v.y - this.y ) * alpha;
  3045. return this;
  3046. }
  3047. /**
  3048. * Linearly interpolates between the given vectors, where alpha is the percent
  3049. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3050. * be the second one. The result is stored in this instance.
  3051. *
  3052. * @param {Vector2} v1 - The first vector.
  3053. * @param {Vector2} v2 - The second vector.
  3054. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3055. * @return {Vector2} A reference to this vector.
  3056. */
  3057. lerpVectors( v1, v2, alpha ) {
  3058. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3059. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3060. return this;
  3061. }
  3062. /**
  3063. * Returns `true` if this vector is equal with the given one.
  3064. *
  3065. * @param {Vector2} v - The vector to test for equality.
  3066. * @return {boolean} Whether this vector is equal with the given one.
  3067. */
  3068. equals( v ) {
  3069. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3070. }
  3071. /**
  3072. * Sets this vector's x value to be `array[ offset ]` and y
  3073. * value to be `array[ offset + 1 ]`.
  3074. *
  3075. * @param {Array<number>} array - An array holding the vector component values.
  3076. * @param {number} [offset=0] - The offset into the array.
  3077. * @return {Vector2} A reference to this vector.
  3078. */
  3079. fromArray( array, offset = 0 ) {
  3080. this.x = array[ offset ];
  3081. this.y = array[ offset + 1 ];
  3082. return this;
  3083. }
  3084. /**
  3085. * Writes the components of this vector to the given array. If no array is provided,
  3086. * the method returns a new instance.
  3087. *
  3088. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3089. * @param {number} [offset=0] - Index of the first element in the array.
  3090. * @return {Array<number>} The vector components.
  3091. */
  3092. toArray( array = [], offset = 0 ) {
  3093. array[ offset ] = this.x;
  3094. array[ offset + 1 ] = this.y;
  3095. return array;
  3096. }
  3097. /**
  3098. * Sets the components of this vector from the given buffer attribute.
  3099. *
  3100. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3101. * @param {number} index - The index into the attribute.
  3102. * @return {Vector2} A reference to this vector.
  3103. */
  3104. fromBufferAttribute( attribute, index ) {
  3105. this.x = attribute.getX( index );
  3106. this.y = attribute.getY( index );
  3107. return this;
  3108. }
  3109. /**
  3110. * Rotates this vector around the given center by the given angle.
  3111. *
  3112. * @param {Vector2} center - The point around which to rotate.
  3113. * @param {number} angle - The angle to rotate, in radians.
  3114. * @return {Vector2} A reference to this vector.
  3115. */
  3116. rotateAround( center, angle ) {
  3117. const c = Math.cos( angle ), s = Math.sin( angle );
  3118. const x = this.x - center.x;
  3119. const y = this.y - center.y;
  3120. this.x = x * c - y * s + center.x;
  3121. this.y = x * s + y * c + center.y;
  3122. return this;
  3123. }
  3124. /**
  3125. * Sets each component of this vector to a pseudo-random value between `0` and
  3126. * `1`, excluding `1`.
  3127. *
  3128. * @return {Vector2} A reference to this vector.
  3129. */
  3130. random() {
  3131. this.x = Math.random();
  3132. this.y = Math.random();
  3133. return this;
  3134. }
  3135. *[ Symbol.iterator ]() {
  3136. yield this.x;
  3137. yield this.y;
  3138. }
  3139. }
  3140. /**
  3141. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3142. *
  3143. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3144. * the corresponding order.
  3145. *
  3146. * Note that three.js expects Quaternions to be normalized.
  3147. * ```js
  3148. * const quaternion = new THREE.Quaternion();
  3149. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3150. *
  3151. * const vector = new THREE.Vector3( 1, 0, 0 );
  3152. * vector.applyQuaternion( quaternion );
  3153. * ```
  3154. */
  3155. class Quaternion {
  3156. /**
  3157. * Constructs a new quaternion.
  3158. *
  3159. * @param {number} [x=0] - The x value of this quaternion.
  3160. * @param {number} [y=0] - The y value of this quaternion.
  3161. * @param {number} [z=0] - The z value of this quaternion.
  3162. * @param {number} [w=1] - The w value of this quaternion.
  3163. */
  3164. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3165. /**
  3166. * This flag can be used for type testing.
  3167. *
  3168. * @type {boolean}
  3169. * @readonly
  3170. * @default true
  3171. */
  3172. this.isQuaternion = true;
  3173. this._x = x;
  3174. this._y = y;
  3175. this._z = z;
  3176. this._w = w;
  3177. }
  3178. /**
  3179. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3180. * quaternion data are managed in flat arrays.
  3181. *
  3182. * @param {Array<number>} dst - The destination array.
  3183. * @param {number} dstOffset - An offset into the destination array.
  3184. * @param {Array<number>} src0 - The source array of the first quaternion.
  3185. * @param {number} srcOffset0 - An offset into the first source array.
  3186. * @param {Array<number>} src1 - The source array of the second quaternion.
  3187. * @param {number} srcOffset1 - An offset into the second source array.
  3188. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3189. * @see {@link Quaternion#slerp}
  3190. */
  3191. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3192. let x0 = src0[ srcOffset0 + 0 ],
  3193. y0 = src0[ srcOffset0 + 1 ],
  3194. z0 = src0[ srcOffset0 + 2 ],
  3195. w0 = src0[ srcOffset0 + 3 ];
  3196. let x1 = src1[ srcOffset1 + 0 ],
  3197. y1 = src1[ srcOffset1 + 1 ],
  3198. z1 = src1[ srcOffset1 + 2 ],
  3199. w1 = src1[ srcOffset1 + 3 ];
  3200. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3201. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3202. if ( dot < 0 ) {
  3203. x1 = - x1;
  3204. y1 = - y1;
  3205. z1 = - z1;
  3206. w1 = - w1;
  3207. dot = - dot;
  3208. }
  3209. let s = 1 - t;
  3210. if ( dot < 0.9995 ) {
  3211. // slerp
  3212. const theta = Math.acos( dot );
  3213. const sin = Math.sin( theta );
  3214. s = Math.sin( s * theta ) / sin;
  3215. t = Math.sin( t * theta ) / sin;
  3216. x0 = x0 * s + x1 * t;
  3217. y0 = y0 * s + y1 * t;
  3218. z0 = z0 * s + z1 * t;
  3219. w0 = w0 * s + w1 * t;
  3220. } else {
  3221. // for small angles, lerp then normalize
  3222. x0 = x0 * s + x1 * t;
  3223. y0 = y0 * s + y1 * t;
  3224. z0 = z0 * s + z1 * t;
  3225. w0 = w0 * s + w1 * t;
  3226. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3227. x0 *= f;
  3228. y0 *= f;
  3229. z0 *= f;
  3230. w0 *= f;
  3231. }
  3232. }
  3233. dst[ dstOffset ] = x0;
  3234. dst[ dstOffset + 1 ] = y0;
  3235. dst[ dstOffset + 2 ] = z0;
  3236. dst[ dstOffset + 3 ] = w0;
  3237. }
  3238. /**
  3239. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3240. * in flat arrays.
  3241. *
  3242. * @param {Array<number>} dst - The destination array.
  3243. * @param {number} dstOffset - An offset into the destination array.
  3244. * @param {Array<number>} src0 - The source array of the first quaternion.
  3245. * @param {number} srcOffset0 - An offset into the first source array.
  3246. * @param {Array<number>} src1 - The source array of the second quaternion.
  3247. * @param {number} srcOffset1 - An offset into the second source array.
  3248. * @return {Array<number>} The destination array.
  3249. * @see {@link Quaternion#multiplyQuaternions}.
  3250. */
  3251. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3252. const x0 = src0[ srcOffset0 ];
  3253. const y0 = src0[ srcOffset0 + 1 ];
  3254. const z0 = src0[ srcOffset0 + 2 ];
  3255. const w0 = src0[ srcOffset0 + 3 ];
  3256. const x1 = src1[ srcOffset1 ];
  3257. const y1 = src1[ srcOffset1 + 1 ];
  3258. const z1 = src1[ srcOffset1 + 2 ];
  3259. const w1 = src1[ srcOffset1 + 3 ];
  3260. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3261. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3262. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3263. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3264. return dst;
  3265. }
  3266. /**
  3267. * The x value of this quaternion.
  3268. *
  3269. * @type {number}
  3270. * @default 0
  3271. */
  3272. get x() {
  3273. return this._x;
  3274. }
  3275. set x( value ) {
  3276. this._x = value;
  3277. this._onChangeCallback();
  3278. }
  3279. /**
  3280. * The y value of this quaternion.
  3281. *
  3282. * @type {number}
  3283. * @default 0
  3284. */
  3285. get y() {
  3286. return this._y;
  3287. }
  3288. set y( value ) {
  3289. this._y = value;
  3290. this._onChangeCallback();
  3291. }
  3292. /**
  3293. * The z value of this quaternion.
  3294. *
  3295. * @type {number}
  3296. * @default 0
  3297. */
  3298. get z() {
  3299. return this._z;
  3300. }
  3301. set z( value ) {
  3302. this._z = value;
  3303. this._onChangeCallback();
  3304. }
  3305. /**
  3306. * The w value of this quaternion.
  3307. *
  3308. * @type {number}
  3309. * @default 1
  3310. */
  3311. get w() {
  3312. return this._w;
  3313. }
  3314. set w( value ) {
  3315. this._w = value;
  3316. this._onChangeCallback();
  3317. }
  3318. /**
  3319. * Sets the quaternion components.
  3320. *
  3321. * @param {number} x - The x value of this quaternion.
  3322. * @param {number} y - The y value of this quaternion.
  3323. * @param {number} z - The z value of this quaternion.
  3324. * @param {number} w - The w value of this quaternion.
  3325. * @return {Quaternion} A reference to this quaternion.
  3326. */
  3327. set( x, y, z, w ) {
  3328. this._x = x;
  3329. this._y = y;
  3330. this._z = z;
  3331. this._w = w;
  3332. this._onChangeCallback();
  3333. return this;
  3334. }
  3335. /**
  3336. * Returns a new quaternion with copied values from this instance.
  3337. *
  3338. * @return {Quaternion} A clone of this instance.
  3339. */
  3340. clone() {
  3341. return new this.constructor( this._x, this._y, this._z, this._w );
  3342. }
  3343. /**
  3344. * Copies the values of the given quaternion to this instance.
  3345. *
  3346. * @param {Quaternion} quaternion - The quaternion to copy.
  3347. * @return {Quaternion} A reference to this quaternion.
  3348. */
  3349. copy( quaternion ) {
  3350. this._x = quaternion.x;
  3351. this._y = quaternion.y;
  3352. this._z = quaternion.z;
  3353. this._w = quaternion.w;
  3354. this._onChangeCallback();
  3355. return this;
  3356. }
  3357. /**
  3358. * Sets this quaternion from the rotation specified by the given
  3359. * Euler angles.
  3360. *
  3361. * @param {Euler} euler - The Euler angles.
  3362. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3363. * @return {Quaternion} A reference to this quaternion.
  3364. */
  3365. setFromEuler( euler, update = true ) {
  3366. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3367. // http://www.mathworks.com/matlabcentral/fileexchange/
  3368. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3369. // content/SpinCalc.m
  3370. const cos = Math.cos;
  3371. const sin = Math.sin;
  3372. const c1 = cos( x / 2 );
  3373. const c2 = cos( y / 2 );
  3374. const c3 = cos( z / 2 );
  3375. const s1 = sin( x / 2 );
  3376. const s2 = sin( y / 2 );
  3377. const s3 = sin( z / 2 );
  3378. switch ( order ) {
  3379. case 'XYZ':
  3380. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3381. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3382. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3383. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3384. break;
  3385. case 'YXZ':
  3386. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3387. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3388. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3389. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3390. break;
  3391. case 'ZXY':
  3392. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3393. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3394. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3395. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3396. break;
  3397. case 'ZYX':
  3398. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3399. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3400. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3401. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3402. break;
  3403. case 'YZX':
  3404. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3405. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3406. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3407. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3408. break;
  3409. case 'XZY':
  3410. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3411. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3412. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3413. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3414. break;
  3415. default:
  3416. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3417. }
  3418. if ( update === true ) this._onChangeCallback();
  3419. return this;
  3420. }
  3421. /**
  3422. * Sets this quaternion from the given axis and angle.
  3423. *
  3424. * @param {Vector3} axis - The normalized axis.
  3425. * @param {number} angle - The angle in radians.
  3426. * @return {Quaternion} A reference to this quaternion.
  3427. */
  3428. setFromAxisAngle( axis, angle ) {
  3429. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3430. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3431. this._x = axis.x * s;
  3432. this._y = axis.y * s;
  3433. this._z = axis.z * s;
  3434. this._w = Math.cos( halfAngle );
  3435. this._onChangeCallback();
  3436. return this;
  3437. }
  3438. /**
  3439. * Sets this quaternion from the given rotation matrix.
  3440. *
  3441. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3442. * @return {Quaternion} A reference to this quaternion.
  3443. */
  3444. setFromRotationMatrix( m ) {
  3445. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3446. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3447. const te = m.elements,
  3448. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3449. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3450. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3451. trace = m11 + m22 + m33;
  3452. if ( trace > 0 ) {
  3453. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3454. this._w = 0.25 / s;
  3455. this._x = ( m32 - m23 ) * s;
  3456. this._y = ( m13 - m31 ) * s;
  3457. this._z = ( m21 - m12 ) * s;
  3458. } else if ( m11 > m22 && m11 > m33 ) {
  3459. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3460. this._w = ( m32 - m23 ) / s;
  3461. this._x = 0.25 * s;
  3462. this._y = ( m12 + m21 ) / s;
  3463. this._z = ( m13 + m31 ) / s;
  3464. } else if ( m22 > m33 ) {
  3465. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3466. this._w = ( m13 - m31 ) / s;
  3467. this._x = ( m12 + m21 ) / s;
  3468. this._y = 0.25 * s;
  3469. this._z = ( m23 + m32 ) / s;
  3470. } else {
  3471. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3472. this._w = ( m21 - m12 ) / s;
  3473. this._x = ( m13 + m31 ) / s;
  3474. this._y = ( m23 + m32 ) / s;
  3475. this._z = 0.25 * s;
  3476. }
  3477. this._onChangeCallback();
  3478. return this;
  3479. }
  3480. /**
  3481. * Sets this quaternion to the rotation required to rotate the direction vector
  3482. * `vFrom` to the direction vector `vTo`.
  3483. *
  3484. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3485. * @param {Vector3} vTo - The second (normalized) direction vector.
  3486. * @return {Quaternion} A reference to this quaternion.
  3487. */
  3488. setFromUnitVectors( vFrom, vTo ) {
  3489. // assumes direction vectors vFrom and vTo are normalized
  3490. let r = vFrom.dot( vTo ) + 1;
  3491. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3492. // vFrom and vTo point in opposite directions
  3493. r = 0;
  3494. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3495. this._x = - vFrom.y;
  3496. this._y = vFrom.x;
  3497. this._z = 0;
  3498. this._w = r;
  3499. } else {
  3500. this._x = 0;
  3501. this._y = - vFrom.z;
  3502. this._z = vFrom.y;
  3503. this._w = r;
  3504. }
  3505. } else {
  3506. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3507. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3508. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3509. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3510. this._w = r;
  3511. }
  3512. return this.normalize();
  3513. }
  3514. /**
  3515. * Returns the angle between this quaternion and the given one in radians.
  3516. *
  3517. * @param {Quaternion} q - The quaternion to compute the angle with.
  3518. * @return {number} The angle in radians.
  3519. */
  3520. angleTo( q ) {
  3521. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3522. }
  3523. /**
  3524. * Rotates this quaternion by a given angular step to the given quaternion.
  3525. * The method ensures that the final quaternion will not overshoot `q`.
  3526. *
  3527. * @param {Quaternion} q - The target quaternion.
  3528. * @param {number} step - The angular step in radians.
  3529. * @return {Quaternion} A reference to this quaternion.
  3530. */
  3531. rotateTowards( q, step ) {
  3532. const angle = this.angleTo( q );
  3533. if ( angle === 0 ) return this;
  3534. const t = Math.min( 1, step / angle );
  3535. this.slerp( q, t );
  3536. return this;
  3537. }
  3538. /**
  3539. * Sets this quaternion to the identity quaternion; that is, to the
  3540. * quaternion that represents "no rotation".
  3541. *
  3542. * @return {Quaternion} A reference to this quaternion.
  3543. */
  3544. identity() {
  3545. return this.set( 0, 0, 0, 1 );
  3546. }
  3547. /**
  3548. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3549. * quaternion is assumed to have unit length.
  3550. *
  3551. * @return {Quaternion} A reference to this quaternion.
  3552. */
  3553. invert() {
  3554. return this.conjugate();
  3555. }
  3556. /**
  3557. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3558. * quaternion represents the same rotation in the opposite direction about
  3559. * the rotational axis.
  3560. *
  3561. * @return {Quaternion} A reference to this quaternion.
  3562. */
  3563. conjugate() {
  3564. this._x *= -1;
  3565. this._y *= -1;
  3566. this._z *= -1;
  3567. this._onChangeCallback();
  3568. return this;
  3569. }
  3570. /**
  3571. * Calculates the dot product of this quaternion and the given one.
  3572. *
  3573. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3574. * @return {number} The result of the dot product.
  3575. */
  3576. dot( v ) {
  3577. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3578. }
  3579. /**
  3580. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3581. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3582. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3583. * {@link Quaternion#length}.
  3584. *
  3585. * @return {number} The squared Euclidean length.
  3586. */
  3587. lengthSq() {
  3588. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3589. }
  3590. /**
  3591. * Computes the Euclidean length (straight-line length) of this quaternion,
  3592. * considered as a 4 dimensional vector.
  3593. *
  3594. * @return {number} The Euclidean length.
  3595. */
  3596. length() {
  3597. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3598. }
  3599. /**
  3600. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3601. * the same rotation as this one, but has a length equal to `1`.
  3602. *
  3603. * @return {Quaternion} A reference to this quaternion.
  3604. */
  3605. normalize() {
  3606. let l = this.length();
  3607. if ( l === 0 ) {
  3608. this._x = 0;
  3609. this._y = 0;
  3610. this._z = 0;
  3611. this._w = 1;
  3612. } else {
  3613. l = 1 / l;
  3614. this._x = this._x * l;
  3615. this._y = this._y * l;
  3616. this._z = this._z * l;
  3617. this._w = this._w * l;
  3618. }
  3619. this._onChangeCallback();
  3620. return this;
  3621. }
  3622. /**
  3623. * Multiplies this quaternion by the given one.
  3624. *
  3625. * @param {Quaternion} q - The quaternion.
  3626. * @return {Quaternion} A reference to this quaternion.
  3627. */
  3628. multiply( q ) {
  3629. return this.multiplyQuaternions( this, q );
  3630. }
  3631. /**
  3632. * Pre-multiplies this quaternion by the given one.
  3633. *
  3634. * @param {Quaternion} q - The quaternion.
  3635. * @return {Quaternion} A reference to this quaternion.
  3636. */
  3637. premultiply( q ) {
  3638. return this.multiplyQuaternions( q, this );
  3639. }
  3640. /**
  3641. * Multiplies the given quaternions and stores the result in this instance.
  3642. *
  3643. * @param {Quaternion} a - The first quaternion.
  3644. * @param {Quaternion} b - The second quaternion.
  3645. * @return {Quaternion} A reference to this quaternion.
  3646. */
  3647. multiplyQuaternions( a, b ) {
  3648. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3649. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3650. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3651. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3652. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3653. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3654. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3655. this._onChangeCallback();
  3656. return this;
  3657. }
  3658. /**
  3659. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3660. *
  3661. * @param {Quaternion} qb - The target quaternion.
  3662. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3663. * @return {Quaternion} A reference to this quaternion.
  3664. */
  3665. slerp( qb, t ) {
  3666. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3667. let dot = this.dot( qb );
  3668. if ( dot < 0 ) {
  3669. x = - x;
  3670. y = - y;
  3671. z = - z;
  3672. w = - w;
  3673. dot = - dot;
  3674. }
  3675. let s = 1 - t;
  3676. if ( dot < 0.9995 ) {
  3677. // slerp
  3678. const theta = Math.acos( dot );
  3679. const sin = Math.sin( theta );
  3680. s = Math.sin( s * theta ) / sin;
  3681. t = Math.sin( t * theta ) / sin;
  3682. this._x = this._x * s + x * t;
  3683. this._y = this._y * s + y * t;
  3684. this._z = this._z * s + z * t;
  3685. this._w = this._w * s + w * t;
  3686. this._onChangeCallback();
  3687. } else {
  3688. // for small angles, lerp then normalize
  3689. this._x = this._x * s + x * t;
  3690. this._y = this._y * s + y * t;
  3691. this._z = this._z * s + z * t;
  3692. this._w = this._w * s + w * t;
  3693. this.normalize(); // normalize calls _onChangeCallback()
  3694. }
  3695. return this;
  3696. }
  3697. /**
  3698. * Performs a spherical linear interpolation between the given quaternions
  3699. * and stores the result in this quaternion.
  3700. *
  3701. * @param {Quaternion} qa - The source quaternion.
  3702. * @param {Quaternion} qb - The target quaternion.
  3703. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3704. * @return {Quaternion} A reference to this quaternion.
  3705. */
  3706. slerpQuaternions( qa, qb, t ) {
  3707. return this.copy( qa ).slerp( qb, t );
  3708. }
  3709. /**
  3710. * Sets this quaternion to a uniformly random, normalized quaternion.
  3711. *
  3712. * @return {Quaternion} A reference to this quaternion.
  3713. */
  3714. random() {
  3715. // Ken Shoemake
  3716. // Uniform random rotations
  3717. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3718. const theta1 = 2 * Math.PI * Math.random();
  3719. const theta2 = 2 * Math.PI * Math.random();
  3720. const x0 = Math.random();
  3721. const r1 = Math.sqrt( 1 - x0 );
  3722. const r2 = Math.sqrt( x0 );
  3723. return this.set(
  3724. r1 * Math.sin( theta1 ),
  3725. r1 * Math.cos( theta1 ),
  3726. r2 * Math.sin( theta2 ),
  3727. r2 * Math.cos( theta2 ),
  3728. );
  3729. }
  3730. /**
  3731. * Returns `true` if this quaternion is equal with the given one.
  3732. *
  3733. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3734. * @return {boolean} Whether this quaternion is equal with the given one.
  3735. */
  3736. equals( quaternion ) {
  3737. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3738. }
  3739. /**
  3740. * Sets this quaternion's components from the given array.
  3741. *
  3742. * @param {Array<number>} array - An array holding the quaternion component values.
  3743. * @param {number} [offset=0] - The offset into the array.
  3744. * @return {Quaternion} A reference to this quaternion.
  3745. */
  3746. fromArray( array, offset = 0 ) {
  3747. this._x = array[ offset ];
  3748. this._y = array[ offset + 1 ];
  3749. this._z = array[ offset + 2 ];
  3750. this._w = array[ offset + 3 ];
  3751. this._onChangeCallback();
  3752. return this;
  3753. }
  3754. /**
  3755. * Writes the components of this quaternion to the given array. If no array is provided,
  3756. * the method returns a new instance.
  3757. *
  3758. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3759. * @param {number} [offset=0] - Index of the first element in the array.
  3760. * @return {Array<number>} The quaternion components.
  3761. */
  3762. toArray( array = [], offset = 0 ) {
  3763. array[ offset ] = this._x;
  3764. array[ offset + 1 ] = this._y;
  3765. array[ offset + 2 ] = this._z;
  3766. array[ offset + 3 ] = this._w;
  3767. return array;
  3768. }
  3769. /**
  3770. * Sets the components of this quaternion from the given buffer attribute.
  3771. *
  3772. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3773. * @param {number} index - The index into the attribute.
  3774. * @return {Quaternion} A reference to this quaternion.
  3775. */
  3776. fromBufferAttribute( attribute, index ) {
  3777. this._x = attribute.getX( index );
  3778. this._y = attribute.getY( index );
  3779. this._z = attribute.getZ( index );
  3780. this._w = attribute.getW( index );
  3781. this._onChangeCallback();
  3782. return this;
  3783. }
  3784. /**
  3785. * This methods defines the serialization result of this class. Returns the
  3786. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3787. *
  3788. * @return {Array<number>} The serialized quaternion.
  3789. */
  3790. toJSON() {
  3791. return this.toArray();
  3792. }
  3793. _onChange( callback ) {
  3794. this._onChangeCallback = callback;
  3795. return this;
  3796. }
  3797. _onChangeCallback() {}
  3798. *[ Symbol.iterator ]() {
  3799. yield this._x;
  3800. yield this._y;
  3801. yield this._z;
  3802. yield this._w;
  3803. }
  3804. }
  3805. /**
  3806. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3807. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3808. *
  3809. * - A point in 3D space.
  3810. * - A direction and length in 3D space. In three.js the length will
  3811. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3812. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3813. * - Any arbitrary ordered triplet of numbers.
  3814. *
  3815. * There are other things a 3D vector can be used to represent, such as
  3816. * momentum vectors and so on, however these are the most
  3817. * common uses in three.js.
  3818. *
  3819. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3820. * the corresponding order.
  3821. * ```js
  3822. * const a = new THREE.Vector3( 0, 1, 0 );
  3823. *
  3824. * //no arguments; will be initialised to (0, 0, 0)
  3825. * const b = new THREE.Vector3( );
  3826. *
  3827. * const d = a.distanceTo( b );
  3828. * ```
  3829. */
  3830. class Vector3 {
  3831. /**
  3832. * Constructs a new 3D vector.
  3833. *
  3834. * @param {number} [x=0] - The x value of this vector.
  3835. * @param {number} [y=0] - The y value of this vector.
  3836. * @param {number} [z=0] - The z value of this vector.
  3837. */
  3838. constructor( x = 0, y = 0, z = 0 ) {
  3839. /**
  3840. * This flag can be used for type testing.
  3841. *
  3842. * @type {boolean}
  3843. * @readonly
  3844. * @default true
  3845. */
  3846. Vector3.prototype.isVector3 = true;
  3847. /**
  3848. * The x value of this vector.
  3849. *
  3850. * @type {number}
  3851. */
  3852. this.x = x;
  3853. /**
  3854. * The y value of this vector.
  3855. *
  3856. * @type {number}
  3857. */
  3858. this.y = y;
  3859. /**
  3860. * The z value of this vector.
  3861. *
  3862. * @type {number}
  3863. */
  3864. this.z = z;
  3865. }
  3866. /**
  3867. * Sets the vector components.
  3868. *
  3869. * @param {number} x - The value of the x component.
  3870. * @param {number} y - The value of the y component.
  3871. * @param {number} z - The value of the z component.
  3872. * @return {Vector3} A reference to this vector.
  3873. */
  3874. set( x, y, z ) {
  3875. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3876. this.x = x;
  3877. this.y = y;
  3878. this.z = z;
  3879. return this;
  3880. }
  3881. /**
  3882. * Sets the vector components to the same value.
  3883. *
  3884. * @param {number} scalar - The value to set for all vector components.
  3885. * @return {Vector3} A reference to this vector.
  3886. */
  3887. setScalar( scalar ) {
  3888. this.x = scalar;
  3889. this.y = scalar;
  3890. this.z = scalar;
  3891. return this;
  3892. }
  3893. /**
  3894. * Sets the vector's x component to the given value.
  3895. *
  3896. * @param {number} x - The value to set.
  3897. * @return {Vector3} A reference to this vector.
  3898. */
  3899. setX( x ) {
  3900. this.x = x;
  3901. return this;
  3902. }
  3903. /**
  3904. * Sets the vector's y component to the given value.
  3905. *
  3906. * @param {number} y - The value to set.
  3907. * @return {Vector3} A reference to this vector.
  3908. */
  3909. setY( y ) {
  3910. this.y = y;
  3911. return this;
  3912. }
  3913. /**
  3914. * Sets the vector's z component to the given value.
  3915. *
  3916. * @param {number} z - The value to set.
  3917. * @return {Vector3} A reference to this vector.
  3918. */
  3919. setZ( z ) {
  3920. this.z = z;
  3921. return this;
  3922. }
  3923. /**
  3924. * Allows to set a vector component with an index.
  3925. *
  3926. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3927. * @param {number} value - The value to set.
  3928. * @return {Vector3} A reference to this vector.
  3929. */
  3930. setComponent( index, value ) {
  3931. switch ( index ) {
  3932. case 0: this.x = value; break;
  3933. case 1: this.y = value; break;
  3934. case 2: this.z = value; break;
  3935. default: throw new Error( 'index is out of range: ' + index );
  3936. }
  3937. return this;
  3938. }
  3939. /**
  3940. * Returns the value of the vector component which matches the given index.
  3941. *
  3942. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3943. * @return {number} A vector component value.
  3944. */
  3945. getComponent( index ) {
  3946. switch ( index ) {
  3947. case 0: return this.x;
  3948. case 1: return this.y;
  3949. case 2: return this.z;
  3950. default: throw new Error( 'index is out of range: ' + index );
  3951. }
  3952. }
  3953. /**
  3954. * Returns a new vector with copied values from this instance.
  3955. *
  3956. * @return {Vector3} A clone of this instance.
  3957. */
  3958. clone() {
  3959. return new this.constructor( this.x, this.y, this.z );
  3960. }
  3961. /**
  3962. * Copies the values of the given vector to this instance.
  3963. *
  3964. * @param {Vector3} v - The vector to copy.
  3965. * @return {Vector3} A reference to this vector.
  3966. */
  3967. copy( v ) {
  3968. this.x = v.x;
  3969. this.y = v.y;
  3970. this.z = v.z;
  3971. return this;
  3972. }
  3973. /**
  3974. * Adds the given vector to this instance.
  3975. *
  3976. * @param {Vector3} v - The vector to add.
  3977. * @return {Vector3} A reference to this vector.
  3978. */
  3979. add( v ) {
  3980. this.x += v.x;
  3981. this.y += v.y;
  3982. this.z += v.z;
  3983. return this;
  3984. }
  3985. /**
  3986. * Adds the given scalar value to all components of this instance.
  3987. *
  3988. * @param {number} s - The scalar to add.
  3989. * @return {Vector3} A reference to this vector.
  3990. */
  3991. addScalar( s ) {
  3992. this.x += s;
  3993. this.y += s;
  3994. this.z += s;
  3995. return this;
  3996. }
  3997. /**
  3998. * Adds the given vectors and stores the result in this instance.
  3999. *
  4000. * @param {Vector3} a - The first vector.
  4001. * @param {Vector3} b - The second vector.
  4002. * @return {Vector3} A reference to this vector.
  4003. */
  4004. addVectors( a, b ) {
  4005. this.x = a.x + b.x;
  4006. this.y = a.y + b.y;
  4007. this.z = a.z + b.z;
  4008. return this;
  4009. }
  4010. /**
  4011. * Adds the given vector scaled by the given factor to this instance.
  4012. *
  4013. * @param {Vector3|Vector4} v - The vector.
  4014. * @param {number} s - The factor that scales `v`.
  4015. * @return {Vector3} A reference to this vector.
  4016. */
  4017. addScaledVector( v, s ) {
  4018. this.x += v.x * s;
  4019. this.y += v.y * s;
  4020. this.z += v.z * s;
  4021. return this;
  4022. }
  4023. /**
  4024. * Subtracts the given vector from this instance.
  4025. *
  4026. * @param {Vector3} v - The vector to subtract.
  4027. * @return {Vector3} A reference to this vector.
  4028. */
  4029. sub( v ) {
  4030. this.x -= v.x;
  4031. this.y -= v.y;
  4032. this.z -= v.z;
  4033. return this;
  4034. }
  4035. /**
  4036. * Subtracts the given scalar value from all components of this instance.
  4037. *
  4038. * @param {number} s - The scalar to subtract.
  4039. * @return {Vector3} A reference to this vector.
  4040. */
  4041. subScalar( s ) {
  4042. this.x -= s;
  4043. this.y -= s;
  4044. this.z -= s;
  4045. return this;
  4046. }
  4047. /**
  4048. * Subtracts the given vectors and stores the result in this instance.
  4049. *
  4050. * @param {Vector3} a - The first vector.
  4051. * @param {Vector3} b - The second vector.
  4052. * @return {Vector3} A reference to this vector.
  4053. */
  4054. subVectors( a, b ) {
  4055. this.x = a.x - b.x;
  4056. this.y = a.y - b.y;
  4057. this.z = a.z - b.z;
  4058. return this;
  4059. }
  4060. /**
  4061. * Multiplies the given vector with this instance.
  4062. *
  4063. * @param {Vector3} v - The vector to multiply.
  4064. * @return {Vector3} A reference to this vector.
  4065. */
  4066. multiply( v ) {
  4067. this.x *= v.x;
  4068. this.y *= v.y;
  4069. this.z *= v.z;
  4070. return this;
  4071. }
  4072. /**
  4073. * Multiplies the given scalar value with all components of this instance.
  4074. *
  4075. * @param {number} scalar - The scalar to multiply.
  4076. * @return {Vector3} A reference to this vector.
  4077. */
  4078. multiplyScalar( scalar ) {
  4079. this.x *= scalar;
  4080. this.y *= scalar;
  4081. this.z *= scalar;
  4082. return this;
  4083. }
  4084. /**
  4085. * Multiplies the given vectors and stores the result in this instance.
  4086. *
  4087. * @param {Vector3} a - The first vector.
  4088. * @param {Vector3} b - The second vector.
  4089. * @return {Vector3} A reference to this vector.
  4090. */
  4091. multiplyVectors( a, b ) {
  4092. this.x = a.x * b.x;
  4093. this.y = a.y * b.y;
  4094. this.z = a.z * b.z;
  4095. return this;
  4096. }
  4097. /**
  4098. * Applies the given Euler rotation to this vector.
  4099. *
  4100. * @param {Euler} euler - The Euler angles.
  4101. * @return {Vector3} A reference to this vector.
  4102. */
  4103. applyEuler( euler ) {
  4104. return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) );
  4105. }
  4106. /**
  4107. * Applies a rotation specified by an axis and an angle to this vector.
  4108. *
  4109. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4110. * @param {number} angle - The angle in radians.
  4111. * @return {Vector3} A reference to this vector.
  4112. */
  4113. applyAxisAngle( axis, angle ) {
  4114. return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) );
  4115. }
  4116. /**
  4117. * Multiplies this vector with the given 3x3 matrix.
  4118. *
  4119. * @param {Matrix3} m - The 3x3 matrix.
  4120. * @return {Vector3} A reference to this vector.
  4121. */
  4122. applyMatrix3( m ) {
  4123. const x = this.x, y = this.y, z = this.z;
  4124. const e = m.elements;
  4125. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4126. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4127. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4128. return this;
  4129. }
  4130. /**
  4131. * Multiplies this vector by the given normal matrix and normalizes
  4132. * the result.
  4133. *
  4134. * @param {Matrix3} m - The normal matrix.
  4135. * @return {Vector3} A reference to this vector.
  4136. */
  4137. applyNormalMatrix( m ) {
  4138. return this.applyMatrix3( m ).normalize();
  4139. }
  4140. /**
  4141. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4142. * divides by perspective.
  4143. *
  4144. * @param {Matrix4} m - The matrix to apply.
  4145. * @return {Vector3} A reference to this vector.
  4146. */
  4147. applyMatrix4( m ) {
  4148. const x = this.x, y = this.y, z = this.z;
  4149. const e = m.elements;
  4150. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4151. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4152. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4153. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4154. return this;
  4155. }
  4156. /**
  4157. * Applies the given Quaternion to this vector.
  4158. *
  4159. * @param {Quaternion} q - The Quaternion.
  4160. * @return {Vector3} A reference to this vector.
  4161. */
  4162. applyQuaternion( q ) {
  4163. // quaternion q is assumed to have unit length
  4164. const vx = this.x, vy = this.y, vz = this.z;
  4165. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4166. // t = 2 * cross( q.xyz, v );
  4167. const tx = 2 * ( qy * vz - qz * vy );
  4168. const ty = 2 * ( qz * vx - qx * vz );
  4169. const tz = 2 * ( qx * vy - qy * vx );
  4170. // v + q.w * t + cross( q.xyz, t );
  4171. this.x = vx + qw * tx + qy * tz - qz * ty;
  4172. this.y = vy + qw * ty + qz * tx - qx * tz;
  4173. this.z = vz + qw * tz + qx * ty - qy * tx;
  4174. return this;
  4175. }
  4176. /**
  4177. * Projects this vector from world space into the camera's normalized
  4178. * device coordinate (NDC) space.
  4179. *
  4180. * @param {Camera} camera - The camera.
  4181. * @return {Vector3} A reference to this vector.
  4182. */
  4183. project( camera ) {
  4184. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4185. }
  4186. /**
  4187. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4188. * space into world space.
  4189. *
  4190. * @param {Camera} camera - The camera.
  4191. * @return {Vector3} A reference to this vector.
  4192. */
  4193. unproject( camera ) {
  4194. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4195. }
  4196. /**
  4197. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4198. * subset of the given 4x4 matrix and then normalizes the result.
  4199. *
  4200. * @param {Matrix4} m - The matrix.
  4201. * @return {Vector3} A reference to this vector.
  4202. */
  4203. transformDirection( m ) {
  4204. // input: THREE.Matrix4 affine matrix
  4205. // vector interpreted as a direction
  4206. const x = this.x, y = this.y, z = this.z;
  4207. const e = m.elements;
  4208. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4209. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4210. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4211. return this.normalize();
  4212. }
  4213. /**
  4214. * Divides this instance by the given vector.
  4215. *
  4216. * @param {Vector3} v - The vector to divide.
  4217. * @return {Vector3} A reference to this vector.
  4218. */
  4219. divide( v ) {
  4220. this.x /= v.x;
  4221. this.y /= v.y;
  4222. this.z /= v.z;
  4223. return this;
  4224. }
  4225. /**
  4226. * Divides this vector by the given scalar.
  4227. *
  4228. * @param {number} scalar - The scalar to divide.
  4229. * @return {Vector3} A reference to this vector.
  4230. */
  4231. divideScalar( scalar ) {
  4232. return this.multiplyScalar( 1 / scalar );
  4233. }
  4234. /**
  4235. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4236. * value, replace that value with the corresponding min value.
  4237. *
  4238. * @param {Vector3} v - The vector.
  4239. * @return {Vector3} A reference to this vector.
  4240. */
  4241. min( v ) {
  4242. this.x = Math.min( this.x, v.x );
  4243. this.y = Math.min( this.y, v.y );
  4244. this.z = Math.min( this.z, v.z );
  4245. return this;
  4246. }
  4247. /**
  4248. * If this vector's x, y or z value is less than the given vector's x, y or z
  4249. * value, replace that value with the corresponding max value.
  4250. *
  4251. * @param {Vector3} v - The vector.
  4252. * @return {Vector3} A reference to this vector.
  4253. */
  4254. max( v ) {
  4255. this.x = Math.max( this.x, v.x );
  4256. this.y = Math.max( this.y, v.y );
  4257. this.z = Math.max( this.z, v.z );
  4258. return this;
  4259. }
  4260. /**
  4261. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4262. * value, it is replaced by the corresponding value.
  4263. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4264. * it is replaced by the corresponding value.
  4265. *
  4266. * @param {Vector3} min - The minimum x, y and z values.
  4267. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4268. * @return {Vector3} A reference to this vector.
  4269. */
  4270. clamp( min, max ) {
  4271. // assumes min < max, componentwise
  4272. this.x = clamp( this.x, min.x, max.x );
  4273. this.y = clamp( this.y, min.y, max.y );
  4274. this.z = clamp( this.z, min.z, max.z );
  4275. return this;
  4276. }
  4277. /**
  4278. * If this vector's x, y or z values are greater than the max value, they are
  4279. * replaced by the max value.
  4280. * If this vector's x, y or z values are less than the min value, they are
  4281. * replaced by the min value.
  4282. *
  4283. * @param {number} minVal - The minimum value the components will be clamped to.
  4284. * @param {number} maxVal - The maximum value the components will be clamped to.
  4285. * @return {Vector3} A reference to this vector.
  4286. */
  4287. clampScalar( minVal, maxVal ) {
  4288. this.x = clamp( this.x, minVal, maxVal );
  4289. this.y = clamp( this.y, minVal, maxVal );
  4290. this.z = clamp( this.z, minVal, maxVal );
  4291. return this;
  4292. }
  4293. /**
  4294. * If this vector's length is greater than the max value, it is replaced by
  4295. * the max value.
  4296. * If this vector's length is less than the min value, it is replaced by the
  4297. * min value.
  4298. *
  4299. * @param {number} min - The minimum value the vector length will be clamped to.
  4300. * @param {number} max - The maximum value the vector length will be clamped to.
  4301. * @return {Vector3} A reference to this vector.
  4302. */
  4303. clampLength( min, max ) {
  4304. const length = this.length();
  4305. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4306. }
  4307. /**
  4308. * The components of this vector are rounded down to the nearest integer value.
  4309. *
  4310. * @return {Vector3} A reference to this vector.
  4311. */
  4312. floor() {
  4313. this.x = Math.floor( this.x );
  4314. this.y = Math.floor( this.y );
  4315. this.z = Math.floor( this.z );
  4316. return this;
  4317. }
  4318. /**
  4319. * The components of this vector are rounded up to the nearest integer value.
  4320. *
  4321. * @return {Vector3} A reference to this vector.
  4322. */
  4323. ceil() {
  4324. this.x = Math.ceil( this.x );
  4325. this.y = Math.ceil( this.y );
  4326. this.z = Math.ceil( this.z );
  4327. return this;
  4328. }
  4329. /**
  4330. * The components of this vector are rounded to the nearest integer value
  4331. *
  4332. * @return {Vector3} A reference to this vector.
  4333. */
  4334. round() {
  4335. this.x = Math.round( this.x );
  4336. this.y = Math.round( this.y );
  4337. this.z = Math.round( this.z );
  4338. return this;
  4339. }
  4340. /**
  4341. * The components of this vector are rounded towards zero (up if negative,
  4342. * down if positive) to an integer value.
  4343. *
  4344. * @return {Vector3} A reference to this vector.
  4345. */
  4346. roundToZero() {
  4347. this.x = Math.trunc( this.x );
  4348. this.y = Math.trunc( this.y );
  4349. this.z = Math.trunc( this.z );
  4350. return this;
  4351. }
  4352. /**
  4353. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4354. *
  4355. * @return {Vector3} A reference to this vector.
  4356. */
  4357. negate() {
  4358. this.x = - this.x;
  4359. this.y = - this.y;
  4360. this.z = - this.z;
  4361. return this;
  4362. }
  4363. /**
  4364. * Calculates the dot product of the given vector with this instance.
  4365. *
  4366. * @param {Vector3} v - The vector to compute the dot product with.
  4367. * @return {number} The result of the dot product.
  4368. */
  4369. dot( v ) {
  4370. return this.x * v.x + this.y * v.y + this.z * v.z;
  4371. }
  4372. /**
  4373. * Computes the square of the Euclidean length (straight-line length) from
  4374. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4375. * compare the length squared instead as it is slightly more efficient to calculate.
  4376. *
  4377. * @return {number} The square length of this vector.
  4378. */
  4379. lengthSq() {
  4380. return this.x * this.x + this.y * this.y + this.z * this.z;
  4381. }
  4382. /**
  4383. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4384. *
  4385. * @return {number} The length of this vector.
  4386. */
  4387. length() {
  4388. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4389. }
  4390. /**
  4391. * Computes the Manhattan length of this vector.
  4392. *
  4393. * @return {number} The length of this vector.
  4394. */
  4395. manhattanLength() {
  4396. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4397. }
  4398. /**
  4399. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4400. * with the same direction as this one, but with a vector length of `1`.
  4401. *
  4402. * @return {Vector3} A reference to this vector.
  4403. */
  4404. normalize() {
  4405. return this.divideScalar( this.length() || 1 );
  4406. }
  4407. /**
  4408. * Sets this vector to a vector with the same direction as this one, but
  4409. * with the specified length.
  4410. *
  4411. * @param {number} length - The new length of this vector.
  4412. * @return {Vector3} A reference to this vector.
  4413. */
  4414. setLength( length ) {
  4415. return this.normalize().multiplyScalar( length );
  4416. }
  4417. /**
  4418. * Linearly interpolates between the given vector and this instance, where
  4419. * alpha is the percent distance along the line - alpha = 0 will be this
  4420. * vector, and alpha = 1 will be the given one.
  4421. *
  4422. * @param {Vector3} v - The vector to interpolate towards.
  4423. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4424. * @return {Vector3} A reference to this vector.
  4425. */
  4426. lerp( v, alpha ) {
  4427. this.x += ( v.x - this.x ) * alpha;
  4428. this.y += ( v.y - this.y ) * alpha;
  4429. this.z += ( v.z - this.z ) * alpha;
  4430. return this;
  4431. }
  4432. /**
  4433. * Linearly interpolates between the given vectors, where alpha is the percent
  4434. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4435. * be the second one. The result is stored in this instance.
  4436. *
  4437. * @param {Vector3} v1 - The first vector.
  4438. * @param {Vector3} v2 - The second vector.
  4439. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4440. * @return {Vector3} A reference to this vector.
  4441. */
  4442. lerpVectors( v1, v2, alpha ) {
  4443. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4444. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4445. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4446. return this;
  4447. }
  4448. /**
  4449. * Calculates the cross product of the given vector with this instance.
  4450. *
  4451. * @param {Vector3} v - The vector to compute the cross product with.
  4452. * @return {Vector3} The result of the cross product.
  4453. */
  4454. cross( v ) {
  4455. return this.crossVectors( this, v );
  4456. }
  4457. /**
  4458. * Calculates the cross product of the given vectors and stores the result
  4459. * in this instance.
  4460. *
  4461. * @param {Vector3} a - The first vector.
  4462. * @param {Vector3} b - The second vector.
  4463. * @return {Vector3} A reference to this vector.
  4464. */
  4465. crossVectors( a, b ) {
  4466. const ax = a.x, ay = a.y, az = a.z;
  4467. const bx = b.x, by = b.y, bz = b.z;
  4468. this.x = ay * bz - az * by;
  4469. this.y = az * bx - ax * bz;
  4470. this.z = ax * by - ay * bx;
  4471. return this;
  4472. }
  4473. /**
  4474. * Projects this vector onto the given one.
  4475. *
  4476. * @param {Vector3} v - The vector to project to.
  4477. * @return {Vector3} A reference to this vector.
  4478. */
  4479. projectOnVector( v ) {
  4480. const denominator = v.lengthSq();
  4481. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4482. const scalar = v.dot( this ) / denominator;
  4483. return this.copy( v ).multiplyScalar( scalar );
  4484. }
  4485. /**
  4486. * Projects this vector onto a plane by subtracting this
  4487. * vector projected onto the plane's normal from this vector.
  4488. *
  4489. * @param {Vector3} planeNormal - The plane normal.
  4490. * @return {Vector3} A reference to this vector.
  4491. */
  4492. projectOnPlane( planeNormal ) {
  4493. _vector$c.copy( this ).projectOnVector( planeNormal );
  4494. return this.sub( _vector$c );
  4495. }
  4496. /**
  4497. * Reflects this vector off a plane orthogonal to the given normal vector.
  4498. *
  4499. * @param {Vector3} normal - The (normalized) normal vector.
  4500. * @return {Vector3} A reference to this vector.
  4501. */
  4502. reflect( normal ) {
  4503. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4504. }
  4505. /**
  4506. * Returns the angle between the given vector and this instance in radians.
  4507. *
  4508. * @param {Vector3} v - The vector to compute the angle with.
  4509. * @return {number} The angle in radians.
  4510. */
  4511. angleTo( v ) {
  4512. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4513. if ( denominator === 0 ) return Math.PI / 2;
  4514. const theta = this.dot( v ) / denominator;
  4515. // clamp, to handle numerical problems
  4516. return Math.acos( clamp( theta, -1, 1 ) );
  4517. }
  4518. /**
  4519. * Computes the distance from the given vector to this instance.
  4520. *
  4521. * @param {Vector3} v - The vector to compute the distance to.
  4522. * @return {number} The distance.
  4523. */
  4524. distanceTo( v ) {
  4525. return Math.sqrt( this.distanceToSquared( v ) );
  4526. }
  4527. /**
  4528. * Computes the squared distance from the given vector to this instance.
  4529. * If you are just comparing the distance with another distance, you should compare
  4530. * the distance squared instead as it is slightly more efficient to calculate.
  4531. *
  4532. * @param {Vector3} v - The vector to compute the squared distance to.
  4533. * @return {number} The squared distance.
  4534. */
  4535. distanceToSquared( v ) {
  4536. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4537. return dx * dx + dy * dy + dz * dz;
  4538. }
  4539. /**
  4540. * Computes the Manhattan distance from the given vector to this instance.
  4541. *
  4542. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4543. * @return {number} The Manhattan distance.
  4544. */
  4545. manhattanDistanceTo( v ) {
  4546. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4547. }
  4548. /**
  4549. * Sets the vector components from the given spherical coordinates.
  4550. *
  4551. * @param {Spherical} s - The spherical coordinates.
  4552. * @return {Vector3} A reference to this vector.
  4553. */
  4554. setFromSpherical( s ) {
  4555. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4556. }
  4557. /**
  4558. * Sets the vector components from the given spherical coordinates.
  4559. *
  4560. * @param {number} radius - The radius.
  4561. * @param {number} phi - The phi angle in radians.
  4562. * @param {number} theta - The theta angle in radians.
  4563. * @return {Vector3} A reference to this vector.
  4564. */
  4565. setFromSphericalCoords( radius, phi, theta ) {
  4566. const sinPhiRadius = Math.sin( phi ) * radius;
  4567. this.x = sinPhiRadius * Math.sin( theta );
  4568. this.y = Math.cos( phi ) * radius;
  4569. this.z = sinPhiRadius * Math.cos( theta );
  4570. return this;
  4571. }
  4572. /**
  4573. * Sets the vector components from the given cylindrical coordinates.
  4574. *
  4575. * @param {Cylindrical} c - The cylindrical coordinates.
  4576. * @return {Vector3} A reference to this vector.
  4577. */
  4578. setFromCylindrical( c ) {
  4579. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4580. }
  4581. /**
  4582. * Sets the vector components from the given cylindrical coordinates.
  4583. *
  4584. * @param {number} radius - The radius.
  4585. * @param {number} theta - The theta angle in radians.
  4586. * @param {number} y - The y value.
  4587. * @return {Vector3} A reference to this vector.
  4588. */
  4589. setFromCylindricalCoords( radius, theta, y ) {
  4590. this.x = radius * Math.sin( theta );
  4591. this.y = y;
  4592. this.z = radius * Math.cos( theta );
  4593. return this;
  4594. }
  4595. /**
  4596. * Sets the vector components to the position elements of the
  4597. * given transformation matrix.
  4598. *
  4599. * @param {Matrix4} m - The 4x4 matrix.
  4600. * @return {Vector3} A reference to this vector.
  4601. */
  4602. setFromMatrixPosition( m ) {
  4603. const e = m.elements;
  4604. this.x = e[ 12 ];
  4605. this.y = e[ 13 ];
  4606. this.z = e[ 14 ];
  4607. return this;
  4608. }
  4609. /**
  4610. * Sets the vector components to the scale elements of the
  4611. * given transformation matrix.
  4612. *
  4613. * @param {Matrix4} m - The 4x4 matrix.
  4614. * @return {Vector3} A reference to this vector.
  4615. */
  4616. setFromMatrixScale( m ) {
  4617. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4618. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4619. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4620. this.x = sx;
  4621. this.y = sy;
  4622. this.z = sz;
  4623. return this;
  4624. }
  4625. /**
  4626. * Sets the vector components from the specified matrix column.
  4627. *
  4628. * @param {Matrix4} m - The 4x4 matrix.
  4629. * @param {number} index - The column index.
  4630. * @return {Vector3} A reference to this vector.
  4631. */
  4632. setFromMatrixColumn( m, index ) {
  4633. return this.fromArray( m.elements, index * 4 );
  4634. }
  4635. /**
  4636. * Sets the vector components from the specified matrix column.
  4637. *
  4638. * @param {Matrix3} m - The 3x3 matrix.
  4639. * @param {number} index - The column index.
  4640. * @return {Vector3} A reference to this vector.
  4641. */
  4642. setFromMatrix3Column( m, index ) {
  4643. return this.fromArray( m.elements, index * 3 );
  4644. }
  4645. /**
  4646. * Sets the vector components from the given Euler angles.
  4647. *
  4648. * @param {Euler} e - The Euler angles to set.
  4649. * @return {Vector3} A reference to this vector.
  4650. */
  4651. setFromEuler( e ) {
  4652. this.x = e._x;
  4653. this.y = e._y;
  4654. this.z = e._z;
  4655. return this;
  4656. }
  4657. /**
  4658. * Sets the vector components from the RGB components of the
  4659. * given color.
  4660. *
  4661. * @param {Color} c - The color to set.
  4662. * @return {Vector3} A reference to this vector.
  4663. */
  4664. setFromColor( c ) {
  4665. this.x = c.r;
  4666. this.y = c.g;
  4667. this.z = c.b;
  4668. return this;
  4669. }
  4670. /**
  4671. * Returns `true` if this vector is equal with the given one.
  4672. *
  4673. * @param {Vector3} v - The vector to test for equality.
  4674. * @return {boolean} Whether this vector is equal with the given one.
  4675. */
  4676. equals( v ) {
  4677. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4678. }
  4679. /**
  4680. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4681. * and z value to be `array[ offset + 2 ]`.
  4682. *
  4683. * @param {Array<number>} array - An array holding the vector component values.
  4684. * @param {number} [offset=0] - The offset into the array.
  4685. * @return {Vector3} A reference to this vector.
  4686. */
  4687. fromArray( array, offset = 0 ) {
  4688. this.x = array[ offset ];
  4689. this.y = array[ offset + 1 ];
  4690. this.z = array[ offset + 2 ];
  4691. return this;
  4692. }
  4693. /**
  4694. * Writes the components of this vector to the given array. If no array is provided,
  4695. * the method returns a new instance.
  4696. *
  4697. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4698. * @param {number} [offset=0] - Index of the first element in the array.
  4699. * @return {Array<number>} The vector components.
  4700. */
  4701. toArray( array = [], offset = 0 ) {
  4702. array[ offset ] = this.x;
  4703. array[ offset + 1 ] = this.y;
  4704. array[ offset + 2 ] = this.z;
  4705. return array;
  4706. }
  4707. /**
  4708. * Sets the components of this vector from the given buffer attribute.
  4709. *
  4710. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4711. * @param {number} index - The index into the attribute.
  4712. * @return {Vector3} A reference to this vector.
  4713. */
  4714. fromBufferAttribute( attribute, index ) {
  4715. this.x = attribute.getX( index );
  4716. this.y = attribute.getY( index );
  4717. this.z = attribute.getZ( index );
  4718. return this;
  4719. }
  4720. /**
  4721. * Sets each component of this vector to a pseudo-random value between `0` and
  4722. * `1`, excluding `1`.
  4723. *
  4724. * @return {Vector3} A reference to this vector.
  4725. */
  4726. random() {
  4727. this.x = Math.random();
  4728. this.y = Math.random();
  4729. this.z = Math.random();
  4730. return this;
  4731. }
  4732. /**
  4733. * Sets this vector to a uniformly random point on a unit sphere.
  4734. *
  4735. * @return {Vector3} A reference to this vector.
  4736. */
  4737. randomDirection() {
  4738. // https://mathworld.wolfram.com/SpherePointPicking.html
  4739. const theta = Math.random() * Math.PI * 2;
  4740. const u = Math.random() * 2 - 1;
  4741. const c = Math.sqrt( 1 - u * u );
  4742. this.x = c * Math.cos( theta );
  4743. this.y = u;
  4744. this.z = c * Math.sin( theta );
  4745. return this;
  4746. }
  4747. *[ Symbol.iterator ]() {
  4748. yield this.x;
  4749. yield this.y;
  4750. yield this.z;
  4751. }
  4752. }
  4753. const _vector$c = /*@__PURE__*/ new Vector3();
  4754. const _quaternion$5 = /*@__PURE__*/ new Quaternion();
  4755. /**
  4756. * Represents a 3x3 matrix.
  4757. *
  4758. * A Note on Row-Major and Column-Major Ordering:
  4759. *
  4760. * The constructor and {@link Matrix3#set} method take arguments in
  4761. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4762. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4763. * This means that calling:
  4764. * ```js
  4765. * const m = new THREE.Matrix();
  4766. * m.set( 11, 12, 13,
  4767. * 21, 22, 23,
  4768. * 31, 32, 33 );
  4769. * ```
  4770. * will result in the elements array containing:
  4771. * ```js
  4772. * m.elements = [ 11, 21, 31,
  4773. * 12, 22, 32,
  4774. * 13, 23, 33 ];
  4775. * ```
  4776. * and internally all calculations are performed using column-major ordering.
  4777. * However, as the actual ordering makes no difference mathematically and
  4778. * most people are used to thinking about matrices in row-major order, the
  4779. * three.js documentation shows matrices in row-major order. Just bear in
  4780. * mind that if you are reading the source code, you'll have to take the
  4781. * transpose of any matrices outlined here to make sense of the calculations.
  4782. */
  4783. class Matrix3 {
  4784. /**
  4785. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4786. * in row-major order. If no arguments are provided, the constructor
  4787. * initializes the matrix as an identity matrix.
  4788. *
  4789. * @param {number} [n11] - 1-1 matrix element.
  4790. * @param {number} [n12] - 1-2 matrix element.
  4791. * @param {number} [n13] - 1-3 matrix element.
  4792. * @param {number} [n21] - 2-1 matrix element.
  4793. * @param {number} [n22] - 2-2 matrix element.
  4794. * @param {number} [n23] - 2-3 matrix element.
  4795. * @param {number} [n31] - 3-1 matrix element.
  4796. * @param {number} [n32] - 3-2 matrix element.
  4797. * @param {number} [n33] - 3-3 matrix element.
  4798. */
  4799. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4800. /**
  4801. * This flag can be used for type testing.
  4802. *
  4803. * @type {boolean}
  4804. * @readonly
  4805. * @default true
  4806. */
  4807. Matrix3.prototype.isMatrix3 = true;
  4808. /**
  4809. * A column-major list of matrix values.
  4810. *
  4811. * @type {Array<number>}
  4812. */
  4813. this.elements = [
  4814. 1, 0, 0,
  4815. 0, 1, 0,
  4816. 0, 0, 1
  4817. ];
  4818. if ( n11 !== undefined ) {
  4819. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4820. }
  4821. }
  4822. /**
  4823. * Sets the elements of the matrix.The arguments are supposed to be
  4824. * in row-major order.
  4825. *
  4826. * @param {number} [n11] - 1-1 matrix element.
  4827. * @param {number} [n12] - 1-2 matrix element.
  4828. * @param {number} [n13] - 1-3 matrix element.
  4829. * @param {number} [n21] - 2-1 matrix element.
  4830. * @param {number} [n22] - 2-2 matrix element.
  4831. * @param {number} [n23] - 2-3 matrix element.
  4832. * @param {number} [n31] - 3-1 matrix element.
  4833. * @param {number} [n32] - 3-2 matrix element.
  4834. * @param {number} [n33] - 3-3 matrix element.
  4835. * @return {Matrix3} A reference to this matrix.
  4836. */
  4837. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4838. const te = this.elements;
  4839. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4840. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4841. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4842. return this;
  4843. }
  4844. /**
  4845. * Sets this matrix to the 3x3 identity matrix.
  4846. *
  4847. * @return {Matrix3} A reference to this matrix.
  4848. */
  4849. identity() {
  4850. this.set(
  4851. 1, 0, 0,
  4852. 0, 1, 0,
  4853. 0, 0, 1
  4854. );
  4855. return this;
  4856. }
  4857. /**
  4858. * Copies the values of the given matrix to this instance.
  4859. *
  4860. * @param {Matrix3} m - The matrix to copy.
  4861. * @return {Matrix3} A reference to this matrix.
  4862. */
  4863. copy( m ) {
  4864. const te = this.elements;
  4865. const me = m.elements;
  4866. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4867. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4868. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4869. return this;
  4870. }
  4871. /**
  4872. * Extracts the basis of this matrix into the three axis vectors provided.
  4873. *
  4874. * @param {Vector3} xAxis - The basis's x axis.
  4875. * @param {Vector3} yAxis - The basis's y axis.
  4876. * @param {Vector3} zAxis - The basis's z axis.
  4877. * @return {Matrix3} A reference to this matrix.
  4878. */
  4879. extractBasis( xAxis, yAxis, zAxis ) {
  4880. xAxis.setFromMatrix3Column( this, 0 );
  4881. yAxis.setFromMatrix3Column( this, 1 );
  4882. zAxis.setFromMatrix3Column( this, 2 );
  4883. return this;
  4884. }
  4885. /**
  4886. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4887. *
  4888. * @param {Matrix4} m - The 4x4 matrix.
  4889. * @return {Matrix3} A reference to this matrix.
  4890. */
  4891. setFromMatrix4( m ) {
  4892. const me = m.elements;
  4893. this.set(
  4894. me[ 0 ], me[ 4 ], me[ 8 ],
  4895. me[ 1 ], me[ 5 ], me[ 9 ],
  4896. me[ 2 ], me[ 6 ], me[ 10 ]
  4897. );
  4898. return this;
  4899. }
  4900. /**
  4901. * Post-multiplies this matrix by the given 3x3 matrix.
  4902. *
  4903. * @param {Matrix3} m - The matrix to multiply with.
  4904. * @return {Matrix3} A reference to this matrix.
  4905. */
  4906. multiply( m ) {
  4907. return this.multiplyMatrices( this, m );
  4908. }
  4909. /**
  4910. * Pre-multiplies this matrix by the given 3x3 matrix.
  4911. *
  4912. * @param {Matrix3} m - The matrix to multiply with.
  4913. * @return {Matrix3} A reference to this matrix.
  4914. */
  4915. premultiply( m ) {
  4916. return this.multiplyMatrices( m, this );
  4917. }
  4918. /**
  4919. * Multiples the given 3x3 matrices and stores the result
  4920. * in this matrix.
  4921. *
  4922. * @param {Matrix3} a - The first matrix.
  4923. * @param {Matrix3} b - The second matrix.
  4924. * @return {Matrix3} A reference to this matrix.
  4925. */
  4926. multiplyMatrices( a, b ) {
  4927. const ae = a.elements;
  4928. const be = b.elements;
  4929. const te = this.elements;
  4930. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4931. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4932. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4933. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4934. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4935. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4936. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4937. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4938. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4939. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4940. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4941. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4942. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4943. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4944. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4945. return this;
  4946. }
  4947. /**
  4948. * Multiplies every component of the matrix by the given scalar.
  4949. *
  4950. * @param {number} s - The scalar.
  4951. * @return {Matrix3} A reference to this matrix.
  4952. */
  4953. multiplyScalar( s ) {
  4954. const te = this.elements;
  4955. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4956. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4957. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4958. return this;
  4959. }
  4960. /**
  4961. * Computes and returns the determinant of this matrix.
  4962. *
  4963. * @return {number} The determinant.
  4964. */
  4965. determinant() {
  4966. const te = this.elements;
  4967. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4968. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4969. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4970. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4971. }
  4972. /**
  4973. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4974. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4975. * a zero matrix instead.
  4976. *
  4977. * @return {Matrix3} A reference to this matrix.
  4978. */
  4979. invert() {
  4980. const te = this.elements,
  4981. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4982. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4983. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4984. t11 = n33 * n22 - n32 * n23,
  4985. t12 = n32 * n13 - n33 * n12,
  4986. t13 = n23 * n12 - n22 * n13,
  4987. det = n11 * t11 + n21 * t12 + n31 * t13;
  4988. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4989. const detInv = 1 / det;
  4990. te[ 0 ] = t11 * detInv;
  4991. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4992. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4993. te[ 3 ] = t12 * detInv;
  4994. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4995. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4996. te[ 6 ] = t13 * detInv;
  4997. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4998. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4999. return this;
  5000. }
  5001. /**
  5002. * Transposes this matrix in place.
  5003. *
  5004. * @return {Matrix3} A reference to this matrix.
  5005. */
  5006. transpose() {
  5007. let tmp;
  5008. const m = this.elements;
  5009. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  5010. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  5011. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  5012. return this;
  5013. }
  5014. /**
  5015. * Computes the normal matrix which is the inverse transpose of the upper
  5016. * left 3x3 portion of the given 4x4 matrix.
  5017. *
  5018. * @param {Matrix4} matrix4 - The 4x4 matrix.
  5019. * @return {Matrix3} A reference to this matrix.
  5020. */
  5021. getNormalMatrix( matrix4 ) {
  5022. return this.setFromMatrix4( matrix4 ).invert().transpose();
  5023. }
  5024. /**
  5025. * Transposes this matrix into the supplied array, and returns itself unchanged.
  5026. *
  5027. * @param {Array<number>} r - An array to store the transposed matrix elements.
  5028. * @return {Matrix3} A reference to this matrix.
  5029. */
  5030. transposeIntoArray( r ) {
  5031. const m = this.elements;
  5032. r[ 0 ] = m[ 0 ];
  5033. r[ 1 ] = m[ 3 ];
  5034. r[ 2 ] = m[ 6 ];
  5035. r[ 3 ] = m[ 1 ];
  5036. r[ 4 ] = m[ 4 ];
  5037. r[ 5 ] = m[ 7 ];
  5038. r[ 6 ] = m[ 2 ];
  5039. r[ 7 ] = m[ 5 ];
  5040. r[ 8 ] = m[ 8 ];
  5041. return this;
  5042. }
  5043. /**
  5044. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  5045. *
  5046. * @param {number} tx - Offset x.
  5047. * @param {number} ty - Offset y.
  5048. * @param {number} sx - Repeat x.
  5049. * @param {number} sy - Repeat y.
  5050. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5051. * @param {number} cx - Center x of rotation.
  5052. * @param {number} cy - Center y of rotation
  5053. * @return {Matrix3} A reference to this matrix.
  5054. */
  5055. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5056. const c = Math.cos( rotation );
  5057. const s = Math.sin( rotation );
  5058. this.set(
  5059. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5060. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5061. 0, 0, 1
  5062. );
  5063. return this;
  5064. }
  5065. /**
  5066. * Scales this matrix with the given scalar values.
  5067. *
  5068. * @param {number} sx - The amount to scale in the X axis.
  5069. * @param {number} sy - The amount to scale in the Y axis.
  5070. * @return {Matrix3} A reference to this matrix.
  5071. */
  5072. scale( sx, sy ) {
  5073. this.premultiply( _m3.makeScale( sx, sy ) );
  5074. return this;
  5075. }
  5076. /**
  5077. * Rotates this matrix by the given angle.
  5078. *
  5079. * @param {number} theta - The rotation in radians.
  5080. * @return {Matrix3} A reference to this matrix.
  5081. */
  5082. rotate( theta ) {
  5083. this.premultiply( _m3.makeRotation( - theta ) );
  5084. return this;
  5085. }
  5086. /**
  5087. * Translates this matrix by the given scalar values.
  5088. *
  5089. * @param {number} tx - The amount to translate in the X axis.
  5090. * @param {number} ty - The amount to translate in the Y axis.
  5091. * @return {Matrix3} A reference to this matrix.
  5092. */
  5093. translate( tx, ty ) {
  5094. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5095. return this;
  5096. }
  5097. // for 2D Transforms
  5098. /**
  5099. * Sets this matrix as a 2D translation transform.
  5100. *
  5101. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5102. * @param {number} y - The amount to translate in the Y axis.
  5103. * @return {Matrix3} A reference to this matrix.
  5104. */
  5105. makeTranslation( x, y ) {
  5106. if ( x.isVector2 ) {
  5107. this.set(
  5108. 1, 0, x.x,
  5109. 0, 1, x.y,
  5110. 0, 0, 1
  5111. );
  5112. } else {
  5113. this.set(
  5114. 1, 0, x,
  5115. 0, 1, y,
  5116. 0, 0, 1
  5117. );
  5118. }
  5119. return this;
  5120. }
  5121. /**
  5122. * Sets this matrix as a 2D rotational transformation.
  5123. *
  5124. * @param {number} theta - The rotation in radians.
  5125. * @return {Matrix3} A reference to this matrix.
  5126. */
  5127. makeRotation( theta ) {
  5128. // counterclockwise
  5129. const c = Math.cos( theta );
  5130. const s = Math.sin( theta );
  5131. this.set(
  5132. c, - s, 0,
  5133. s, c, 0,
  5134. 0, 0, 1
  5135. );
  5136. return this;
  5137. }
  5138. /**
  5139. * Sets this matrix as a 2D scale transform.
  5140. *
  5141. * @param {number} x - The amount to scale in the X axis.
  5142. * @param {number} y - The amount to scale in the Y axis.
  5143. * @return {Matrix3} A reference to this matrix.
  5144. */
  5145. makeScale( x, y ) {
  5146. this.set(
  5147. x, 0, 0,
  5148. 0, y, 0,
  5149. 0, 0, 1
  5150. );
  5151. return this;
  5152. }
  5153. /**
  5154. * Returns `true` if this matrix is equal with the given one.
  5155. *
  5156. * @param {Matrix3} matrix - The matrix to test for equality.
  5157. * @return {boolean} Whether this matrix is equal with the given one.
  5158. */
  5159. equals( matrix ) {
  5160. const te = this.elements;
  5161. const me = matrix.elements;
  5162. for ( let i = 0; i < 9; i ++ ) {
  5163. if ( te[ i ] !== me[ i ] ) return false;
  5164. }
  5165. return true;
  5166. }
  5167. /**
  5168. * Sets the elements of the matrix from the given array.
  5169. *
  5170. * @param {Array<number>} array - The matrix elements in column-major order.
  5171. * @param {number} [offset=0] - Index of the first element in the array.
  5172. * @return {Matrix3} A reference to this matrix.
  5173. */
  5174. fromArray( array, offset = 0 ) {
  5175. for ( let i = 0; i < 9; i ++ ) {
  5176. this.elements[ i ] = array[ i + offset ];
  5177. }
  5178. return this;
  5179. }
  5180. /**
  5181. * Writes the elements of this matrix to the given array. If no array is provided,
  5182. * the method returns a new instance.
  5183. *
  5184. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5185. * @param {number} [offset=0] - Index of the first element in the array.
  5186. * @return {Array<number>} The matrix elements in column-major order.
  5187. */
  5188. toArray( array = [], offset = 0 ) {
  5189. const te = this.elements;
  5190. array[ offset ] = te[ 0 ];
  5191. array[ offset + 1 ] = te[ 1 ];
  5192. array[ offset + 2 ] = te[ 2 ];
  5193. array[ offset + 3 ] = te[ 3 ];
  5194. array[ offset + 4 ] = te[ 4 ];
  5195. array[ offset + 5 ] = te[ 5 ];
  5196. array[ offset + 6 ] = te[ 6 ];
  5197. array[ offset + 7 ] = te[ 7 ];
  5198. array[ offset + 8 ] = te[ 8 ];
  5199. return array;
  5200. }
  5201. /**
  5202. * Returns a matrix with copied values from this instance.
  5203. *
  5204. * @return {Matrix3} A clone of this instance.
  5205. */
  5206. clone() {
  5207. return new this.constructor().fromArray( this.elements );
  5208. }
  5209. }
  5210. const _m3 = /*@__PURE__*/ new Matrix3();
  5211. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5212. 0.4123908, 0.3575843, 0.1804808,
  5213. 0.2126390, 0.7151687, 0.0721923,
  5214. 0.0193308, 0.1191948, 0.9505322
  5215. );
  5216. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5217. 3.2409699, -1.5373832, -0.4986108,
  5218. -0.9692436, 1.8759675, 0.0415551,
  5219. 0.0556301, -0.203977, 1.0569715
  5220. );
  5221. function createColorManagement() {
  5222. const ColorManagement = {
  5223. enabled: true,
  5224. workingColorSpace: LinearSRGBColorSpace,
  5225. /**
  5226. * Implementations of supported color spaces.
  5227. *
  5228. * Required:
  5229. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5230. * - whitePoint: reference white [ x y ]
  5231. * - transfer: transfer function (pre-defined)
  5232. * - toXYZ: Matrix3 RGB to XYZ transform
  5233. * - fromXYZ: Matrix3 XYZ to RGB transform
  5234. * - luminanceCoefficients: RGB luminance coefficients
  5235. *
  5236. * Optional:
  5237. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5238. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5239. *
  5240. * Reference:
  5241. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5242. */
  5243. spaces: {},
  5244. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5245. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5246. return color;
  5247. }
  5248. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5249. color.r = SRGBToLinear( color.r );
  5250. color.g = SRGBToLinear( color.g );
  5251. color.b = SRGBToLinear( color.b );
  5252. }
  5253. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5254. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5255. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5256. }
  5257. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5258. color.r = LinearToSRGB( color.r );
  5259. color.g = LinearToSRGB( color.g );
  5260. color.b = LinearToSRGB( color.b );
  5261. }
  5262. return color;
  5263. },
  5264. workingToColorSpace: function ( color, targetColorSpace ) {
  5265. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5266. },
  5267. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5268. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5269. },
  5270. getPrimaries: function ( colorSpace ) {
  5271. return this.spaces[ colorSpace ].primaries;
  5272. },
  5273. getTransfer: function ( colorSpace ) {
  5274. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5275. return this.spaces[ colorSpace ].transfer;
  5276. },
  5277. getToneMappingMode: function ( colorSpace ) {
  5278. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5279. },
  5280. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5281. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5282. },
  5283. define: function ( colorSpaces ) {
  5284. Object.assign( this.spaces, colorSpaces );
  5285. },
  5286. // Internal APIs
  5287. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5288. return targetMatrix
  5289. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5290. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5291. },
  5292. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5293. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5294. },
  5295. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5296. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5297. },
  5298. // Deprecated
  5299. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5300. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5301. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5302. },
  5303. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5304. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5305. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5306. },
  5307. };
  5308. /******************************************************************************
  5309. * sRGB definitions
  5310. */
  5311. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5312. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5313. const D65 = [ 0.3127, 0.3290 ];
  5314. ColorManagement.define( {
  5315. [ LinearSRGBColorSpace ]: {
  5316. primaries: REC709_PRIMARIES,
  5317. whitePoint: D65,
  5318. transfer: LinearTransfer,
  5319. toXYZ: LINEAR_REC709_TO_XYZ,
  5320. fromXYZ: XYZ_TO_LINEAR_REC709,
  5321. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5322. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5323. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5324. },
  5325. [ SRGBColorSpace ]: {
  5326. primaries: REC709_PRIMARIES,
  5327. whitePoint: D65,
  5328. transfer: SRGBTransfer,
  5329. toXYZ: LINEAR_REC709_TO_XYZ,
  5330. fromXYZ: XYZ_TO_LINEAR_REC709,
  5331. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5332. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5333. },
  5334. } );
  5335. return ColorManagement;
  5336. }
  5337. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5338. function SRGBToLinear( c ) {
  5339. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5340. }
  5341. function LinearToSRGB( c ) {
  5342. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5343. }
  5344. let _canvas;
  5345. /**
  5346. * A class containing utility functions for images.
  5347. *
  5348. * @hideconstructor
  5349. */
  5350. class ImageUtils {
  5351. /**
  5352. * Returns a data URI containing a representation of the given image.
  5353. *
  5354. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5355. * @param {string} [type='image/png'] - Indicates the image format.
  5356. * @return {string} The data URI.
  5357. */
  5358. static getDataURL( image, type = 'image/png' ) {
  5359. if ( /^data:/i.test( image.src ) ) {
  5360. return image.src;
  5361. }
  5362. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5363. return image.src;
  5364. }
  5365. let canvas;
  5366. if ( image instanceof HTMLCanvasElement ) {
  5367. canvas = image;
  5368. } else {
  5369. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5370. _canvas.width = image.width;
  5371. _canvas.height = image.height;
  5372. const context = _canvas.getContext( '2d' );
  5373. if ( image instanceof ImageData ) {
  5374. context.putImageData( image, 0, 0 );
  5375. } else {
  5376. context.drawImage( image, 0, 0, image.width, image.height );
  5377. }
  5378. canvas = _canvas;
  5379. }
  5380. return canvas.toDataURL( type );
  5381. }
  5382. /**
  5383. * Converts the given sRGB image data to linear color space.
  5384. *
  5385. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5386. * @return {HTMLCanvasElement|Object} The converted image.
  5387. */
  5388. static sRGBToLinear( image ) {
  5389. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5390. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5391. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5392. const canvas = createElementNS( 'canvas' );
  5393. canvas.width = image.width;
  5394. canvas.height = image.height;
  5395. const context = canvas.getContext( '2d' );
  5396. context.drawImage( image, 0, 0, image.width, image.height );
  5397. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5398. const data = imageData.data;
  5399. for ( let i = 0; i < data.length; i ++ ) {
  5400. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5401. }
  5402. context.putImageData( imageData, 0, 0 );
  5403. return canvas;
  5404. } else if ( image.data ) {
  5405. const data = image.data.slice( 0 );
  5406. for ( let i = 0; i < data.length; i ++ ) {
  5407. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5408. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5409. } else {
  5410. // assuming float
  5411. data[ i ] = SRGBToLinear( data[ i ] );
  5412. }
  5413. }
  5414. return {
  5415. data: data,
  5416. width: image.width,
  5417. height: image.height
  5418. };
  5419. } else {
  5420. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5421. return image;
  5422. }
  5423. }
  5424. }
  5425. let _sourceId = 0;
  5426. /**
  5427. * Represents the data source of a texture.
  5428. *
  5429. * The main purpose of this class is to decouple the data definition from the texture
  5430. * definition so the same data can be used with multiple texture instances.
  5431. */
  5432. class Source {
  5433. /**
  5434. * Constructs a new video texture.
  5435. *
  5436. * @param {any} [data=null] - The data definition of a texture.
  5437. */
  5438. constructor( data = null ) {
  5439. /**
  5440. * This flag can be used for type testing.
  5441. *
  5442. * @type {boolean}
  5443. * @readonly
  5444. * @default true
  5445. */
  5446. this.isSource = true;
  5447. /**
  5448. * The ID of the source.
  5449. *
  5450. * @name Source#id
  5451. * @type {number}
  5452. * @readonly
  5453. */
  5454. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5455. /**
  5456. * The UUID of the source.
  5457. *
  5458. * @type {string}
  5459. * @readonly
  5460. */
  5461. this.uuid = generateUUID();
  5462. /**
  5463. * The data definition of a texture.
  5464. *
  5465. * @type {any}
  5466. */
  5467. this.data = data;
  5468. /**
  5469. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5470. * provides more control on how texture data should be processed. When `dataReady` is set
  5471. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5472. * the data into the GPU memory.
  5473. *
  5474. * @type {boolean}
  5475. * @default true
  5476. */
  5477. this.dataReady = true;
  5478. /**
  5479. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5480. *
  5481. * @type {number}
  5482. * @readonly
  5483. * @default 0
  5484. */
  5485. this.version = 0;
  5486. }
  5487. /**
  5488. * Returns the dimensions of the source into the given target vector.
  5489. *
  5490. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5491. * @return {(Vector2|Vector3)} The dimensions of the source.
  5492. */
  5493. getSize( target ) {
  5494. const data = this.data;
  5495. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5496. target.set( data.videoWidth, data.videoHeight, 0 );
  5497. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5498. target.set( data.displayHeight, data.displayWidth, 0 );
  5499. } else if ( data !== null ) {
  5500. target.set( data.width, data.height, data.depth || 0 );
  5501. } else {
  5502. target.set( 0, 0, 0 );
  5503. }
  5504. return target;
  5505. }
  5506. /**
  5507. * When the property is set to `true`, the engine allocates the memory
  5508. * for the texture (if necessary) and triggers the actual texture upload
  5509. * to the GPU next time the source is used.
  5510. *
  5511. * @type {boolean}
  5512. * @default false
  5513. * @param {boolean} value
  5514. */
  5515. set needsUpdate( value ) {
  5516. if ( value === true ) this.version ++;
  5517. }
  5518. /**
  5519. * Serializes the source into JSON.
  5520. *
  5521. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5522. * @return {Object} A JSON object representing the serialized source.
  5523. * @see {@link ObjectLoader#parse}
  5524. */
  5525. toJSON( meta ) {
  5526. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5527. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5528. return meta.images[ this.uuid ];
  5529. }
  5530. const output = {
  5531. uuid: this.uuid,
  5532. url: ''
  5533. };
  5534. const data = this.data;
  5535. if ( data !== null ) {
  5536. let url;
  5537. if ( Array.isArray( data ) ) {
  5538. // cube texture
  5539. url = [];
  5540. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5541. if ( data[ i ].isDataTexture ) {
  5542. url.push( serializeImage( data[ i ].image ) );
  5543. } else {
  5544. url.push( serializeImage( data[ i ] ) );
  5545. }
  5546. }
  5547. } else {
  5548. // texture
  5549. url = serializeImage( data );
  5550. }
  5551. output.url = url;
  5552. }
  5553. if ( ! isRootObject ) {
  5554. meta.images[ this.uuid ] = output;
  5555. }
  5556. return output;
  5557. }
  5558. }
  5559. function serializeImage( image ) {
  5560. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5561. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5562. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5563. // default images
  5564. return ImageUtils.getDataURL( image );
  5565. } else {
  5566. if ( image.data ) {
  5567. // images of DataTexture
  5568. return {
  5569. data: Array.from( image.data ),
  5570. width: image.width,
  5571. height: image.height,
  5572. type: image.data.constructor.name
  5573. };
  5574. } else {
  5575. warn( 'Texture: Unable to serialize Texture.' );
  5576. return {};
  5577. }
  5578. }
  5579. }
  5580. let _textureId = 0;
  5581. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5582. /**
  5583. * Base class for all textures.
  5584. *
  5585. * Note: After the initial use of a texture, its dimensions, format, and type
  5586. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5587. *
  5588. * @augments EventDispatcher
  5589. */
  5590. class Texture extends EventDispatcher {
  5591. /**
  5592. * Constructs a new texture.
  5593. *
  5594. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5595. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5596. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5597. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5598. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5599. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5600. * @param {number} [format=RGBAFormat] - The texture format.
  5601. * @param {number} [type=UnsignedByteType] - The texture type.
  5602. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5603. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5604. */
  5605. 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, colorSpace = NoColorSpace ) {
  5606. super();
  5607. /**
  5608. * This flag can be used for type testing.
  5609. *
  5610. * @type {boolean}
  5611. * @readonly
  5612. * @default true
  5613. */
  5614. this.isTexture = true;
  5615. /**
  5616. * The ID of the texture.
  5617. *
  5618. * @name Texture#id
  5619. * @type {number}
  5620. * @readonly
  5621. */
  5622. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5623. /**
  5624. * The UUID of the texture.
  5625. *
  5626. * @type {string}
  5627. * @readonly
  5628. */
  5629. this.uuid = generateUUID();
  5630. /**
  5631. * The name of the texture.
  5632. *
  5633. * @type {string}
  5634. */
  5635. this.name = '';
  5636. /**
  5637. * The data definition of a texture. A reference to the data source can be
  5638. * shared across textures. This is often useful in context of spritesheets
  5639. * where multiple textures render the same data but with different texture
  5640. * transformations.
  5641. *
  5642. * @type {Source}
  5643. */
  5644. this.source = new Source( image );
  5645. /**
  5646. * An array holding user-defined mipmaps.
  5647. *
  5648. * @type {Array<Object>}
  5649. */
  5650. this.mipmaps = [];
  5651. /**
  5652. * How the texture is applied to the object. The value `UVMapping`
  5653. * is the default, where texture or uv coordinates are used to apply the map.
  5654. *
  5655. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5656. * @default UVMapping
  5657. */
  5658. this.mapping = mapping;
  5659. /**
  5660. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5661. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5662. *
  5663. * @type {number}
  5664. * @default 0
  5665. */
  5666. this.channel = 0;
  5667. /**
  5668. * This defines how the texture is wrapped horizontally and corresponds to
  5669. * *U* in UV mapping.
  5670. *
  5671. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5672. * @default ClampToEdgeWrapping
  5673. */
  5674. this.wrapS = wrapS;
  5675. /**
  5676. * This defines how the texture is wrapped horizontally and corresponds to
  5677. * *V* in UV mapping.
  5678. *
  5679. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5680. * @default ClampToEdgeWrapping
  5681. */
  5682. this.wrapT = wrapT;
  5683. /**
  5684. * How the texture is sampled when a texel covers more than one pixel.
  5685. *
  5686. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5687. * @default LinearFilter
  5688. */
  5689. this.magFilter = magFilter;
  5690. /**
  5691. * How the texture is sampled when a texel covers less than one pixel.
  5692. *
  5693. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5694. * @default LinearMipmapLinearFilter
  5695. */
  5696. this.minFilter = minFilter;
  5697. /**
  5698. * The number of samples taken along the axis through the pixel that has the
  5699. * highest density of texels. By default, this value is `1`. A higher value
  5700. * gives a less blurry result than a basic mipmap, at the cost of more
  5701. * texture samples being used.
  5702. *
  5703. * @type {number}
  5704. * @default Texture.DEFAULT_ANISOTROPY
  5705. */
  5706. this.anisotropy = anisotropy;
  5707. /**
  5708. * The format of the texture.
  5709. *
  5710. * @type {number}
  5711. * @default RGBAFormat
  5712. */
  5713. this.format = format;
  5714. /**
  5715. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5716. * defines how the texture data is going to be stored on the GPU.
  5717. *
  5718. * This property allows to overwrite the default format.
  5719. *
  5720. * @type {?string}
  5721. * @default null
  5722. */
  5723. this.internalFormat = null;
  5724. /**
  5725. * The data type of the texture.
  5726. *
  5727. * @type {number}
  5728. * @default UnsignedByteType
  5729. */
  5730. this.type = type;
  5731. /**
  5732. * How much a single repetition of the texture is offset from the beginning,
  5733. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5734. *
  5735. * @type {Vector2}
  5736. * @default (0,0)
  5737. */
  5738. this.offset = new Vector2( 0, 0 );
  5739. /**
  5740. * How many times the texture is repeated across the surface, in each
  5741. * direction U and V. If repeat is set greater than `1` in either direction,
  5742. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5743. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5744. *
  5745. * @type {Vector2}
  5746. * @default (1,1)
  5747. */
  5748. this.repeat = new Vector2( 1, 1 );
  5749. /**
  5750. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5751. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5752. *
  5753. * @type {Vector2}
  5754. * @default (0,0)
  5755. */
  5756. this.center = new Vector2( 0, 0 );
  5757. /**
  5758. * How much the texture is rotated around the center point, in radians.
  5759. * Positive values are counter-clockwise.
  5760. *
  5761. * @type {number}
  5762. * @default 0
  5763. */
  5764. this.rotation = 0;
  5765. /**
  5766. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5767. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5768. * {@link Texture#rotation}, and {@link Texture#center}.
  5769. *
  5770. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5771. *
  5772. * @type {boolean}
  5773. * @default true
  5774. */
  5775. this.matrixAutoUpdate = true;
  5776. /**
  5777. * The uv-transformation matrix of the texture.
  5778. *
  5779. * @type {Matrix3}
  5780. */
  5781. this.matrix = new Matrix3();
  5782. /**
  5783. * Whether to generate mipmaps (if possible) for a texture.
  5784. *
  5785. * Set this to `false` if you are creating mipmaps manually.
  5786. *
  5787. * @type {boolean}
  5788. * @default true
  5789. */
  5790. this.generateMipmaps = true;
  5791. /**
  5792. * If set to `true`, the alpha channel, if present, is multiplied into the
  5793. * color channels when the texture is uploaded to the GPU.
  5794. *
  5795. * Note that this property has no effect when using `ImageBitmap`. You need to
  5796. * configure premultiply alpha on bitmap creation instead.
  5797. *
  5798. * @type {boolean}
  5799. * @default false
  5800. */
  5801. this.premultiplyAlpha = false;
  5802. /**
  5803. * If set to `true`, the texture is flipped along the vertical axis when
  5804. * uploaded to the GPU.
  5805. *
  5806. * Note that this property has no effect when using `ImageBitmap`. You need to
  5807. * configure the flip on bitmap creation instead.
  5808. *
  5809. * @type {boolean}
  5810. * @default true
  5811. */
  5812. this.flipY = true;
  5813. /**
  5814. * Specifies the alignment requirements for the start of each pixel row in memory.
  5815. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5816. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5817. *
  5818. * @type {number}
  5819. * @default 4
  5820. */
  5821. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5822. /**
  5823. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5824. *
  5825. * @type {string}
  5826. * @default NoColorSpace
  5827. */
  5828. this.colorSpace = colorSpace;
  5829. /**
  5830. * An object that can be used to store custom data about the texture. It
  5831. * should not hold references to functions as these will not be cloned.
  5832. *
  5833. * @type {Object}
  5834. */
  5835. this.userData = {};
  5836. /**
  5837. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5838. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5839. *
  5840. * @type {Array<Object>}
  5841. */
  5842. this.updateRanges = [];
  5843. /**
  5844. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5845. *
  5846. * @type {number}
  5847. * @readonly
  5848. * @default 0
  5849. */
  5850. this.version = 0;
  5851. /**
  5852. * A callback function, called when the texture is updated (e.g., when
  5853. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5854. *
  5855. * @type {?Function}
  5856. * @default null
  5857. */
  5858. this.onUpdate = null;
  5859. /**
  5860. * An optional back reference to the textures render target.
  5861. *
  5862. * @type {?(RenderTarget|WebGLRenderTarget)}
  5863. * @default null
  5864. */
  5865. this.renderTarget = null;
  5866. /**
  5867. * Indicates whether a texture belongs to a render target or not.
  5868. *
  5869. * @type {boolean}
  5870. * @readonly
  5871. * @default false
  5872. */
  5873. this.isRenderTargetTexture = false;
  5874. /**
  5875. * Indicates if a texture should be handled like a texture array.
  5876. *
  5877. * @type {boolean}
  5878. * @readonly
  5879. * @default false
  5880. */
  5881. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5882. /**
  5883. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5884. * (only relevant for render target textures).
  5885. *
  5886. * @type {number}
  5887. * @readonly
  5888. * @default 0
  5889. */
  5890. this.pmremVersion = 0;
  5891. }
  5892. /**
  5893. * The width of the texture in pixels.
  5894. */
  5895. get width() {
  5896. return this.source.getSize( _tempVec3 ).x;
  5897. }
  5898. /**
  5899. * The height of the texture in pixels.
  5900. */
  5901. get height() {
  5902. return this.source.getSize( _tempVec3 ).y;
  5903. }
  5904. /**
  5905. * The depth of the texture in pixels.
  5906. */
  5907. get depth() {
  5908. return this.source.getSize( _tempVec3 ).z;
  5909. }
  5910. /**
  5911. * The image object holding the texture data.
  5912. *
  5913. * @type {?Object}
  5914. */
  5915. get image() {
  5916. return this.source.data;
  5917. }
  5918. set image( value = null ) {
  5919. this.source.data = value;
  5920. }
  5921. /**
  5922. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5923. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5924. */
  5925. updateMatrix() {
  5926. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5927. }
  5928. /**
  5929. * Adds a range of data in the data texture to be updated on the GPU.
  5930. *
  5931. * @param {number} start - Position at which to start update.
  5932. * @param {number} count - The number of components to update.
  5933. */
  5934. addUpdateRange( start, count ) {
  5935. this.updateRanges.push( { start, count } );
  5936. }
  5937. /**
  5938. * Clears the update ranges.
  5939. */
  5940. clearUpdateRanges() {
  5941. this.updateRanges.length = 0;
  5942. }
  5943. /**
  5944. * Returns a new texture with copied values from this instance.
  5945. *
  5946. * @return {Texture} A clone of this instance.
  5947. */
  5948. clone() {
  5949. return new this.constructor().copy( this );
  5950. }
  5951. /**
  5952. * Copies the values of the given texture to this instance.
  5953. *
  5954. * @param {Texture} source - The texture to copy.
  5955. * @return {Texture} A reference to this instance.
  5956. */
  5957. copy( source ) {
  5958. this.name = source.name;
  5959. this.source = source.source;
  5960. this.mipmaps = source.mipmaps.slice( 0 );
  5961. this.mapping = source.mapping;
  5962. this.channel = source.channel;
  5963. this.wrapS = source.wrapS;
  5964. this.wrapT = source.wrapT;
  5965. this.magFilter = source.magFilter;
  5966. this.minFilter = source.minFilter;
  5967. this.anisotropy = source.anisotropy;
  5968. this.format = source.format;
  5969. this.internalFormat = source.internalFormat;
  5970. this.type = source.type;
  5971. this.offset.copy( source.offset );
  5972. this.repeat.copy( source.repeat );
  5973. this.center.copy( source.center );
  5974. this.rotation = source.rotation;
  5975. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5976. this.matrix.copy( source.matrix );
  5977. this.generateMipmaps = source.generateMipmaps;
  5978. this.premultiplyAlpha = source.premultiplyAlpha;
  5979. this.flipY = source.flipY;
  5980. this.unpackAlignment = source.unpackAlignment;
  5981. this.colorSpace = source.colorSpace;
  5982. this.renderTarget = source.renderTarget;
  5983. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5984. this.isArrayTexture = source.isArrayTexture;
  5985. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5986. this.needsUpdate = true;
  5987. return this;
  5988. }
  5989. /**
  5990. * Sets this texture's properties based on `values`.
  5991. * @param {Object} values - A container with texture parameters.
  5992. */
  5993. setValues( values ) {
  5994. for ( const key in values ) {
  5995. const newValue = values[ key ];
  5996. if ( newValue === undefined ) {
  5997. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5998. continue;
  5999. }
  6000. const currentValue = this[ key ];
  6001. if ( currentValue === undefined ) {
  6002. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  6003. continue;
  6004. }
  6005. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  6006. currentValue.copy( newValue );
  6007. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  6008. currentValue.copy( newValue );
  6009. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  6010. currentValue.copy( newValue );
  6011. } else {
  6012. this[ key ] = newValue;
  6013. }
  6014. }
  6015. }
  6016. /**
  6017. * Serializes the texture into JSON.
  6018. *
  6019. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  6020. * @return {Object} A JSON object representing the serialized texture.
  6021. * @see {@link ObjectLoader#parse}
  6022. */
  6023. toJSON( meta ) {
  6024. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  6025. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6026. return meta.textures[ this.uuid ];
  6027. }
  6028. const output = {
  6029. metadata: {
  6030. version: 4.7,
  6031. type: 'Texture',
  6032. generator: 'Texture.toJSON'
  6033. },
  6034. uuid: this.uuid,
  6035. name: this.name,
  6036. image: this.source.toJSON( meta ).uuid,
  6037. mapping: this.mapping,
  6038. channel: this.channel,
  6039. repeat: [ this.repeat.x, this.repeat.y ],
  6040. offset: [ this.offset.x, this.offset.y ],
  6041. center: [ this.center.x, this.center.y ],
  6042. rotation: this.rotation,
  6043. wrap: [ this.wrapS, this.wrapT ],
  6044. format: this.format,
  6045. internalFormat: this.internalFormat,
  6046. type: this.type,
  6047. colorSpace: this.colorSpace,
  6048. minFilter: this.minFilter,
  6049. magFilter: this.magFilter,
  6050. anisotropy: this.anisotropy,
  6051. flipY: this.flipY,
  6052. generateMipmaps: this.generateMipmaps,
  6053. premultiplyAlpha: this.premultiplyAlpha,
  6054. unpackAlignment: this.unpackAlignment
  6055. };
  6056. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6057. if ( ! isRootObject ) {
  6058. meta.textures[ this.uuid ] = output;
  6059. }
  6060. return output;
  6061. }
  6062. /**
  6063. * Frees the GPU-related resources allocated by this instance. Call this
  6064. * method whenever this instance is no longer used in your app.
  6065. *
  6066. * @fires Texture#dispose
  6067. */
  6068. dispose() {
  6069. /**
  6070. * Fires when the texture has been disposed of.
  6071. *
  6072. * @event Texture#dispose
  6073. * @type {Object}
  6074. */
  6075. this.dispatchEvent( { type: 'dispose' } );
  6076. }
  6077. /**
  6078. * Transforms the given uv vector with the textures uv transformation matrix.
  6079. *
  6080. * @param {Vector2} uv - The uv vector.
  6081. * @return {Vector2} The transformed uv vector.
  6082. */
  6083. transformUv( uv ) {
  6084. if ( this.mapping !== UVMapping ) return uv;
  6085. uv.applyMatrix3( this.matrix );
  6086. if ( uv.x < 0 || uv.x > 1 ) {
  6087. switch ( this.wrapS ) {
  6088. case RepeatWrapping:
  6089. uv.x = uv.x - Math.floor( uv.x );
  6090. break;
  6091. case ClampToEdgeWrapping:
  6092. uv.x = uv.x < 0 ? 0 : 1;
  6093. break;
  6094. case MirroredRepeatWrapping:
  6095. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6096. uv.x = Math.ceil( uv.x ) - uv.x;
  6097. } else {
  6098. uv.x = uv.x - Math.floor( uv.x );
  6099. }
  6100. break;
  6101. }
  6102. }
  6103. if ( uv.y < 0 || uv.y > 1 ) {
  6104. switch ( this.wrapT ) {
  6105. case RepeatWrapping:
  6106. uv.y = uv.y - Math.floor( uv.y );
  6107. break;
  6108. case ClampToEdgeWrapping:
  6109. uv.y = uv.y < 0 ? 0 : 1;
  6110. break;
  6111. case MirroredRepeatWrapping:
  6112. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6113. uv.y = Math.ceil( uv.y ) - uv.y;
  6114. } else {
  6115. uv.y = uv.y - Math.floor( uv.y );
  6116. }
  6117. break;
  6118. }
  6119. }
  6120. if ( this.flipY ) {
  6121. uv.y = 1 - uv.y;
  6122. }
  6123. return uv;
  6124. }
  6125. /**
  6126. * Setting this property to `true` indicates the engine the texture
  6127. * must be updated in the next render. This triggers a texture upload
  6128. * to the GPU and ensures correct texture parameter configuration.
  6129. *
  6130. * @type {boolean}
  6131. * @default false
  6132. * @param {boolean} value
  6133. */
  6134. set needsUpdate( value ) {
  6135. if ( value === true ) {
  6136. this.version ++;
  6137. this.source.needsUpdate = true;
  6138. }
  6139. }
  6140. /**
  6141. * Setting this property to `true` indicates the engine the PMREM
  6142. * must be regenerated.
  6143. *
  6144. * @type {boolean}
  6145. * @default false
  6146. * @param {boolean} value
  6147. */
  6148. set needsPMREMUpdate( value ) {
  6149. if ( value === true ) {
  6150. this.pmremVersion ++;
  6151. }
  6152. }
  6153. }
  6154. /**
  6155. * The default image for all textures.
  6156. *
  6157. * @static
  6158. * @type {?Image}
  6159. * @default null
  6160. */
  6161. Texture.DEFAULT_IMAGE = null;
  6162. /**
  6163. * The default mapping for all textures.
  6164. *
  6165. * @static
  6166. * @type {number}
  6167. * @default UVMapping
  6168. */
  6169. Texture.DEFAULT_MAPPING = UVMapping;
  6170. /**
  6171. * The default anisotropy value for all textures.
  6172. *
  6173. * @static
  6174. * @type {number}
  6175. * @default 1
  6176. */
  6177. Texture.DEFAULT_ANISOTROPY = 1;
  6178. /**
  6179. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6180. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6181. *
  6182. * - A point in 4D space.
  6183. * - A direction and length in 4D space. In three.js the length will
  6184. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6185. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6186. * - Any arbitrary ordered quadruplet of numbers.
  6187. *
  6188. * There are other things a 4D vector can be used to represent, however these
  6189. * are the most common uses in *three.js*.
  6190. *
  6191. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6192. * the corresponding order.
  6193. * ```js
  6194. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6195. *
  6196. * //no arguments; will be initialised to (0, 0, 0, 1)
  6197. * const b = new THREE.Vector4( );
  6198. *
  6199. * const d = a.dot( b );
  6200. * ```
  6201. */
  6202. class Vector4 {
  6203. /**
  6204. * Constructs a new 4D vector.
  6205. *
  6206. * @param {number} [x=0] - The x value of this vector.
  6207. * @param {number} [y=0] - The y value of this vector.
  6208. * @param {number} [z=0] - The z value of this vector.
  6209. * @param {number} [w=1] - The w value of this vector.
  6210. */
  6211. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6212. /**
  6213. * This flag can be used for type testing.
  6214. *
  6215. * @type {boolean}
  6216. * @readonly
  6217. * @default true
  6218. */
  6219. Vector4.prototype.isVector4 = true;
  6220. /**
  6221. * The x value of this vector.
  6222. *
  6223. * @type {number}
  6224. */
  6225. this.x = x;
  6226. /**
  6227. * The y value of this vector.
  6228. *
  6229. * @type {number}
  6230. */
  6231. this.y = y;
  6232. /**
  6233. * The z value of this vector.
  6234. *
  6235. * @type {number}
  6236. */
  6237. this.z = z;
  6238. /**
  6239. * The w value of this vector.
  6240. *
  6241. * @type {number}
  6242. */
  6243. this.w = w;
  6244. }
  6245. /**
  6246. * Alias for {@link Vector4#z}.
  6247. *
  6248. * @type {number}
  6249. */
  6250. get width() {
  6251. return this.z;
  6252. }
  6253. set width( value ) {
  6254. this.z = value;
  6255. }
  6256. /**
  6257. * Alias for {@link Vector4#w}.
  6258. *
  6259. * @type {number}
  6260. */
  6261. get height() {
  6262. return this.w;
  6263. }
  6264. set height( value ) {
  6265. this.w = value;
  6266. }
  6267. /**
  6268. * Sets the vector components.
  6269. *
  6270. * @param {number} x - The value of the x component.
  6271. * @param {number} y - The value of the y component.
  6272. * @param {number} z - The value of the z component.
  6273. * @param {number} w - The value of the w component.
  6274. * @return {Vector4} A reference to this vector.
  6275. */
  6276. set( x, y, z, w ) {
  6277. this.x = x;
  6278. this.y = y;
  6279. this.z = z;
  6280. this.w = w;
  6281. return this;
  6282. }
  6283. /**
  6284. * Sets the vector components to the same value.
  6285. *
  6286. * @param {number} scalar - The value to set for all vector components.
  6287. * @return {Vector4} A reference to this vector.
  6288. */
  6289. setScalar( scalar ) {
  6290. this.x = scalar;
  6291. this.y = scalar;
  6292. this.z = scalar;
  6293. this.w = scalar;
  6294. return this;
  6295. }
  6296. /**
  6297. * Sets the vector's x component to the given value
  6298. *
  6299. * @param {number} x - The value to set.
  6300. * @return {Vector4} A reference to this vector.
  6301. */
  6302. setX( x ) {
  6303. this.x = x;
  6304. return this;
  6305. }
  6306. /**
  6307. * Sets the vector's y component to the given value
  6308. *
  6309. * @param {number} y - The value to set.
  6310. * @return {Vector4} A reference to this vector.
  6311. */
  6312. setY( y ) {
  6313. this.y = y;
  6314. return this;
  6315. }
  6316. /**
  6317. * Sets the vector's z component to the given value
  6318. *
  6319. * @param {number} z - The value to set.
  6320. * @return {Vector4} A reference to this vector.
  6321. */
  6322. setZ( z ) {
  6323. this.z = z;
  6324. return this;
  6325. }
  6326. /**
  6327. * Sets the vector's w component to the given value
  6328. *
  6329. * @param {number} w - The value to set.
  6330. * @return {Vector4} A reference to this vector.
  6331. */
  6332. setW( w ) {
  6333. this.w = w;
  6334. return this;
  6335. }
  6336. /**
  6337. * Allows to set a vector component with an index.
  6338. *
  6339. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6340. * `2` equals to z, `3` equals to w.
  6341. * @param {number} value - The value to set.
  6342. * @return {Vector4} A reference to this vector.
  6343. */
  6344. setComponent( index, value ) {
  6345. switch ( index ) {
  6346. case 0: this.x = value; break;
  6347. case 1: this.y = value; break;
  6348. case 2: this.z = value; break;
  6349. case 3: this.w = value; break;
  6350. default: throw new Error( 'index is out of range: ' + index );
  6351. }
  6352. return this;
  6353. }
  6354. /**
  6355. * Returns the value of the vector component which matches the given index.
  6356. *
  6357. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6358. * `2` equals to z, `3` equals to w.
  6359. * @return {number} A vector component value.
  6360. */
  6361. getComponent( index ) {
  6362. switch ( index ) {
  6363. case 0: return this.x;
  6364. case 1: return this.y;
  6365. case 2: return this.z;
  6366. case 3: return this.w;
  6367. default: throw new Error( 'index is out of range: ' + index );
  6368. }
  6369. }
  6370. /**
  6371. * Returns a new vector with copied values from this instance.
  6372. *
  6373. * @return {Vector4} A clone of this instance.
  6374. */
  6375. clone() {
  6376. return new this.constructor( this.x, this.y, this.z, this.w );
  6377. }
  6378. /**
  6379. * Copies the values of the given vector to this instance.
  6380. *
  6381. * @param {Vector3|Vector4} v - The vector to copy.
  6382. * @return {Vector4} A reference to this vector.
  6383. */
  6384. copy( v ) {
  6385. this.x = v.x;
  6386. this.y = v.y;
  6387. this.z = v.z;
  6388. this.w = ( v.w !== undefined ) ? v.w : 1;
  6389. return this;
  6390. }
  6391. /**
  6392. * Adds the given vector to this instance.
  6393. *
  6394. * @param {Vector4} v - The vector to add.
  6395. * @return {Vector4} A reference to this vector.
  6396. */
  6397. add( v ) {
  6398. this.x += v.x;
  6399. this.y += v.y;
  6400. this.z += v.z;
  6401. this.w += v.w;
  6402. return this;
  6403. }
  6404. /**
  6405. * Adds the given scalar value to all components of this instance.
  6406. *
  6407. * @param {number} s - The scalar to add.
  6408. * @return {Vector4} A reference to this vector.
  6409. */
  6410. addScalar( s ) {
  6411. this.x += s;
  6412. this.y += s;
  6413. this.z += s;
  6414. this.w += s;
  6415. return this;
  6416. }
  6417. /**
  6418. * Adds the given vectors and stores the result in this instance.
  6419. *
  6420. * @param {Vector4} a - The first vector.
  6421. * @param {Vector4} b - The second vector.
  6422. * @return {Vector4} A reference to this vector.
  6423. */
  6424. addVectors( a, b ) {
  6425. this.x = a.x + b.x;
  6426. this.y = a.y + b.y;
  6427. this.z = a.z + b.z;
  6428. this.w = a.w + b.w;
  6429. return this;
  6430. }
  6431. /**
  6432. * Adds the given vector scaled by the given factor to this instance.
  6433. *
  6434. * @param {Vector4} v - The vector.
  6435. * @param {number} s - The factor that scales `v`.
  6436. * @return {Vector4} A reference to this vector.
  6437. */
  6438. addScaledVector( v, s ) {
  6439. this.x += v.x * s;
  6440. this.y += v.y * s;
  6441. this.z += v.z * s;
  6442. this.w += v.w * s;
  6443. return this;
  6444. }
  6445. /**
  6446. * Subtracts the given vector from this instance.
  6447. *
  6448. * @param {Vector4} v - The vector to subtract.
  6449. * @return {Vector4} A reference to this vector.
  6450. */
  6451. sub( v ) {
  6452. this.x -= v.x;
  6453. this.y -= v.y;
  6454. this.z -= v.z;
  6455. this.w -= v.w;
  6456. return this;
  6457. }
  6458. /**
  6459. * Subtracts the given scalar value from all components of this instance.
  6460. *
  6461. * @param {number} s - The scalar to subtract.
  6462. * @return {Vector4} A reference to this vector.
  6463. */
  6464. subScalar( s ) {
  6465. this.x -= s;
  6466. this.y -= s;
  6467. this.z -= s;
  6468. this.w -= s;
  6469. return this;
  6470. }
  6471. /**
  6472. * Subtracts the given vectors and stores the result in this instance.
  6473. *
  6474. * @param {Vector4} a - The first vector.
  6475. * @param {Vector4} b - The second vector.
  6476. * @return {Vector4} A reference to this vector.
  6477. */
  6478. subVectors( a, b ) {
  6479. this.x = a.x - b.x;
  6480. this.y = a.y - b.y;
  6481. this.z = a.z - b.z;
  6482. this.w = a.w - b.w;
  6483. return this;
  6484. }
  6485. /**
  6486. * Multiplies the given vector with this instance.
  6487. *
  6488. * @param {Vector4} v - The vector to multiply.
  6489. * @return {Vector4} A reference to this vector.
  6490. */
  6491. multiply( v ) {
  6492. this.x *= v.x;
  6493. this.y *= v.y;
  6494. this.z *= v.z;
  6495. this.w *= v.w;
  6496. return this;
  6497. }
  6498. /**
  6499. * Multiplies the given scalar value with all components of this instance.
  6500. *
  6501. * @param {number} scalar - The scalar to multiply.
  6502. * @return {Vector4} A reference to this vector.
  6503. */
  6504. multiplyScalar( scalar ) {
  6505. this.x *= scalar;
  6506. this.y *= scalar;
  6507. this.z *= scalar;
  6508. this.w *= scalar;
  6509. return this;
  6510. }
  6511. /**
  6512. * Multiplies this vector with the given 4x4 matrix.
  6513. *
  6514. * @param {Matrix4} m - The 4x4 matrix.
  6515. * @return {Vector4} A reference to this vector.
  6516. */
  6517. applyMatrix4( m ) {
  6518. const x = this.x, y = this.y, z = this.z, w = this.w;
  6519. const e = m.elements;
  6520. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6521. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6522. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6523. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6524. return this;
  6525. }
  6526. /**
  6527. * Divides this instance by the given vector.
  6528. *
  6529. * @param {Vector4} v - The vector to divide.
  6530. * @return {Vector4} A reference to this vector.
  6531. */
  6532. divide( v ) {
  6533. this.x /= v.x;
  6534. this.y /= v.y;
  6535. this.z /= v.z;
  6536. this.w /= v.w;
  6537. return this;
  6538. }
  6539. /**
  6540. * Divides this vector by the given scalar.
  6541. *
  6542. * @param {number} scalar - The scalar to divide.
  6543. * @return {Vector4} A reference to this vector.
  6544. */
  6545. divideScalar( scalar ) {
  6546. return this.multiplyScalar( 1 / scalar );
  6547. }
  6548. /**
  6549. * Sets the x, y and z components of this
  6550. * vector to the quaternion's axis and w to the angle.
  6551. *
  6552. * @param {Quaternion} q - The Quaternion to set.
  6553. * @return {Vector4} A reference to this vector.
  6554. */
  6555. setAxisAngleFromQuaternion( q ) {
  6556. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6557. // q is assumed to be normalized
  6558. this.w = 2 * Math.acos( q.w );
  6559. const s = Math.sqrt( 1 - q.w * q.w );
  6560. if ( s < 0.0001 ) {
  6561. this.x = 1;
  6562. this.y = 0;
  6563. this.z = 0;
  6564. } else {
  6565. this.x = q.x / s;
  6566. this.y = q.y / s;
  6567. this.z = q.z / s;
  6568. }
  6569. return this;
  6570. }
  6571. /**
  6572. * Sets the x, y and z components of this
  6573. * vector to the axis of rotation and w to the angle.
  6574. *
  6575. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6576. * @return {Vector4} A reference to this vector.
  6577. */
  6578. setAxisAngleFromRotationMatrix( m ) {
  6579. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6580. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6581. let angle, x, y, z; // variables for result
  6582. const epsilon = 0.01, // margin to allow for rounding errors
  6583. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6584. te = m.elements,
  6585. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6586. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6587. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6588. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6589. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6590. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6591. // singularity found
  6592. // first check for identity matrix which must have +1 for all terms
  6593. // in leading diagonal and zero in other terms
  6594. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6595. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6596. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6597. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6598. // this singularity is identity matrix so angle = 0
  6599. this.set( 1, 0, 0, 0 );
  6600. return this; // zero angle, arbitrary axis
  6601. }
  6602. // otherwise this singularity is angle = 180
  6603. angle = Math.PI;
  6604. const xx = ( m11 + 1 ) / 2;
  6605. const yy = ( m22 + 1 ) / 2;
  6606. const zz = ( m33 + 1 ) / 2;
  6607. const xy = ( m12 + m21 ) / 4;
  6608. const xz = ( m13 + m31 ) / 4;
  6609. const yz = ( m23 + m32 ) / 4;
  6610. if ( ( xx > yy ) && ( xx > zz ) ) {
  6611. // m11 is the largest diagonal term
  6612. if ( xx < epsilon ) {
  6613. x = 0;
  6614. y = 0.707106781;
  6615. z = 0.707106781;
  6616. } else {
  6617. x = Math.sqrt( xx );
  6618. y = xy / x;
  6619. z = xz / x;
  6620. }
  6621. } else if ( yy > zz ) {
  6622. // m22 is the largest diagonal term
  6623. if ( yy < epsilon ) {
  6624. x = 0.707106781;
  6625. y = 0;
  6626. z = 0.707106781;
  6627. } else {
  6628. y = Math.sqrt( yy );
  6629. x = xy / y;
  6630. z = yz / y;
  6631. }
  6632. } else {
  6633. // m33 is the largest diagonal term so base result on this
  6634. if ( zz < epsilon ) {
  6635. x = 0.707106781;
  6636. y = 0.707106781;
  6637. z = 0;
  6638. } else {
  6639. z = Math.sqrt( zz );
  6640. x = xz / z;
  6641. y = yz / z;
  6642. }
  6643. }
  6644. this.set( x, y, z, angle );
  6645. return this; // return 180 deg rotation
  6646. }
  6647. // as we have reached here there are no singularities so we can handle normally
  6648. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6649. ( m13 - m31 ) * ( m13 - m31 ) +
  6650. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6651. if ( Math.abs( s ) < 0.001 ) s = 1;
  6652. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6653. // caught by singularity test above, but I've left it in just in case
  6654. this.x = ( m32 - m23 ) / s;
  6655. this.y = ( m13 - m31 ) / s;
  6656. this.z = ( m21 - m12 ) / s;
  6657. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6658. return this;
  6659. }
  6660. /**
  6661. * Sets the vector components to the position elements of the
  6662. * given transformation matrix.
  6663. *
  6664. * @param {Matrix4} m - The 4x4 matrix.
  6665. * @return {Vector4} A reference to this vector.
  6666. */
  6667. setFromMatrixPosition( m ) {
  6668. const e = m.elements;
  6669. this.x = e[ 12 ];
  6670. this.y = e[ 13 ];
  6671. this.z = e[ 14 ];
  6672. this.w = e[ 15 ];
  6673. return this;
  6674. }
  6675. /**
  6676. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6677. * value, replace that value with the corresponding min value.
  6678. *
  6679. * @param {Vector4} v - The vector.
  6680. * @return {Vector4} A reference to this vector.
  6681. */
  6682. min( v ) {
  6683. this.x = Math.min( this.x, v.x );
  6684. this.y = Math.min( this.y, v.y );
  6685. this.z = Math.min( this.z, v.z );
  6686. this.w = Math.min( this.w, v.w );
  6687. return this;
  6688. }
  6689. /**
  6690. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6691. * value, replace that value with the corresponding max value.
  6692. *
  6693. * @param {Vector4} v - The vector.
  6694. * @return {Vector4} A reference to this vector.
  6695. */
  6696. max( v ) {
  6697. this.x = Math.max( this.x, v.x );
  6698. this.y = Math.max( this.y, v.y );
  6699. this.z = Math.max( this.z, v.z );
  6700. this.w = Math.max( this.w, v.w );
  6701. return this;
  6702. }
  6703. /**
  6704. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6705. * value, it is replaced by the corresponding value.
  6706. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6707. * it is replaced by the corresponding value.
  6708. *
  6709. * @param {Vector4} min - The minimum x, y and z values.
  6710. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6711. * @return {Vector4} A reference to this vector.
  6712. */
  6713. clamp( min, max ) {
  6714. // assumes min < max, componentwise
  6715. this.x = clamp( this.x, min.x, max.x );
  6716. this.y = clamp( this.y, min.y, max.y );
  6717. this.z = clamp( this.z, min.z, max.z );
  6718. this.w = clamp( this.w, min.w, max.w );
  6719. return this;
  6720. }
  6721. /**
  6722. * If this vector's x, y, z or w values are greater than the max value, they are
  6723. * replaced by the max value.
  6724. * If this vector's x, y, z or w values are less than the min value, they are
  6725. * replaced by the min value.
  6726. *
  6727. * @param {number} minVal - The minimum value the components will be clamped to.
  6728. * @param {number} maxVal - The maximum value the components will be clamped to.
  6729. * @return {Vector4} A reference to this vector.
  6730. */
  6731. clampScalar( minVal, maxVal ) {
  6732. this.x = clamp( this.x, minVal, maxVal );
  6733. this.y = clamp( this.y, minVal, maxVal );
  6734. this.z = clamp( this.z, minVal, maxVal );
  6735. this.w = clamp( this.w, minVal, maxVal );
  6736. return this;
  6737. }
  6738. /**
  6739. * If this vector's length is greater than the max value, it is replaced by
  6740. * the max value.
  6741. * If this vector's length is less than the min value, it is replaced by the
  6742. * min value.
  6743. *
  6744. * @param {number} min - The minimum value the vector length will be clamped to.
  6745. * @param {number} max - The maximum value the vector length will be clamped to.
  6746. * @return {Vector4} A reference to this vector.
  6747. */
  6748. clampLength( min, max ) {
  6749. const length = this.length();
  6750. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6751. }
  6752. /**
  6753. * The components of this vector are rounded down to the nearest integer value.
  6754. *
  6755. * @return {Vector4} A reference to this vector.
  6756. */
  6757. floor() {
  6758. this.x = Math.floor( this.x );
  6759. this.y = Math.floor( this.y );
  6760. this.z = Math.floor( this.z );
  6761. this.w = Math.floor( this.w );
  6762. return this;
  6763. }
  6764. /**
  6765. * The components of this vector are rounded up to the nearest integer value.
  6766. *
  6767. * @return {Vector4} A reference to this vector.
  6768. */
  6769. ceil() {
  6770. this.x = Math.ceil( this.x );
  6771. this.y = Math.ceil( this.y );
  6772. this.z = Math.ceil( this.z );
  6773. this.w = Math.ceil( this.w );
  6774. return this;
  6775. }
  6776. /**
  6777. * The components of this vector are rounded to the nearest integer value
  6778. *
  6779. * @return {Vector4} A reference to this vector.
  6780. */
  6781. round() {
  6782. this.x = Math.round( this.x );
  6783. this.y = Math.round( this.y );
  6784. this.z = Math.round( this.z );
  6785. this.w = Math.round( this.w );
  6786. return this;
  6787. }
  6788. /**
  6789. * The components of this vector are rounded towards zero (up if negative,
  6790. * down if positive) to an integer value.
  6791. *
  6792. * @return {Vector4} A reference to this vector.
  6793. */
  6794. roundToZero() {
  6795. this.x = Math.trunc( this.x );
  6796. this.y = Math.trunc( this.y );
  6797. this.z = Math.trunc( this.z );
  6798. this.w = Math.trunc( this.w );
  6799. return this;
  6800. }
  6801. /**
  6802. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6803. *
  6804. * @return {Vector4} A reference to this vector.
  6805. */
  6806. negate() {
  6807. this.x = - this.x;
  6808. this.y = - this.y;
  6809. this.z = - this.z;
  6810. this.w = - this.w;
  6811. return this;
  6812. }
  6813. /**
  6814. * Calculates the dot product of the given vector with this instance.
  6815. *
  6816. * @param {Vector4} v - The vector to compute the dot product with.
  6817. * @return {number} The result of the dot product.
  6818. */
  6819. dot( v ) {
  6820. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6821. }
  6822. /**
  6823. * Computes the square of the Euclidean length (straight-line length) from
  6824. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6825. * compare the length squared instead as it is slightly more efficient to calculate.
  6826. *
  6827. * @return {number} The square length of this vector.
  6828. */
  6829. lengthSq() {
  6830. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6831. }
  6832. /**
  6833. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6834. *
  6835. * @return {number} The length of this vector.
  6836. */
  6837. length() {
  6838. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6839. }
  6840. /**
  6841. * Computes the Manhattan length of this vector.
  6842. *
  6843. * @return {number} The length of this vector.
  6844. */
  6845. manhattanLength() {
  6846. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6847. }
  6848. /**
  6849. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6850. * with the same direction as this one, but with a vector length of `1`.
  6851. *
  6852. * @return {Vector4} A reference to this vector.
  6853. */
  6854. normalize() {
  6855. return this.divideScalar( this.length() || 1 );
  6856. }
  6857. /**
  6858. * Sets this vector to a vector with the same direction as this one, but
  6859. * with the specified length.
  6860. *
  6861. * @param {number} length - The new length of this vector.
  6862. * @return {Vector4} A reference to this vector.
  6863. */
  6864. setLength( length ) {
  6865. return this.normalize().multiplyScalar( length );
  6866. }
  6867. /**
  6868. * Linearly interpolates between the given vector and this instance, where
  6869. * alpha is the percent distance along the line - alpha = 0 will be this
  6870. * vector, and alpha = 1 will be the given one.
  6871. *
  6872. * @param {Vector4} v - The vector to interpolate towards.
  6873. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6874. * @return {Vector4} A reference to this vector.
  6875. */
  6876. lerp( v, alpha ) {
  6877. this.x += ( v.x - this.x ) * alpha;
  6878. this.y += ( v.y - this.y ) * alpha;
  6879. this.z += ( v.z - this.z ) * alpha;
  6880. this.w += ( v.w - this.w ) * alpha;
  6881. return this;
  6882. }
  6883. /**
  6884. * Linearly interpolates between the given vectors, where alpha is the percent
  6885. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6886. * be the second one. The result is stored in this instance.
  6887. *
  6888. * @param {Vector4} v1 - The first vector.
  6889. * @param {Vector4} v2 - The second vector.
  6890. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6891. * @return {Vector4} A reference to this vector.
  6892. */
  6893. lerpVectors( v1, v2, alpha ) {
  6894. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6895. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6896. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6897. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6898. return this;
  6899. }
  6900. /**
  6901. * Returns `true` if this vector is equal with the given one.
  6902. *
  6903. * @param {Vector4} v - The vector to test for equality.
  6904. * @return {boolean} Whether this vector is equal with the given one.
  6905. */
  6906. equals( v ) {
  6907. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6908. }
  6909. /**
  6910. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6911. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6912. *
  6913. * @param {Array<number>} array - An array holding the vector component values.
  6914. * @param {number} [offset=0] - The offset into the array.
  6915. * @return {Vector4} A reference to this vector.
  6916. */
  6917. fromArray( array, offset = 0 ) {
  6918. this.x = array[ offset ];
  6919. this.y = array[ offset + 1 ];
  6920. this.z = array[ offset + 2 ];
  6921. this.w = array[ offset + 3 ];
  6922. return this;
  6923. }
  6924. /**
  6925. * Writes the components of this vector to the given array. If no array is provided,
  6926. * the method returns a new instance.
  6927. *
  6928. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6929. * @param {number} [offset=0] - Index of the first element in the array.
  6930. * @return {Array<number>} The vector components.
  6931. */
  6932. toArray( array = [], offset = 0 ) {
  6933. array[ offset ] = this.x;
  6934. array[ offset + 1 ] = this.y;
  6935. array[ offset + 2 ] = this.z;
  6936. array[ offset + 3 ] = this.w;
  6937. return array;
  6938. }
  6939. /**
  6940. * Sets the components of this vector from the given buffer attribute.
  6941. *
  6942. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6943. * @param {number} index - The index into the attribute.
  6944. * @return {Vector4} A reference to this vector.
  6945. */
  6946. fromBufferAttribute( attribute, index ) {
  6947. this.x = attribute.getX( index );
  6948. this.y = attribute.getY( index );
  6949. this.z = attribute.getZ( index );
  6950. this.w = attribute.getW( index );
  6951. return this;
  6952. }
  6953. /**
  6954. * Sets each component of this vector to a pseudo-random value between `0` and
  6955. * `1`, excluding `1`.
  6956. *
  6957. * @return {Vector4} A reference to this vector.
  6958. */
  6959. random() {
  6960. this.x = Math.random();
  6961. this.y = Math.random();
  6962. this.z = Math.random();
  6963. this.w = Math.random();
  6964. return this;
  6965. }
  6966. *[ Symbol.iterator ]() {
  6967. yield this.x;
  6968. yield this.y;
  6969. yield this.z;
  6970. yield this.w;
  6971. }
  6972. }
  6973. /**
  6974. * A render target is a buffer where the video card draws pixels for a scene
  6975. * that is being rendered in the background. It is used in different effects,
  6976. * such as applying postprocessing to a rendered image before displaying it
  6977. * on the screen.
  6978. *
  6979. * @augments EventDispatcher
  6980. */
  6981. class RenderTarget extends EventDispatcher {
  6982. /**
  6983. * Render target options.
  6984. *
  6985. * @typedef {Object} RenderTarget~Options
  6986. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6987. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6988. * @property {number} [minFilter=LinearFilter] - The min filter.
  6989. * @property {number} [format=RGBAFormat] - The texture format.
  6990. * @property {number} [type=UnsignedByteType] - The texture type.
  6991. * @property {?string} [internalFormat=null] - The texture's internal format.
  6992. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6993. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6994. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6995. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6996. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6997. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6998. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6999. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  7000. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  7001. * @property {number} [samples=0] - The MSAA samples count.
  7002. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  7003. * @property {number} [depth=1] - The texture depth.
  7004. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  7005. */
  7006. /**
  7007. * Constructs a new render target.
  7008. *
  7009. * @param {number} [width=1] - The width of the render target.
  7010. * @param {number} [height=1] - The height of the render target.
  7011. * @param {RenderTarget~Options} [options] - The configuration object.
  7012. */
  7013. constructor( width = 1, height = 1, options = {} ) {
  7014. super();
  7015. options = Object.assign( {
  7016. generateMipmaps: false,
  7017. internalFormat: null,
  7018. minFilter: LinearFilter,
  7019. depthBuffer: true,
  7020. stencilBuffer: false,
  7021. resolveDepthBuffer: true,
  7022. resolveStencilBuffer: true,
  7023. depthTexture: null,
  7024. samples: 0,
  7025. count: 1,
  7026. depth: 1,
  7027. multiview: false
  7028. }, options );
  7029. /**
  7030. * This flag can be used for type testing.
  7031. *
  7032. * @type {boolean}
  7033. * @readonly
  7034. * @default true
  7035. */
  7036. this.isRenderTarget = true;
  7037. /**
  7038. * The width of the render target.
  7039. *
  7040. * @type {number}
  7041. * @default 1
  7042. */
  7043. this.width = width;
  7044. /**
  7045. * The height of the render target.
  7046. *
  7047. * @type {number}
  7048. * @default 1
  7049. */
  7050. this.height = height;
  7051. /**
  7052. * The depth of the render target.
  7053. *
  7054. * @type {number}
  7055. * @default 1
  7056. */
  7057. this.depth = options.depth;
  7058. /**
  7059. * A rectangular area inside the render target's viewport. Fragments that are
  7060. * outside the area will be discarded.
  7061. *
  7062. * @type {Vector4}
  7063. * @default (0,0,width,height)
  7064. */
  7065. this.scissor = new Vector4( 0, 0, width, height );
  7066. /**
  7067. * Indicates whether the scissor test should be enabled when rendering into
  7068. * this render target or not.
  7069. *
  7070. * @type {boolean}
  7071. * @default false
  7072. */
  7073. this.scissorTest = false;
  7074. /**
  7075. * A rectangular area representing the render target's viewport.
  7076. *
  7077. * @type {Vector4}
  7078. * @default (0,0,width,height)
  7079. */
  7080. this.viewport = new Vector4( 0, 0, width, height );
  7081. /**
  7082. * An array of textures. Each color attachment is represented as a separate texture.
  7083. * Has at least a single entry for the default color attachment.
  7084. *
  7085. * @type {Array<Texture>}
  7086. */
  7087. this.textures = [];
  7088. const image = { width: width, height: height, depth: options.depth };
  7089. const texture = new Texture( image );
  7090. const count = options.count;
  7091. for ( let i = 0; i < count; i ++ ) {
  7092. this.textures[ i ] = texture.clone();
  7093. this.textures[ i ].isRenderTargetTexture = true;
  7094. this.textures[ i ].renderTarget = this;
  7095. }
  7096. this._setTextureOptions( options );
  7097. /**
  7098. * Whether to allocate a depth buffer or not.
  7099. *
  7100. * @type {boolean}
  7101. * @default true
  7102. */
  7103. this.depthBuffer = options.depthBuffer;
  7104. /**
  7105. * Whether to allocate a stencil buffer or not.
  7106. *
  7107. * @type {boolean}
  7108. * @default false
  7109. */
  7110. this.stencilBuffer = options.stencilBuffer;
  7111. /**
  7112. * Whether to resolve the depth buffer or not.
  7113. *
  7114. * @type {boolean}
  7115. * @default true
  7116. */
  7117. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7118. /**
  7119. * Whether to resolve the stencil buffer or not.
  7120. *
  7121. * @type {boolean}
  7122. * @default true
  7123. */
  7124. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7125. this._depthTexture = null;
  7126. this.depthTexture = options.depthTexture;
  7127. /**
  7128. * The number of MSAA samples.
  7129. *
  7130. * A value of `0` disables MSAA.
  7131. *
  7132. * @type {number}
  7133. * @default 0
  7134. */
  7135. this.samples = options.samples;
  7136. /**
  7137. * Whether to this target is used in multiview rendering.
  7138. *
  7139. * @type {boolean}
  7140. * @default false
  7141. */
  7142. this.multiview = options.multiview;
  7143. }
  7144. _setTextureOptions( options = {} ) {
  7145. const values = {
  7146. minFilter: LinearFilter,
  7147. generateMipmaps: false,
  7148. flipY: false,
  7149. internalFormat: null
  7150. };
  7151. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7152. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7153. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7154. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7155. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7156. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7157. if ( options.format !== undefined ) values.format = options.format;
  7158. if ( options.type !== undefined ) values.type = options.type;
  7159. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7160. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7161. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7162. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7163. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7164. for ( let i = 0; i < this.textures.length; i ++ ) {
  7165. const texture = this.textures[ i ];
  7166. texture.setValues( values );
  7167. }
  7168. }
  7169. /**
  7170. * The texture representing the default color attachment.
  7171. *
  7172. * @type {Texture}
  7173. */
  7174. get texture() {
  7175. return this.textures[ 0 ];
  7176. }
  7177. set texture( value ) {
  7178. this.textures[ 0 ] = value;
  7179. }
  7180. set depthTexture( current ) {
  7181. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7182. if ( current !== null ) current.renderTarget = this;
  7183. this._depthTexture = current;
  7184. }
  7185. /**
  7186. * Instead of saving the depth in a renderbuffer, a texture
  7187. * can be used instead which is useful for further processing
  7188. * e.g. in context of post-processing.
  7189. *
  7190. * @type {?DepthTexture}
  7191. * @default null
  7192. */
  7193. get depthTexture() {
  7194. return this._depthTexture;
  7195. }
  7196. /**
  7197. * Sets the size of this render target.
  7198. *
  7199. * @param {number} width - The width.
  7200. * @param {number} height - The height.
  7201. * @param {number} [depth=1] - The depth.
  7202. */
  7203. setSize( width, height, depth = 1 ) {
  7204. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7205. this.width = width;
  7206. this.height = height;
  7207. this.depth = depth;
  7208. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7209. this.textures[ i ].image.width = width;
  7210. this.textures[ i ].image.height = height;
  7211. this.textures[ i ].image.depth = depth;
  7212. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7213. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7214. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7215. // both are evaluated on each call?
  7216. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7217. }
  7218. }
  7219. this.dispose();
  7220. }
  7221. this.viewport.set( 0, 0, width, height );
  7222. this.scissor.set( 0, 0, width, height );
  7223. }
  7224. /**
  7225. * Returns a new render target with copied values from this instance.
  7226. *
  7227. * @return {RenderTarget} A clone of this instance.
  7228. */
  7229. clone() {
  7230. return new this.constructor().copy( this );
  7231. }
  7232. /**
  7233. * Copies the settings of the given render target. This is a structural copy so
  7234. * no resources are shared between render targets after the copy. That includes
  7235. * all MRT textures and the depth texture.
  7236. *
  7237. * @param {RenderTarget} source - The render target to copy.
  7238. * @return {RenderTarget} A reference to this instance.
  7239. */
  7240. copy( source ) {
  7241. this.width = source.width;
  7242. this.height = source.height;
  7243. this.depth = source.depth;
  7244. this.scissor.copy( source.scissor );
  7245. this.scissorTest = source.scissorTest;
  7246. this.viewport.copy( source.viewport );
  7247. this.textures.length = 0;
  7248. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7249. this.textures[ i ] = source.textures[ i ].clone();
  7250. this.textures[ i ].isRenderTargetTexture = true;
  7251. this.textures[ i ].renderTarget = this;
  7252. // ensure image object is not shared, see #20328
  7253. const image = Object.assign( {}, source.textures[ i ].image );
  7254. this.textures[ i ].source = new Source( image );
  7255. }
  7256. this.depthBuffer = source.depthBuffer;
  7257. this.stencilBuffer = source.stencilBuffer;
  7258. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7259. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7260. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7261. this.samples = source.samples;
  7262. return this;
  7263. }
  7264. /**
  7265. * Frees the GPU-related resources allocated by this instance. Call this
  7266. * method whenever this instance is no longer used in your app.
  7267. *
  7268. * @fires RenderTarget#dispose
  7269. */
  7270. dispose() {
  7271. this.dispatchEvent( { type: 'dispose' } );
  7272. }
  7273. }
  7274. /**
  7275. * A render target used in context of {@link WebGLRenderer}.
  7276. *
  7277. * @augments RenderTarget
  7278. */
  7279. class WebGLRenderTarget extends RenderTarget {
  7280. /**
  7281. * Constructs a new 3D render target.
  7282. *
  7283. * @param {number} [width=1] - The width of the render target.
  7284. * @param {number} [height=1] - The height of the render target.
  7285. * @param {RenderTarget~Options} [options] - The configuration object.
  7286. */
  7287. constructor( width = 1, height = 1, options = {} ) {
  7288. super( width, height, options );
  7289. /**
  7290. * This flag can be used for type testing.
  7291. *
  7292. * @type {boolean}
  7293. * @readonly
  7294. * @default true
  7295. */
  7296. this.isWebGLRenderTarget = true;
  7297. }
  7298. }
  7299. /**
  7300. * Creates an array of textures directly from raw buffer data.
  7301. *
  7302. * @augments Texture
  7303. */
  7304. class DataArrayTexture extends Texture {
  7305. /**
  7306. * Constructs a new data array texture.
  7307. *
  7308. * @param {?TypedArray} [data=null] - The buffer data.
  7309. * @param {number} [width=1] - The width of the texture.
  7310. * @param {number} [height=1] - The height of the texture.
  7311. * @param {number} [depth=1] - The depth of the texture.
  7312. */
  7313. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7314. super( null );
  7315. /**
  7316. * This flag can be used for type testing.
  7317. *
  7318. * @type {boolean}
  7319. * @readonly
  7320. * @default true
  7321. */
  7322. this.isDataArrayTexture = true;
  7323. /**
  7324. * The image definition of a data texture.
  7325. *
  7326. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7327. */
  7328. this.image = { data, width, height, depth };
  7329. /**
  7330. * How the texture is sampled when a texel covers more than one pixel.
  7331. *
  7332. * Overwritten and set to `NearestFilter` by default.
  7333. *
  7334. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7335. * @default NearestFilter
  7336. */
  7337. this.magFilter = NearestFilter;
  7338. /**
  7339. * How the texture is sampled when a texel covers less than one pixel.
  7340. *
  7341. * Overwritten and set to `NearestFilter` by default.
  7342. *
  7343. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7344. * @default NearestFilter
  7345. */
  7346. this.minFilter = NearestFilter;
  7347. /**
  7348. * This defines how the texture is wrapped in the depth and corresponds to
  7349. * *W* in UVW mapping.
  7350. *
  7351. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7352. * @default ClampToEdgeWrapping
  7353. */
  7354. this.wrapR = ClampToEdgeWrapping;
  7355. /**
  7356. * Whether to generate mipmaps (if possible) for a texture.
  7357. *
  7358. * Overwritten and set to `false` by default.
  7359. *
  7360. * @type {boolean}
  7361. * @default false
  7362. */
  7363. this.generateMipmaps = false;
  7364. /**
  7365. * If set to `true`, the texture is flipped along the vertical axis when
  7366. * uploaded to the GPU.
  7367. *
  7368. * Overwritten and set to `false` by default.
  7369. *
  7370. * @type {boolean}
  7371. * @default false
  7372. */
  7373. this.flipY = false;
  7374. /**
  7375. * Specifies the alignment requirements for the start of each pixel row in memory.
  7376. *
  7377. * Overwritten and set to `1` by default.
  7378. *
  7379. * @type {boolean}
  7380. * @default 1
  7381. */
  7382. this.unpackAlignment = 1;
  7383. /**
  7384. * A set of all layers which need to be updated in the texture.
  7385. *
  7386. * @type {Set<number>}
  7387. */
  7388. this.layerUpdates = new Set();
  7389. }
  7390. /**
  7391. * Describes that a specific layer of the texture needs to be updated.
  7392. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7393. * entire data texture array is sent to the GPU. Marking specific
  7394. * layers will only transmit subsets of all mipmaps associated with a
  7395. * specific depth in the array which is often much more performant.
  7396. *
  7397. * @param {number} layerIndex - The layer index that should be updated.
  7398. */
  7399. addLayerUpdate( layerIndex ) {
  7400. this.layerUpdates.add( layerIndex );
  7401. }
  7402. /**
  7403. * Resets the layer updates registry.
  7404. */
  7405. clearLayerUpdates() {
  7406. this.layerUpdates.clear();
  7407. }
  7408. }
  7409. /**
  7410. * An array render target used in context of {@link WebGLRenderer}.
  7411. *
  7412. * @augments WebGLRenderTarget
  7413. */
  7414. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7415. /**
  7416. * Constructs a new array render target.
  7417. *
  7418. * @param {number} [width=1] - The width of the render target.
  7419. * @param {number} [height=1] - The height of the render target.
  7420. * @param {number} [depth=1] - The height of the render target.
  7421. * @param {RenderTarget~Options} [options] - The configuration object.
  7422. */
  7423. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7424. super( width, height, options );
  7425. /**
  7426. * This flag can be used for type testing.
  7427. *
  7428. * @type {boolean}
  7429. * @readonly
  7430. * @default true
  7431. */
  7432. this.isWebGLArrayRenderTarget = true;
  7433. this.depth = depth;
  7434. /**
  7435. * Overwritten with a different texture type.
  7436. *
  7437. * @type {DataArrayTexture}
  7438. */
  7439. this.texture = new DataArrayTexture( null, width, height, depth );
  7440. this._setTextureOptions( options );
  7441. this.texture.isRenderTargetTexture = true;
  7442. }
  7443. }
  7444. /**
  7445. * Creates a three-dimensional texture from raw data, with parameters to
  7446. * divide it into width, height, and depth.
  7447. *
  7448. * @augments Texture
  7449. */
  7450. class Data3DTexture extends Texture {
  7451. /**
  7452. * Constructs a new data array texture.
  7453. *
  7454. * @param {?TypedArray} [data=null] - The buffer data.
  7455. * @param {number} [width=1] - The width of the texture.
  7456. * @param {number} [height=1] - The height of the texture.
  7457. * @param {number} [depth=1] - The depth of the texture.
  7458. */
  7459. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7460. // We're going to add .setXXX() methods for setting properties later.
  7461. // Users can still set in Data3DTexture directly.
  7462. //
  7463. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7464. // texture.anisotropy = 16;
  7465. //
  7466. // See #14839
  7467. super( null );
  7468. /**
  7469. * This flag can be used for type testing.
  7470. *
  7471. * @type {boolean}
  7472. * @readonly
  7473. * @default true
  7474. */
  7475. this.isData3DTexture = true;
  7476. /**
  7477. * The image definition of a data texture.
  7478. *
  7479. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7480. */
  7481. this.image = { data, width, height, depth };
  7482. /**
  7483. * How the texture is sampled when a texel covers more than one pixel.
  7484. *
  7485. * Overwritten and set to `NearestFilter` by default.
  7486. *
  7487. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7488. * @default NearestFilter
  7489. */
  7490. this.magFilter = NearestFilter;
  7491. /**
  7492. * How the texture is sampled when a texel covers less than one pixel.
  7493. *
  7494. * Overwritten and set to `NearestFilter` by default.
  7495. *
  7496. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7497. * @default NearestFilter
  7498. */
  7499. this.minFilter = NearestFilter;
  7500. /**
  7501. * This defines how the texture is wrapped in the depth and corresponds to
  7502. * *W* in UVW mapping.
  7503. *
  7504. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7505. * @default ClampToEdgeWrapping
  7506. */
  7507. this.wrapR = ClampToEdgeWrapping;
  7508. /**
  7509. * Whether to generate mipmaps (if possible) for a texture.
  7510. *
  7511. * Overwritten and set to `false` by default.
  7512. *
  7513. * @type {boolean}
  7514. * @default false
  7515. */
  7516. this.generateMipmaps = false;
  7517. /**
  7518. * If set to `true`, the texture is flipped along the vertical axis when
  7519. * uploaded to the GPU.
  7520. *
  7521. * Overwritten and set to `false` by default.
  7522. *
  7523. * @type {boolean}
  7524. * @default false
  7525. */
  7526. this.flipY = false;
  7527. /**
  7528. * Specifies the alignment requirements for the start of each pixel row in memory.
  7529. *
  7530. * Overwritten and set to `1` by default.
  7531. *
  7532. * @type {boolean}
  7533. * @default 1
  7534. */
  7535. this.unpackAlignment = 1;
  7536. }
  7537. }
  7538. /**
  7539. * A 3D render target used in context of {@link WebGLRenderer}.
  7540. *
  7541. * @augments WebGLRenderTarget
  7542. */
  7543. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7544. /**
  7545. * Constructs a new 3D render target.
  7546. *
  7547. * @param {number} [width=1] - The width of the render target.
  7548. * @param {number} [height=1] - The height of the render target.
  7549. * @param {number} [depth=1] - The height of the render target.
  7550. * @param {RenderTarget~Options} [options] - The configuration object.
  7551. */
  7552. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7553. super( width, height, options );
  7554. /**
  7555. * This flag can be used for type testing.
  7556. *
  7557. * @type {boolean}
  7558. * @readonly
  7559. * @default true
  7560. */
  7561. this.isWebGL3DRenderTarget = true;
  7562. this.depth = depth;
  7563. /**
  7564. * Overwritten with a different texture type.
  7565. *
  7566. * @type {Data3DTexture}
  7567. */
  7568. this.texture = new Data3DTexture( null, width, height, depth );
  7569. this._setTextureOptions( options );
  7570. this.texture.isRenderTargetTexture = true;
  7571. }
  7572. }
  7573. /**
  7574. * Represents a 4x4 matrix.
  7575. *
  7576. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  7577. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  7578. *
  7579. * This allows a 3D vector representing a point in 3D space to undergo
  7580. * transformations such as translation, rotation, shear, scale, reflection,
  7581. * orthogonal or perspective projection and so on, by being multiplied by the
  7582. * matrix. This is known as `applying` the matrix to the vector.
  7583. *
  7584. * A Note on Row-Major and Column-Major Ordering:
  7585. *
  7586. * The constructor and {@link Matrix3#set} method take arguments in
  7587. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  7588. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  7589. * This means that calling:
  7590. * ```js
  7591. * const m = new THREE.Matrix4();
  7592. * m.set( 11, 12, 13, 14,
  7593. * 21, 22, 23, 24,
  7594. * 31, 32, 33, 34,
  7595. * 41, 42, 43, 44 );
  7596. * ```
  7597. * will result in the elements array containing:
  7598. * ```js
  7599. * m.elements = [ 11, 21, 31, 41,
  7600. * 12, 22, 32, 42,
  7601. * 13, 23, 33, 43,
  7602. * 14, 24, 34, 44 ];
  7603. * ```
  7604. * and internally all calculations are performed using column-major ordering.
  7605. * However, as the actual ordering makes no difference mathematically and
  7606. * most people are used to thinking about matrices in row-major order, the
  7607. * three.js documentation shows matrices in row-major order. Just bear in
  7608. * mind that if you are reading the source code, you'll have to take the
  7609. * transpose of any matrices outlined here to make sense of the calculations.
  7610. */
  7611. class Matrix4 {
  7612. /**
  7613. * Constructs a new 4x4 matrix. The arguments are supposed to be
  7614. * in row-major order. If no arguments are provided, the constructor
  7615. * initializes the matrix as an identity matrix.
  7616. *
  7617. * @param {number} [n11] - 1-1 matrix element.
  7618. * @param {number} [n12] - 1-2 matrix element.
  7619. * @param {number} [n13] - 1-3 matrix element.
  7620. * @param {number} [n14] - 1-4 matrix element.
  7621. * @param {number} [n21] - 2-1 matrix element.
  7622. * @param {number} [n22] - 2-2 matrix element.
  7623. * @param {number} [n23] - 2-3 matrix element.
  7624. * @param {number} [n24] - 2-4 matrix element.
  7625. * @param {number} [n31] - 3-1 matrix element.
  7626. * @param {number} [n32] - 3-2 matrix element.
  7627. * @param {number} [n33] - 3-3 matrix element.
  7628. * @param {number} [n34] - 3-4 matrix element.
  7629. * @param {number} [n41] - 4-1 matrix element.
  7630. * @param {number} [n42] - 4-2 matrix element.
  7631. * @param {number} [n43] - 4-3 matrix element.
  7632. * @param {number} [n44] - 4-4 matrix element.
  7633. */
  7634. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7635. /**
  7636. * This flag can be used for type testing.
  7637. *
  7638. * @type {boolean}
  7639. * @readonly
  7640. * @default true
  7641. */
  7642. Matrix4.prototype.isMatrix4 = true;
  7643. /**
  7644. * A column-major list of matrix values.
  7645. *
  7646. * @type {Array<number>}
  7647. */
  7648. this.elements = [
  7649. 1, 0, 0, 0,
  7650. 0, 1, 0, 0,
  7651. 0, 0, 1, 0,
  7652. 0, 0, 0, 1
  7653. ];
  7654. if ( n11 !== undefined ) {
  7655. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  7656. }
  7657. }
  7658. /**
  7659. * Sets the elements of the matrix.The arguments are supposed to be
  7660. * in row-major order.
  7661. *
  7662. * @param {number} [n11] - 1-1 matrix element.
  7663. * @param {number} [n12] - 1-2 matrix element.
  7664. * @param {number} [n13] - 1-3 matrix element.
  7665. * @param {number} [n14] - 1-4 matrix element.
  7666. * @param {number} [n21] - 2-1 matrix element.
  7667. * @param {number} [n22] - 2-2 matrix element.
  7668. * @param {number} [n23] - 2-3 matrix element.
  7669. * @param {number} [n24] - 2-4 matrix element.
  7670. * @param {number} [n31] - 3-1 matrix element.
  7671. * @param {number} [n32] - 3-2 matrix element.
  7672. * @param {number} [n33] - 3-3 matrix element.
  7673. * @param {number} [n34] - 3-4 matrix element.
  7674. * @param {number} [n41] - 4-1 matrix element.
  7675. * @param {number} [n42] - 4-2 matrix element.
  7676. * @param {number} [n43] - 4-3 matrix element.
  7677. * @param {number} [n44] - 4-4 matrix element.
  7678. * @return {Matrix4} A reference to this matrix.
  7679. */
  7680. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7681. const te = this.elements;
  7682. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7683. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7684. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7685. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7686. return this;
  7687. }
  7688. /**
  7689. * Sets this matrix to the 4x4 identity matrix.
  7690. *
  7691. * @return {Matrix4} A reference to this matrix.
  7692. */
  7693. identity() {
  7694. this.set(
  7695. 1, 0, 0, 0,
  7696. 0, 1, 0, 0,
  7697. 0, 0, 1, 0,
  7698. 0, 0, 0, 1
  7699. );
  7700. return this;
  7701. }
  7702. /**
  7703. * Returns a matrix with copied values from this instance.
  7704. *
  7705. * @return {Matrix4} A clone of this instance.
  7706. */
  7707. clone() {
  7708. return new Matrix4().fromArray( this.elements );
  7709. }
  7710. /**
  7711. * Copies the values of the given matrix to this instance.
  7712. *
  7713. * @param {Matrix4} m - The matrix to copy.
  7714. * @return {Matrix4} A reference to this matrix.
  7715. */
  7716. copy( m ) {
  7717. const te = this.elements;
  7718. const me = m.elements;
  7719. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7720. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7721. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7722. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7723. return this;
  7724. }
  7725. /**
  7726. * Copies the translation component of the given matrix
  7727. * into this matrix's translation component.
  7728. *
  7729. * @param {Matrix4} m - The matrix to copy the translation component.
  7730. * @return {Matrix4} A reference to this matrix.
  7731. */
  7732. copyPosition( m ) {
  7733. const te = this.elements, me = m.elements;
  7734. te[ 12 ] = me[ 12 ];
  7735. te[ 13 ] = me[ 13 ];
  7736. te[ 14 ] = me[ 14 ];
  7737. return this;
  7738. }
  7739. /**
  7740. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  7741. *
  7742. * @param {Matrix3} m - The 3x3 matrix.
  7743. * @return {Matrix4} A reference to this matrix.
  7744. */
  7745. setFromMatrix3( m ) {
  7746. const me = m.elements;
  7747. this.set(
  7748. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  7749. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  7750. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  7751. 0, 0, 0, 1
  7752. );
  7753. return this;
  7754. }
  7755. /**
  7756. * Extracts the basis of this matrix into the three axis vectors provided.
  7757. *
  7758. * @param {Vector3} xAxis - The basis's x axis.
  7759. * @param {Vector3} yAxis - The basis's y axis.
  7760. * @param {Vector3} zAxis - The basis's z axis.
  7761. * @return {Matrix4} A reference to this matrix.
  7762. */
  7763. extractBasis( xAxis, yAxis, zAxis ) {
  7764. if ( this.determinant() === 0 ) {
  7765. xAxis.set( 1, 0, 0 );
  7766. yAxis.set( 0, 1, 0 );
  7767. zAxis.set( 0, 0, 1 );
  7768. return this;
  7769. }
  7770. xAxis.setFromMatrixColumn( this, 0 );
  7771. yAxis.setFromMatrixColumn( this, 1 );
  7772. zAxis.setFromMatrixColumn( this, 2 );
  7773. return this;
  7774. }
  7775. /**
  7776. * Sets the given basis vectors to this matrix.
  7777. *
  7778. * @param {Vector3} xAxis - The basis's x axis.
  7779. * @param {Vector3} yAxis - The basis's y axis.
  7780. * @param {Vector3} zAxis - The basis's z axis.
  7781. * @return {Matrix4} A reference to this matrix.
  7782. */
  7783. makeBasis( xAxis, yAxis, zAxis ) {
  7784. this.set(
  7785. xAxis.x, yAxis.x, zAxis.x, 0,
  7786. xAxis.y, yAxis.y, zAxis.y, 0,
  7787. xAxis.z, yAxis.z, zAxis.z, 0,
  7788. 0, 0, 0, 1
  7789. );
  7790. return this;
  7791. }
  7792. /**
  7793. * Extracts the rotation component of the given matrix
  7794. * into this matrix's rotation component.
  7795. *
  7796. * Note: This method does not support reflection matrices.
  7797. *
  7798. * @param {Matrix4} m - The matrix.
  7799. * @return {Matrix4} A reference to this matrix.
  7800. */
  7801. extractRotation( m ) {
  7802. if ( m.determinant() === 0 ) {
  7803. return this.identity();
  7804. }
  7805. const te = this.elements;
  7806. const me = m.elements;
  7807. const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length();
  7808. const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length();
  7809. const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length();
  7810. te[ 0 ] = me[ 0 ] * scaleX;
  7811. te[ 1 ] = me[ 1 ] * scaleX;
  7812. te[ 2 ] = me[ 2 ] * scaleX;
  7813. te[ 3 ] = 0;
  7814. te[ 4 ] = me[ 4 ] * scaleY;
  7815. te[ 5 ] = me[ 5 ] * scaleY;
  7816. te[ 6 ] = me[ 6 ] * scaleY;
  7817. te[ 7 ] = 0;
  7818. te[ 8 ] = me[ 8 ] * scaleZ;
  7819. te[ 9 ] = me[ 9 ] * scaleZ;
  7820. te[ 10 ] = me[ 10 ] * scaleZ;
  7821. te[ 11 ] = 0;
  7822. te[ 12 ] = 0;
  7823. te[ 13 ] = 0;
  7824. te[ 14 ] = 0;
  7825. te[ 15 ] = 1;
  7826. return this;
  7827. }
  7828. /**
  7829. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  7830. * the rotation specified by the given Euler angles. The rest of
  7831. * the matrix is set to the identity. Depending on the {@link Euler#order},
  7832. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  7833. * for a complete list.
  7834. *
  7835. * @param {Euler} euler - The Euler angles.
  7836. * @return {Matrix4} A reference to this matrix.
  7837. */
  7838. makeRotationFromEuler( euler ) {
  7839. const te = this.elements;
  7840. const x = euler.x, y = euler.y, z = euler.z;
  7841. const a = Math.cos( x ), b = Math.sin( x );
  7842. const c = Math.cos( y ), d = Math.sin( y );
  7843. const e = Math.cos( z ), f = Math.sin( z );
  7844. if ( euler.order === 'XYZ' ) {
  7845. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7846. te[ 0 ] = c * e;
  7847. te[ 4 ] = - c * f;
  7848. te[ 8 ] = d;
  7849. te[ 1 ] = af + be * d;
  7850. te[ 5 ] = ae - bf * d;
  7851. te[ 9 ] = - b * c;
  7852. te[ 2 ] = bf - ae * d;
  7853. te[ 6 ] = be + af * d;
  7854. te[ 10 ] = a * c;
  7855. } else if ( euler.order === 'YXZ' ) {
  7856. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7857. te[ 0 ] = ce + df * b;
  7858. te[ 4 ] = de * b - cf;
  7859. te[ 8 ] = a * d;
  7860. te[ 1 ] = a * f;
  7861. te[ 5 ] = a * e;
  7862. te[ 9 ] = - b;
  7863. te[ 2 ] = cf * b - de;
  7864. te[ 6 ] = df + ce * b;
  7865. te[ 10 ] = a * c;
  7866. } else if ( euler.order === 'ZXY' ) {
  7867. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7868. te[ 0 ] = ce - df * b;
  7869. te[ 4 ] = - a * f;
  7870. te[ 8 ] = de + cf * b;
  7871. te[ 1 ] = cf + de * b;
  7872. te[ 5 ] = a * e;
  7873. te[ 9 ] = df - ce * b;
  7874. te[ 2 ] = - a * d;
  7875. te[ 6 ] = b;
  7876. te[ 10 ] = a * c;
  7877. } else if ( euler.order === 'ZYX' ) {
  7878. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7879. te[ 0 ] = c * e;
  7880. te[ 4 ] = be * d - af;
  7881. te[ 8 ] = ae * d + bf;
  7882. te[ 1 ] = c * f;
  7883. te[ 5 ] = bf * d + ae;
  7884. te[ 9 ] = af * d - be;
  7885. te[ 2 ] = - d;
  7886. te[ 6 ] = b * c;
  7887. te[ 10 ] = a * c;
  7888. } else if ( euler.order === 'YZX' ) {
  7889. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7890. te[ 0 ] = c * e;
  7891. te[ 4 ] = bd - ac * f;
  7892. te[ 8 ] = bc * f + ad;
  7893. te[ 1 ] = f;
  7894. te[ 5 ] = a * e;
  7895. te[ 9 ] = - b * e;
  7896. te[ 2 ] = - d * e;
  7897. te[ 6 ] = ad * f + bc;
  7898. te[ 10 ] = ac - bd * f;
  7899. } else if ( euler.order === 'XZY' ) {
  7900. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7901. te[ 0 ] = c * e;
  7902. te[ 4 ] = - f;
  7903. te[ 8 ] = d * e;
  7904. te[ 1 ] = ac * f + bd;
  7905. te[ 5 ] = a * e;
  7906. te[ 9 ] = ad * f - bc;
  7907. te[ 2 ] = bc * f - ad;
  7908. te[ 6 ] = b * e;
  7909. te[ 10 ] = bd * f + ac;
  7910. }
  7911. // bottom row
  7912. te[ 3 ] = 0;
  7913. te[ 7 ] = 0;
  7914. te[ 11 ] = 0;
  7915. // last column
  7916. te[ 12 ] = 0;
  7917. te[ 13 ] = 0;
  7918. te[ 14 ] = 0;
  7919. te[ 15 ] = 1;
  7920. return this;
  7921. }
  7922. /**
  7923. * Sets the rotation component of this matrix to the rotation specified by
  7924. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  7925. * The rest of the matrix is set to the identity.
  7926. *
  7927. * @param {Quaternion} q - The Quaternion.
  7928. * @return {Matrix4} A reference to this matrix.
  7929. */
  7930. makeRotationFromQuaternion( q ) {
  7931. return this.compose( _zero, q, _one );
  7932. }
  7933. /**
  7934. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  7935. * `target`, and oriented by the up-direction.
  7936. *
  7937. * @param {Vector3} eye - The eye vector.
  7938. * @param {Vector3} target - The target vector.
  7939. * @param {Vector3} up - The up vector.
  7940. * @return {Matrix4} A reference to this matrix.
  7941. */
  7942. lookAt( eye, target, up ) {
  7943. const te = this.elements;
  7944. _z.subVectors( eye, target );
  7945. if ( _z.lengthSq() === 0 ) {
  7946. // eye and target are in the same position
  7947. _z.z = 1;
  7948. }
  7949. _z.normalize();
  7950. _x.crossVectors( up, _z );
  7951. if ( _x.lengthSq() === 0 ) {
  7952. // up and z are parallel
  7953. if ( Math.abs( up.z ) === 1 ) {
  7954. _z.x += 0.0001;
  7955. } else {
  7956. _z.z += 0.0001;
  7957. }
  7958. _z.normalize();
  7959. _x.crossVectors( up, _z );
  7960. }
  7961. _x.normalize();
  7962. _y.crossVectors( _z, _x );
  7963. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  7964. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  7965. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  7966. return this;
  7967. }
  7968. /**
  7969. * Post-multiplies this matrix by the given 4x4 matrix.
  7970. *
  7971. * @param {Matrix4} m - The matrix to multiply with.
  7972. * @return {Matrix4} A reference to this matrix.
  7973. */
  7974. multiply( m ) {
  7975. return this.multiplyMatrices( this, m );
  7976. }
  7977. /**
  7978. * Pre-multiplies this matrix by the given 4x4 matrix.
  7979. *
  7980. * @param {Matrix4} m - The matrix to multiply with.
  7981. * @return {Matrix4} A reference to this matrix.
  7982. */
  7983. premultiply( m ) {
  7984. return this.multiplyMatrices( m, this );
  7985. }
  7986. /**
  7987. * Multiples the given 4x4 matrices and stores the result
  7988. * in this matrix.
  7989. *
  7990. * @param {Matrix4} a - The first matrix.
  7991. * @param {Matrix4} b - The second matrix.
  7992. * @return {Matrix4} A reference to this matrix.
  7993. */
  7994. multiplyMatrices( a, b ) {
  7995. const ae = a.elements;
  7996. const be = b.elements;
  7997. const te = this.elements;
  7998. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  7999. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8000. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8001. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8002. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8003. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8004. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8005. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8006. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8007. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8008. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8009. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8010. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8011. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8012. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8013. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8014. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8015. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8016. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8017. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8018. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8019. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8020. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8021. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8022. return this;
  8023. }
  8024. /**
  8025. * Multiplies every component of the matrix by the given scalar.
  8026. *
  8027. * @param {number} s - The scalar.
  8028. * @return {Matrix4} A reference to this matrix.
  8029. */
  8030. multiplyScalar( s ) {
  8031. const te = this.elements;
  8032. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8033. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8034. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8035. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8036. return this;
  8037. }
  8038. /**
  8039. * Computes and returns the determinant of this matrix.
  8040. *
  8041. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  8042. *
  8043. * @return {number} The determinant.
  8044. */
  8045. determinant() {
  8046. const te = this.elements;
  8047. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8048. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8049. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8050. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8051. const t11 = n23 * n34 - n24 * n33;
  8052. const t12 = n22 * n34 - n24 * n32;
  8053. const t13 = n22 * n33 - n23 * n32;
  8054. const t21 = n21 * n34 - n24 * n31;
  8055. const t22 = n21 * n33 - n23 * n31;
  8056. const t23 = n21 * n32 - n22 * n31;
  8057. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  8058. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  8059. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  8060. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  8061. }
  8062. /**
  8063. * Transposes this matrix in place.
  8064. *
  8065. * @return {Matrix4} A reference to this matrix.
  8066. */
  8067. transpose() {
  8068. const te = this.elements;
  8069. let tmp;
  8070. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8071. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8072. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8073. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8074. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8075. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8076. return this;
  8077. }
  8078. /**
  8079. * Sets the position component for this matrix from the given vector,
  8080. * without affecting the rest of the matrix.
  8081. *
  8082. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8083. * @param {number} y - The y component of the vector.
  8084. * @param {number} z - The z component of the vector.
  8085. * @return {Matrix4} A reference to this matrix.
  8086. */
  8087. setPosition( x, y, z ) {
  8088. const te = this.elements;
  8089. if ( x.isVector3 ) {
  8090. te[ 12 ] = x.x;
  8091. te[ 13 ] = x.y;
  8092. te[ 14 ] = x.z;
  8093. } else {
  8094. te[ 12 ] = x;
  8095. te[ 13 ] = y;
  8096. te[ 14 ] = z;
  8097. }
  8098. return this;
  8099. }
  8100. /**
  8101. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  8102. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8103. * a zero matrix instead.
  8104. *
  8105. * @return {Matrix4} A reference to this matrix.
  8106. */
  8107. invert() {
  8108. // based on https://github.com/toji/gl-matrix
  8109. const te = this.elements,
  8110. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8111. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8112. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8113. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8114. t1 = n11 * n22 - n21 * n12,
  8115. t2 = n11 * n32 - n31 * n12,
  8116. t3 = n11 * n42 - n41 * n12,
  8117. t4 = n21 * n32 - n31 * n22,
  8118. t5 = n21 * n42 - n41 * n22,
  8119. t6 = n31 * n42 - n41 * n32,
  8120. t7 = n13 * n24 - n23 * n14,
  8121. t8 = n13 * n34 - n33 * n14,
  8122. t9 = n13 * n44 - n43 * n14,
  8123. t10 = n23 * n34 - n33 * n24,
  8124. t11 = n23 * n44 - n43 * n24,
  8125. t12 = n33 * n44 - n43 * n34;
  8126. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  8127. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8128. const detInv = 1 / det;
  8129. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  8130. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  8131. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  8132. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  8133. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  8134. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  8135. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  8136. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  8137. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  8138. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  8139. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  8140. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  8141. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  8142. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  8143. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  8144. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  8145. return this;
  8146. }
  8147. /**
  8148. * Multiplies the columns of this matrix by the given vector.
  8149. *
  8150. * @param {Vector3} v - The scale vector.
  8151. * @return {Matrix4} A reference to this matrix.
  8152. */
  8153. scale( v ) {
  8154. const te = this.elements;
  8155. const x = v.x, y = v.y, z = v.z;
  8156. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8157. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8158. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8159. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8160. return this;
  8161. }
  8162. /**
  8163. * Gets the maximum scale value of the three axes.
  8164. *
  8165. * @return {number} The maximum scale.
  8166. */
  8167. getMaxScaleOnAxis() {
  8168. const te = this.elements;
  8169. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8170. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8171. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8172. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8173. }
  8174. /**
  8175. * Sets this matrix as a translation transform from the given vector.
  8176. *
  8177. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  8178. * @param {number} y - The amount to translate in the Y axis.
  8179. * @param {number} z - The amount to translate in the z axis.
  8180. * @return {Matrix4} A reference to this matrix.
  8181. */
  8182. makeTranslation( x, y, z ) {
  8183. if ( x.isVector3 ) {
  8184. this.set(
  8185. 1, 0, 0, x.x,
  8186. 0, 1, 0, x.y,
  8187. 0, 0, 1, x.z,
  8188. 0, 0, 0, 1
  8189. );
  8190. } else {
  8191. this.set(
  8192. 1, 0, 0, x,
  8193. 0, 1, 0, y,
  8194. 0, 0, 1, z,
  8195. 0, 0, 0, 1
  8196. );
  8197. }
  8198. return this;
  8199. }
  8200. /**
  8201. * Sets this matrix as a rotational transformation around the X axis by
  8202. * the given angle.
  8203. *
  8204. * @param {number} theta - The rotation in radians.
  8205. * @return {Matrix4} A reference to this matrix.
  8206. */
  8207. makeRotationX( theta ) {
  8208. const c = Math.cos( theta ), s = Math.sin( theta );
  8209. this.set(
  8210. 1, 0, 0, 0,
  8211. 0, c, - s, 0,
  8212. 0, s, c, 0,
  8213. 0, 0, 0, 1
  8214. );
  8215. return this;
  8216. }
  8217. /**
  8218. * Sets this matrix as a rotational transformation around the Y axis by
  8219. * the given angle.
  8220. *
  8221. * @param {number} theta - The rotation in radians.
  8222. * @return {Matrix4} A reference to this matrix.
  8223. */
  8224. makeRotationY( theta ) {
  8225. const c = Math.cos( theta ), s = Math.sin( theta );
  8226. this.set(
  8227. c, 0, s, 0,
  8228. 0, 1, 0, 0,
  8229. - s, 0, c, 0,
  8230. 0, 0, 0, 1
  8231. );
  8232. return this;
  8233. }
  8234. /**
  8235. * Sets this matrix as a rotational transformation around the Z axis by
  8236. * the given angle.
  8237. *
  8238. * @param {number} theta - The rotation in radians.
  8239. * @return {Matrix4} A reference to this matrix.
  8240. */
  8241. makeRotationZ( theta ) {
  8242. const c = Math.cos( theta ), s = Math.sin( theta );
  8243. this.set(
  8244. c, - s, 0, 0,
  8245. s, c, 0, 0,
  8246. 0, 0, 1, 0,
  8247. 0, 0, 0, 1
  8248. );
  8249. return this;
  8250. }
  8251. /**
  8252. * Sets this matrix as a rotational transformation around the given axis by
  8253. * the given angle.
  8254. *
  8255. * This is a somewhat controversial but mathematically sound alternative to
  8256. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  8257. *
  8258. * @param {Vector3} axis - The normalized rotation axis.
  8259. * @param {number} angle - The rotation in radians.
  8260. * @return {Matrix4} A reference to this matrix.
  8261. */
  8262. makeRotationAxis( axis, angle ) {
  8263. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8264. const c = Math.cos( angle );
  8265. const s = Math.sin( angle );
  8266. const t = 1 - c;
  8267. const x = axis.x, y = axis.y, z = axis.z;
  8268. const tx = t * x, ty = t * y;
  8269. this.set(
  8270. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8271. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8272. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8273. 0, 0, 0, 1
  8274. );
  8275. return this;
  8276. }
  8277. /**
  8278. * Sets this matrix as a scale transformation.
  8279. *
  8280. * @param {number} x - The amount to scale in the X axis.
  8281. * @param {number} y - The amount to scale in the Y axis.
  8282. * @param {number} z - The amount to scale in the Z axis.
  8283. * @return {Matrix4} A reference to this matrix.
  8284. */
  8285. makeScale( x, y, z ) {
  8286. this.set(
  8287. x, 0, 0, 0,
  8288. 0, y, 0, 0,
  8289. 0, 0, z, 0,
  8290. 0, 0, 0, 1
  8291. );
  8292. return this;
  8293. }
  8294. /**
  8295. * Sets this matrix as a shear transformation.
  8296. *
  8297. * @param {number} xy - The amount to shear X by Y.
  8298. * @param {number} xz - The amount to shear X by Z.
  8299. * @param {number} yx - The amount to shear Y by X.
  8300. * @param {number} yz - The amount to shear Y by Z.
  8301. * @param {number} zx - The amount to shear Z by X.
  8302. * @param {number} zy - The amount to shear Z by Y.
  8303. * @return {Matrix4} A reference to this matrix.
  8304. */
  8305. makeShear( xy, xz, yx, yz, zx, zy ) {
  8306. this.set(
  8307. 1, yx, zx, 0,
  8308. xy, 1, zy, 0,
  8309. xz, yz, 1, 0,
  8310. 0, 0, 0, 1
  8311. );
  8312. return this;
  8313. }
  8314. /**
  8315. * Sets this matrix to the transformation composed of the given position,
  8316. * rotation (Quaternion) and scale.
  8317. *
  8318. * @param {Vector3} position - The position vector.
  8319. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8320. * @param {Vector3} scale - The scale vector.
  8321. * @return {Matrix4} A reference to this matrix.
  8322. */
  8323. compose( position, quaternion, scale ) {
  8324. const te = this.elements;
  8325. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8326. const x2 = x + x, y2 = y + y, z2 = z + z;
  8327. const xx = x * x2, xy = x * y2, xz = x * z2;
  8328. const yy = y * y2, yz = y * z2, zz = z * z2;
  8329. const wx = w * x2, wy = w * y2, wz = w * z2;
  8330. const sx = scale.x, sy = scale.y, sz = scale.z;
  8331. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8332. te[ 1 ] = ( xy + wz ) * sx;
  8333. te[ 2 ] = ( xz - wy ) * sx;
  8334. te[ 3 ] = 0;
  8335. te[ 4 ] = ( xy - wz ) * sy;
  8336. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8337. te[ 6 ] = ( yz + wx ) * sy;
  8338. te[ 7 ] = 0;
  8339. te[ 8 ] = ( xz + wy ) * sz;
  8340. te[ 9 ] = ( yz - wx ) * sz;
  8341. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8342. te[ 11 ] = 0;
  8343. te[ 12 ] = position.x;
  8344. te[ 13 ] = position.y;
  8345. te[ 14 ] = position.z;
  8346. te[ 15 ] = 1;
  8347. return this;
  8348. }
  8349. /**
  8350. * Decomposes this matrix into its position, rotation and scale components
  8351. * and provides the result in the given objects.
  8352. *
  8353. * Note: Not all matrices are decomposable in this way. For example, if an
  8354. * object has a non-uniformly scaled parent, then the object's world matrix
  8355. * may not be decomposable, and this method may not be appropriate.
  8356. *
  8357. * @param {Vector3} position - The position vector.
  8358. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8359. * @param {Vector3} scale - The scale vector.
  8360. * @return {Matrix4} A reference to this matrix.
  8361. */
  8362. decompose( position, quaternion, scale ) {
  8363. const te = this.elements;
  8364. position.x = te[ 12 ];
  8365. position.y = te[ 13 ];
  8366. position.z = te[ 14 ];
  8367. const det = this.determinant();
  8368. if ( det === 0 ) {
  8369. scale.set( 1, 1, 1 );
  8370. quaternion.identity();
  8371. return this;
  8372. }
  8373. let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8374. const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8375. const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8376. // if determinant is negative, we need to invert one scale
  8377. if ( det < 0 ) sx = - sx;
  8378. // scale the rotation part
  8379. _m1$4.copy( this );
  8380. const invSX = 1 / sx;
  8381. const invSY = 1 / sy;
  8382. const invSZ = 1 / sz;
  8383. _m1$4.elements[ 0 ] *= invSX;
  8384. _m1$4.elements[ 1 ] *= invSX;
  8385. _m1$4.elements[ 2 ] *= invSX;
  8386. _m1$4.elements[ 4 ] *= invSY;
  8387. _m1$4.elements[ 5 ] *= invSY;
  8388. _m1$4.elements[ 6 ] *= invSY;
  8389. _m1$4.elements[ 8 ] *= invSZ;
  8390. _m1$4.elements[ 9 ] *= invSZ;
  8391. _m1$4.elements[ 10 ] *= invSZ;
  8392. quaternion.setFromRotationMatrix( _m1$4 );
  8393. scale.x = sx;
  8394. scale.y = sy;
  8395. scale.z = sz;
  8396. return this;
  8397. }
  8398. /**
  8399. * Creates a perspective projection matrix. This is used internally by
  8400. * {@link PerspectiveCamera#updateProjectionMatrix}.
  8401. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8402. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8403. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8404. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8405. * @param {number} near - The distance from the camera to the near plane.
  8406. * @param {number} far - The distance from the camera to the far plane.
  8407. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8408. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8409. * @return {Matrix4} A reference to this matrix.
  8410. */
  8411. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8412. const te = this.elements;
  8413. const x = 2 * near / ( right - left );
  8414. const y = 2 * near / ( top - bottom );
  8415. const a = ( right + left ) / ( right - left );
  8416. const b = ( top + bottom ) / ( top - bottom );
  8417. let c, d;
  8418. if ( reversedDepth ) {
  8419. c = near / ( far - near );
  8420. d = ( far * near ) / ( far - near );
  8421. } else {
  8422. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8423. c = - ( far + near ) / ( far - near );
  8424. d = ( -2 * far * near ) / ( far - near );
  8425. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8426. c = - far / ( far - near );
  8427. d = ( - far * near ) / ( far - near );
  8428. } else {
  8429. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  8430. }
  8431. }
  8432. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8433. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8434. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8435. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  8436. return this;
  8437. }
  8438. /**
  8439. * Creates a orthographic projection matrix. This is used internally by
  8440. * {@link OrthographicCamera#updateProjectionMatrix}.
  8441. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8442. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8443. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8444. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8445. * @param {number} near - The distance from the camera to the near plane.
  8446. * @param {number} far - The distance from the camera to the far plane.
  8447. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8448. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8449. * @return {Matrix4} A reference to this matrix.
  8450. */
  8451. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8452. const te = this.elements;
  8453. const x = 2 / ( right - left );
  8454. const y = 2 / ( top - bottom );
  8455. const a = - ( right + left ) / ( right - left );
  8456. const b = - ( top + bottom ) / ( top - bottom );
  8457. let c, d;
  8458. if ( reversedDepth ) {
  8459. c = 1 / ( far - near );
  8460. d = far / ( far - near );
  8461. } else {
  8462. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8463. c = -2 / ( far - near );
  8464. d = - ( far + near ) / ( far - near );
  8465. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8466. c = -1 / ( far - near );
  8467. d = - near / ( far - near );
  8468. } else {
  8469. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  8470. }
  8471. }
  8472. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  8473. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  8474. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8475. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8476. return this;
  8477. }
  8478. /**
  8479. * Returns `true` if this matrix is equal with the given one.
  8480. *
  8481. * @param {Matrix4} matrix - The matrix to test for equality.
  8482. * @return {boolean} Whether this matrix is equal with the given one.
  8483. */
  8484. equals( matrix ) {
  8485. const te = this.elements;
  8486. const me = matrix.elements;
  8487. for ( let i = 0; i < 16; i ++ ) {
  8488. if ( te[ i ] !== me[ i ] ) return false;
  8489. }
  8490. return true;
  8491. }
  8492. /**
  8493. * Sets the elements of the matrix from the given array.
  8494. *
  8495. * @param {Array<number>} array - The matrix elements in column-major order.
  8496. * @param {number} [offset=0] - Index of the first element in the array.
  8497. * @return {Matrix4} A reference to this matrix.
  8498. */
  8499. fromArray( array, offset = 0 ) {
  8500. for ( let i = 0; i < 16; i ++ ) {
  8501. this.elements[ i ] = array[ i + offset ];
  8502. }
  8503. return this;
  8504. }
  8505. /**
  8506. * Writes the elements of this matrix to the given array. If no array is provided,
  8507. * the method returns a new instance.
  8508. *
  8509. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  8510. * @param {number} [offset=0] - Index of the first element in the array.
  8511. * @return {Array<number>} The matrix elements in column-major order.
  8512. */
  8513. toArray( array = [], offset = 0 ) {
  8514. const te = this.elements;
  8515. array[ offset ] = te[ 0 ];
  8516. array[ offset + 1 ] = te[ 1 ];
  8517. array[ offset + 2 ] = te[ 2 ];
  8518. array[ offset + 3 ] = te[ 3 ];
  8519. array[ offset + 4 ] = te[ 4 ];
  8520. array[ offset + 5 ] = te[ 5 ];
  8521. array[ offset + 6 ] = te[ 6 ];
  8522. array[ offset + 7 ] = te[ 7 ];
  8523. array[ offset + 8 ] = te[ 8 ];
  8524. array[ offset + 9 ] = te[ 9 ];
  8525. array[ offset + 10 ] = te[ 10 ];
  8526. array[ offset + 11 ] = te[ 11 ];
  8527. array[ offset + 12 ] = te[ 12 ];
  8528. array[ offset + 13 ] = te[ 13 ];
  8529. array[ offset + 14 ] = te[ 14 ];
  8530. array[ offset + 15 ] = te[ 15 ];
  8531. return array;
  8532. }
  8533. }
  8534. const _v1$7 = /*@__PURE__*/ new Vector3();
  8535. const _m1$4 = /*@__PURE__*/ new Matrix4();
  8536. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  8537. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  8538. const _x = /*@__PURE__*/ new Vector3();
  8539. const _y = /*@__PURE__*/ new Vector3();
  8540. const _z = /*@__PURE__*/ new Vector3();
  8541. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  8542. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  8543. /**
  8544. * A class representing Euler angles.
  8545. *
  8546. * Euler angles describe a rotational transformation by rotating an object on
  8547. * its various axes in specified amounts per axis, and a specified axis
  8548. * order.
  8549. *
  8550. * Iterating through an instance will yield its components (x, y, z,
  8551. * order) in the corresponding order.
  8552. *
  8553. * ```js
  8554. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  8555. * const b = new THREE.Vector3( 1, 0, 1 );
  8556. * b.applyEuler(a);
  8557. * ```
  8558. */
  8559. class Euler {
  8560. /**
  8561. * Constructs a new euler instance.
  8562. *
  8563. * @param {number} [x=0] - The angle of the x axis in radians.
  8564. * @param {number} [y=0] - The angle of the y axis in radians.
  8565. * @param {number} [z=0] - The angle of the z axis in radians.
  8566. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  8567. */
  8568. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  8569. /**
  8570. * This flag can be used for type testing.
  8571. *
  8572. * @type {boolean}
  8573. * @readonly
  8574. * @default true
  8575. */
  8576. this.isEuler = true;
  8577. this._x = x;
  8578. this._y = y;
  8579. this._z = z;
  8580. this._order = order;
  8581. }
  8582. /**
  8583. * The angle of the x axis in radians.
  8584. *
  8585. * @type {number}
  8586. * @default 0
  8587. */
  8588. get x() {
  8589. return this._x;
  8590. }
  8591. set x( value ) {
  8592. this._x = value;
  8593. this._onChangeCallback();
  8594. }
  8595. /**
  8596. * The angle of the y axis in radians.
  8597. *
  8598. * @type {number}
  8599. * @default 0
  8600. */
  8601. get y() {
  8602. return this._y;
  8603. }
  8604. set y( value ) {
  8605. this._y = value;
  8606. this._onChangeCallback();
  8607. }
  8608. /**
  8609. * The angle of the z axis in radians.
  8610. *
  8611. * @type {number}
  8612. * @default 0
  8613. */
  8614. get z() {
  8615. return this._z;
  8616. }
  8617. set z( value ) {
  8618. this._z = value;
  8619. this._onChangeCallback();
  8620. }
  8621. /**
  8622. * A string representing the order that the rotations are applied.
  8623. *
  8624. * @type {string}
  8625. * @default 'XYZ'
  8626. */
  8627. get order() {
  8628. return this._order;
  8629. }
  8630. set order( value ) {
  8631. this._order = value;
  8632. this._onChangeCallback();
  8633. }
  8634. /**
  8635. * Sets the Euler components.
  8636. *
  8637. * @param {number} x - The angle of the x axis in radians.
  8638. * @param {number} y - The angle of the y axis in radians.
  8639. * @param {number} z - The angle of the z axis in radians.
  8640. * @param {string} [order] - A string representing the order that the rotations are applied.
  8641. * @return {Euler} A reference to this Euler instance.
  8642. */
  8643. set( x, y, z, order = this._order ) {
  8644. this._x = x;
  8645. this._y = y;
  8646. this._z = z;
  8647. this._order = order;
  8648. this._onChangeCallback();
  8649. return this;
  8650. }
  8651. /**
  8652. * Returns a new Euler instance with copied values from this instance.
  8653. *
  8654. * @return {Euler} A clone of this instance.
  8655. */
  8656. clone() {
  8657. return new this.constructor( this._x, this._y, this._z, this._order );
  8658. }
  8659. /**
  8660. * Copies the values of the given Euler instance to this instance.
  8661. *
  8662. * @param {Euler} euler - The Euler instance to copy.
  8663. * @return {Euler} A reference to this Euler instance.
  8664. */
  8665. copy( euler ) {
  8666. this._x = euler._x;
  8667. this._y = euler._y;
  8668. this._z = euler._z;
  8669. this._order = euler._order;
  8670. this._onChangeCallback();
  8671. return this;
  8672. }
  8673. /**
  8674. * Sets the angles of this Euler instance from a pure rotation matrix.
  8675. *
  8676. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  8677. * @param {string} [order] - A string representing the order that the rotations are applied.
  8678. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8679. * @return {Euler} A reference to this Euler instance.
  8680. */
  8681. setFromRotationMatrix( m, order = this._order, update = true ) {
  8682. const te = m.elements;
  8683. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8684. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8685. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8686. switch ( order ) {
  8687. case 'XYZ':
  8688. this._y = Math.asin( clamp( m13, -1, 1 ) );
  8689. if ( Math.abs( m13 ) < 0.9999999 ) {
  8690. this._x = Math.atan2( - m23, m33 );
  8691. this._z = Math.atan2( - m12, m11 );
  8692. } else {
  8693. this._x = Math.atan2( m32, m22 );
  8694. this._z = 0;
  8695. }
  8696. break;
  8697. case 'YXZ':
  8698. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  8699. if ( Math.abs( m23 ) < 0.9999999 ) {
  8700. this._y = Math.atan2( m13, m33 );
  8701. this._z = Math.atan2( m21, m22 );
  8702. } else {
  8703. this._y = Math.atan2( - m31, m11 );
  8704. this._z = 0;
  8705. }
  8706. break;
  8707. case 'ZXY':
  8708. this._x = Math.asin( clamp( m32, -1, 1 ) );
  8709. if ( Math.abs( m32 ) < 0.9999999 ) {
  8710. this._y = Math.atan2( - m31, m33 );
  8711. this._z = Math.atan2( - m12, m22 );
  8712. } else {
  8713. this._y = 0;
  8714. this._z = Math.atan2( m21, m11 );
  8715. }
  8716. break;
  8717. case 'ZYX':
  8718. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  8719. if ( Math.abs( m31 ) < 0.9999999 ) {
  8720. this._x = Math.atan2( m32, m33 );
  8721. this._z = Math.atan2( m21, m11 );
  8722. } else {
  8723. this._x = 0;
  8724. this._z = Math.atan2( - m12, m22 );
  8725. }
  8726. break;
  8727. case 'YZX':
  8728. this._z = Math.asin( clamp( m21, -1, 1 ) );
  8729. if ( Math.abs( m21 ) < 0.9999999 ) {
  8730. this._x = Math.atan2( - m23, m22 );
  8731. this._y = Math.atan2( - m31, m11 );
  8732. } else {
  8733. this._x = 0;
  8734. this._y = Math.atan2( m13, m33 );
  8735. }
  8736. break;
  8737. case 'XZY':
  8738. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  8739. if ( Math.abs( m12 ) < 0.9999999 ) {
  8740. this._x = Math.atan2( m32, m22 );
  8741. this._y = Math.atan2( m13, m11 );
  8742. } else {
  8743. this._x = Math.atan2( - m23, m33 );
  8744. this._y = 0;
  8745. }
  8746. break;
  8747. default:
  8748. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8749. }
  8750. this._order = order;
  8751. if ( update === true ) this._onChangeCallback();
  8752. return this;
  8753. }
  8754. /**
  8755. * Sets the angles of this Euler instance from a normalized quaternion.
  8756. *
  8757. * @param {Quaternion} q - A normalized Quaternion.
  8758. * @param {string} [order] - A string representing the order that the rotations are applied.
  8759. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8760. * @return {Euler} A reference to this Euler instance.
  8761. */
  8762. setFromQuaternion( q, order, update ) {
  8763. _matrix$2.makeRotationFromQuaternion( q );
  8764. return this.setFromRotationMatrix( _matrix$2, order, update );
  8765. }
  8766. /**
  8767. * Sets the angles of this Euler instance from the given vector.
  8768. *
  8769. * @param {Vector3} v - The vector.
  8770. * @param {string} [order] - A string representing the order that the rotations are applied.
  8771. * @return {Euler} A reference to this Euler instance.
  8772. */
  8773. setFromVector3( v, order = this._order ) {
  8774. return this.set( v.x, v.y, v.z, order );
  8775. }
  8776. /**
  8777. * Resets the euler angle with a new order by creating a quaternion from this
  8778. * euler angle and then setting this euler angle with the quaternion and the
  8779. * new order.
  8780. *
  8781. * Warning: This discards revolution information.
  8782. *
  8783. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  8784. * @return {Euler} A reference to this Euler instance.
  8785. */
  8786. reorder( newOrder ) {
  8787. _quaternion$4.setFromEuler( this );
  8788. return this.setFromQuaternion( _quaternion$4, newOrder );
  8789. }
  8790. /**
  8791. * Returns `true` if this Euler instance is equal with the given one.
  8792. *
  8793. * @param {Euler} euler - The Euler instance to test for equality.
  8794. * @return {boolean} Whether this Euler instance is equal with the given one.
  8795. */
  8796. equals( euler ) {
  8797. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8798. }
  8799. /**
  8800. * Sets this Euler instance's components to values from the given array. The first three
  8801. * entries of the array are assign to the x,y and z components. An optional fourth entry
  8802. * defines the Euler order.
  8803. *
  8804. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  8805. * @return {Euler} A reference to this Euler instance.
  8806. */
  8807. fromArray( array ) {
  8808. this._x = array[ 0 ];
  8809. this._y = array[ 1 ];
  8810. this._z = array[ 2 ];
  8811. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8812. this._onChangeCallback();
  8813. return this;
  8814. }
  8815. /**
  8816. * Writes the components of this Euler instance to the given array. If no array is provided,
  8817. * the method returns a new instance.
  8818. *
  8819. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  8820. * @param {number} [offset=0] - Index of the first element in the array.
  8821. * @return {Array<number,number,number,string>} The Euler components.
  8822. */
  8823. toArray( array = [], offset = 0 ) {
  8824. array[ offset ] = this._x;
  8825. array[ offset + 1 ] = this._y;
  8826. array[ offset + 2 ] = this._z;
  8827. array[ offset + 3 ] = this._order;
  8828. return array;
  8829. }
  8830. _onChange( callback ) {
  8831. this._onChangeCallback = callback;
  8832. return this;
  8833. }
  8834. _onChangeCallback() {}
  8835. *[ Symbol.iterator ]() {
  8836. yield this._x;
  8837. yield this._y;
  8838. yield this._z;
  8839. yield this._order;
  8840. }
  8841. }
  8842. /**
  8843. * The default Euler angle order.
  8844. *
  8845. * @static
  8846. * @type {string}
  8847. * @default 'XYZ'
  8848. */
  8849. Euler.DEFAULT_ORDER = 'XYZ';
  8850. /**
  8851. * A layers object assigns an 3D object to 1 or more of 32
  8852. * layers numbered `0` to `31` - internally the layers are stored as a
  8853. * bit mask], and by default all 3D objects are a member of layer `0`.
  8854. *
  8855. * This can be used to control visibility - an object must share a layer with
  8856. * a camera to be visible when that camera's view is
  8857. * rendered.
  8858. *
  8859. * All classes that inherit from {@link Object3D} have an `layers` property which
  8860. * is an instance of this class.
  8861. */
  8862. class Layers {
  8863. /**
  8864. * Constructs a new layers instance, with membership
  8865. * initially set to layer `0`.
  8866. */
  8867. constructor() {
  8868. /**
  8869. * A bit mask storing which of the 32 layers this layers object is currently
  8870. * a member of.
  8871. *
  8872. * @type {number}
  8873. */
  8874. this.mask = 1 | 0;
  8875. }
  8876. /**
  8877. * Sets membership to the given layer, and remove membership all other layers.
  8878. *
  8879. * @param {number} layer - The layer to set.
  8880. */
  8881. set( layer ) {
  8882. this.mask = ( 1 << layer | 0 ) >>> 0;
  8883. }
  8884. /**
  8885. * Adds membership of the given layer.
  8886. *
  8887. * @param {number} layer - The layer to enable.
  8888. */
  8889. enable( layer ) {
  8890. this.mask |= 1 << layer | 0;
  8891. }
  8892. /**
  8893. * Adds membership to all layers.
  8894. */
  8895. enableAll() {
  8896. this.mask = 0xffffffff | 0;
  8897. }
  8898. /**
  8899. * Toggles the membership of the given layer.
  8900. *
  8901. * @param {number} layer - The layer to toggle.
  8902. */
  8903. toggle( layer ) {
  8904. this.mask ^= 1 << layer | 0;
  8905. }
  8906. /**
  8907. * Removes membership of the given layer.
  8908. *
  8909. * @param {number} layer - The layer to enable.
  8910. */
  8911. disable( layer ) {
  8912. this.mask &= ~ ( 1 << layer | 0 );
  8913. }
  8914. /**
  8915. * Removes the membership from all layers.
  8916. */
  8917. disableAll() {
  8918. this.mask = 0;
  8919. }
  8920. /**
  8921. * Returns `true` if this and the given layers object have at least one
  8922. * layer in common.
  8923. *
  8924. * @param {Layers} layers - The layers to test.
  8925. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  8926. */
  8927. test( layers ) {
  8928. return ( this.mask & layers.mask ) !== 0;
  8929. }
  8930. /**
  8931. * Returns `true` if the given layer is enabled.
  8932. *
  8933. * @param {number} layer - The layer to test.
  8934. * @return {boolean } Whether the given layer is enabled or not.
  8935. */
  8936. isEnabled( layer ) {
  8937. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  8938. }
  8939. }
  8940. let _object3DId = 0;
  8941. const _v1$6 = /*@__PURE__*/ new Vector3();
  8942. const _q1 = /*@__PURE__*/ new Quaternion();
  8943. const _m1$3 = /*@__PURE__*/ new Matrix4();
  8944. const _target = /*@__PURE__*/ new Vector3();
  8945. const _position$4 = /*@__PURE__*/ new Vector3();
  8946. const _scale$3 = /*@__PURE__*/ new Vector3();
  8947. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  8948. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  8949. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8950. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  8951. /**
  8952. * Fires when the object has been added to its parent object.
  8953. *
  8954. * @event Object3D#added
  8955. * @type {Object}
  8956. */
  8957. const _addedEvent = { type: 'added' };
  8958. /**
  8959. * Fires when the object has been removed from its parent object.
  8960. *
  8961. * @event Object3D#removed
  8962. * @type {Object}
  8963. */
  8964. const _removedEvent = { type: 'removed' };
  8965. /**
  8966. * Fires when a new child object has been added.
  8967. *
  8968. * @event Object3D#childadded
  8969. * @type {Object}
  8970. */
  8971. const _childaddedEvent = { type: 'childadded', child: null };
  8972. /**
  8973. * Fires when a child object has been removed.
  8974. *
  8975. * @event Object3D#childremoved
  8976. * @type {Object}
  8977. */
  8978. const _childremovedEvent = { type: 'childremoved', child: null };
  8979. /**
  8980. * This is the base class for most objects in three.js and provides a set of
  8981. * properties and methods for manipulating objects in 3D space.
  8982. *
  8983. * @augments EventDispatcher
  8984. */
  8985. class Object3D extends EventDispatcher {
  8986. /**
  8987. * Constructs a new 3D object.
  8988. */
  8989. constructor() {
  8990. super();
  8991. /**
  8992. * This flag can be used for type testing.
  8993. *
  8994. * @type {boolean}
  8995. * @readonly
  8996. * @default true
  8997. */
  8998. this.isObject3D = true;
  8999. /**
  9000. * The ID of the 3D object.
  9001. *
  9002. * @name Object3D#id
  9003. * @type {number}
  9004. * @readonly
  9005. */
  9006. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9007. /**
  9008. * The UUID of the 3D object.
  9009. *
  9010. * @type {string}
  9011. * @readonly
  9012. */
  9013. this.uuid = generateUUID();
  9014. /**
  9015. * The name of the 3D object.
  9016. *
  9017. * @type {string}
  9018. */
  9019. this.name = '';
  9020. /**
  9021. * The type property is used for detecting the object type
  9022. * in context of serialization/deserialization.
  9023. *
  9024. * @type {string}
  9025. * @readonly
  9026. */
  9027. this.type = 'Object3D';
  9028. /**
  9029. * A reference to the parent object.
  9030. *
  9031. * @type {?Object3D}
  9032. * @default null
  9033. */
  9034. this.parent = null;
  9035. /**
  9036. * An array holding the child 3D objects of this instance.
  9037. *
  9038. * @type {Array<Object3D>}
  9039. */
  9040. this.children = [];
  9041. /**
  9042. * Defines the `up` direction of the 3D object which influences
  9043. * the orientation via methods like {@link Object3D#lookAt}.
  9044. *
  9045. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9046. *
  9047. * @type {Vector3}
  9048. */
  9049. this.up = Object3D.DEFAULT_UP.clone();
  9050. const position = new Vector3();
  9051. const rotation = new Euler();
  9052. const quaternion = new Quaternion();
  9053. const scale = new Vector3( 1, 1, 1 );
  9054. function onRotationChange() {
  9055. quaternion.setFromEuler( rotation, false );
  9056. }
  9057. function onQuaternionChange() {
  9058. rotation.setFromQuaternion( quaternion, undefined, false );
  9059. }
  9060. rotation._onChange( onRotationChange );
  9061. quaternion._onChange( onQuaternionChange );
  9062. Object.defineProperties( this, {
  9063. /**
  9064. * Represents the object's local position.
  9065. *
  9066. * @name Object3D#position
  9067. * @type {Vector3}
  9068. * @default (0,0,0)
  9069. */
  9070. position: {
  9071. configurable: true,
  9072. enumerable: true,
  9073. value: position
  9074. },
  9075. /**
  9076. * Represents the object's local rotation as Euler angles, in radians.
  9077. *
  9078. * @name Object3D#rotation
  9079. * @type {Euler}
  9080. * @default (0,0,0)
  9081. */
  9082. rotation: {
  9083. configurable: true,
  9084. enumerable: true,
  9085. value: rotation
  9086. },
  9087. /**
  9088. * Represents the object's local rotation as Quaternions.
  9089. *
  9090. * @name Object3D#quaternion
  9091. * @type {Quaternion}
  9092. */
  9093. quaternion: {
  9094. configurable: true,
  9095. enumerable: true,
  9096. value: quaternion
  9097. },
  9098. /**
  9099. * Represents the object's local scale.
  9100. *
  9101. * @name Object3D#scale
  9102. * @type {Vector3}
  9103. * @default (1,1,1)
  9104. */
  9105. scale: {
  9106. configurable: true,
  9107. enumerable: true,
  9108. value: scale
  9109. },
  9110. /**
  9111. * Represents the object's model-view matrix.
  9112. *
  9113. * @name Object3D#modelViewMatrix
  9114. * @type {Matrix4}
  9115. */
  9116. modelViewMatrix: {
  9117. value: new Matrix4()
  9118. },
  9119. /**
  9120. * Represents the object's normal matrix.
  9121. *
  9122. * @name Object3D#normalMatrix
  9123. * @type {Matrix3}
  9124. */
  9125. normalMatrix: {
  9126. value: new Matrix3()
  9127. }
  9128. } );
  9129. /**
  9130. * Represents the object's transformation matrix in local space.
  9131. *
  9132. * @type {Matrix4}
  9133. */
  9134. this.matrix = new Matrix4();
  9135. /**
  9136. * Represents the object's transformation matrix in world space.
  9137. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9138. *
  9139. * @type {Matrix4}
  9140. */
  9141. this.matrixWorld = new Matrix4();
  9142. /**
  9143. * When set to `true`, the engine automatically computes the local matrix from position,
  9144. * rotation and scale every frame. If set to `false`, the app is responsible for recomputing
  9145. * the local matrix by calling `updateMatrix()`.
  9146. *
  9147. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9148. *
  9149. * @type {boolean}
  9150. * @default true
  9151. */
  9152. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9153. /**
  9154. * When set to `true`, the engine automatically computes the world matrix from the current local
  9155. * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for
  9156. * recomputing the world matrix by directly updating the `matrixWorld` property.
  9157. *
  9158. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9159. *
  9160. * @type {boolean}
  9161. * @default true
  9162. */
  9163. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9164. /**
  9165. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9166. * to `false`.
  9167. *
  9168. * @type {boolean}
  9169. * @default false
  9170. */
  9171. this.matrixWorldNeedsUpdate = false;
  9172. /**
  9173. * The layer membership of the 3D object. The 3D object is only visible if it has
  9174. * at least one layer in common with the camera in use. This property can also be
  9175. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9176. *
  9177. * @type {Layers}
  9178. */
  9179. this.layers = new Layers();
  9180. /**
  9181. * When set to `true`, the 3D object gets rendered.
  9182. *
  9183. * @type {boolean}
  9184. * @default true
  9185. */
  9186. this.visible = true;
  9187. /**
  9188. * When set to `true`, the 3D object gets rendered into shadow maps.
  9189. *
  9190. * @type {boolean}
  9191. * @default false
  9192. */
  9193. this.castShadow = false;
  9194. /**
  9195. * When set to `true`, the 3D object is affected by shadows in the scene.
  9196. *
  9197. * @type {boolean}
  9198. * @default false
  9199. */
  9200. this.receiveShadow = false;
  9201. /**
  9202. * When set to `true`, the 3D object is honored by view frustum culling.
  9203. *
  9204. * @type {boolean}
  9205. * @default true
  9206. */
  9207. this.frustumCulled = true;
  9208. /**
  9209. * This value allows the default rendering order of scene graph objects to be
  9210. * overridden although opaque and transparent objects remain sorted independently.
  9211. * When this property is set for an instance of {@link Group},all descendants
  9212. * objects will be sorted and rendered together. Sorting is from lowest to highest
  9213. * render order.
  9214. *
  9215. * @type {number}
  9216. * @default 0
  9217. */
  9218. this.renderOrder = 0;
  9219. /**
  9220. * An array holding the animation clips of the 3D object.
  9221. *
  9222. * @type {Array<AnimationClip>}
  9223. */
  9224. this.animations = [];
  9225. /**
  9226. * Custom depth material to be used when rendering to the depth map. Can only be used
  9227. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  9228. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  9229. * material for proper shadows.
  9230. *
  9231. * Only relevant in context of {@link WebGLRenderer}.
  9232. *
  9233. * @type {(Material|undefined)}
  9234. * @default undefined
  9235. */
  9236. this.customDepthMaterial = undefined;
  9237. /**
  9238. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  9239. *
  9240. * Only relevant in context of {@link WebGLRenderer}.
  9241. *
  9242. * @type {(Material|undefined)}
  9243. * @default undefined
  9244. */
  9245. this.customDistanceMaterial = undefined;
  9246. /**
  9247. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  9248. * the 3D object is not going to be changed after the initial renderer. This includes
  9249. * geometry and material settings. A static 3D object can be processed by the renderer
  9250. * slightly faster since certain state checks can be bypassed.
  9251. *
  9252. * Only relevant in context of {@link WebGPURenderer}.
  9253. *
  9254. * @type {boolean}
  9255. * @default false
  9256. */
  9257. this.static = false;
  9258. /**
  9259. * An object that can be used to store custom data about the 3D object. It
  9260. * should not hold references to functions as these will not be cloned.
  9261. *
  9262. * @type {Object}
  9263. */
  9264. this.userData = {};
  9265. /**
  9266. * The pivot point for rotation and scale transformations.
  9267. * When set, rotation and scale are applied around this point
  9268. * instead of the object's origin.
  9269. *
  9270. * @type {?Vector3}
  9271. * @default null
  9272. */
  9273. this.pivot = null;
  9274. }
  9275. /**
  9276. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  9277. *
  9278. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9279. * @param {Object3D} object - The 3D object.
  9280. * @param {Camera} camera - The camera that is used to render the scene.
  9281. * @param {Camera} shadowCamera - The shadow camera.
  9282. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9283. * @param {Material} depthMaterial - The depth material.
  9284. * @param {Object} group - The geometry group data.
  9285. */
  9286. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9287. /**
  9288. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  9289. *
  9290. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9291. * @param {Object3D} object - The 3D object.
  9292. * @param {Camera} camera - The camera that is used to render the scene.
  9293. * @param {Camera} shadowCamera - The shadow camera.
  9294. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9295. * @param {Material} depthMaterial - The depth material.
  9296. * @param {Object} group - The geometry group data.
  9297. */
  9298. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9299. /**
  9300. * A callback that is executed immediately before a 3D object is rendered.
  9301. *
  9302. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9303. * @param {Object3D} object - The 3D object.
  9304. * @param {Camera} camera - The camera that is used to render the scene.
  9305. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9306. * @param {Material} material - The 3D object's material.
  9307. * @param {Object} group - The geometry group data.
  9308. */
  9309. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9310. /**
  9311. * A callback that is executed immediately after a 3D object is rendered.
  9312. *
  9313. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9314. * @param {Object3D} object - The 3D object.
  9315. * @param {Camera} camera - The camera that is used to render the scene.
  9316. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9317. * @param {Material} material - The 3D object's material.
  9318. * @param {Object} group - The geometry group data.
  9319. */
  9320. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9321. /**
  9322. * Applies the given transformation matrix to the object and updates the object's position,
  9323. * rotation and scale.
  9324. *
  9325. * @param {Matrix4} matrix - The transformation matrix.
  9326. */
  9327. applyMatrix4( matrix ) {
  9328. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9329. this.matrix.premultiply( matrix );
  9330. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9331. }
  9332. /**
  9333. * Applies a rotation represented by given the quaternion to the 3D object.
  9334. *
  9335. * @param {Quaternion} q - The quaternion.
  9336. * @return {Object3D} A reference to this instance.
  9337. */
  9338. applyQuaternion( q ) {
  9339. this.quaternion.premultiply( q );
  9340. return this;
  9341. }
  9342. /**
  9343. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  9344. *
  9345. * @param {Vector3} axis - The (normalized) axis vector.
  9346. * @param {number} angle - The angle in radians.
  9347. */
  9348. setRotationFromAxisAngle( axis, angle ) {
  9349. // assumes axis is normalized
  9350. this.quaternion.setFromAxisAngle( axis, angle );
  9351. }
  9352. /**
  9353. * Sets the given rotation represented as Euler angles to the 3D object.
  9354. *
  9355. * @param {Euler} euler - The Euler angles.
  9356. */
  9357. setRotationFromEuler( euler ) {
  9358. this.quaternion.setFromEuler( euler, true );
  9359. }
  9360. /**
  9361. * Sets the given rotation represented as rotation matrix to the 3D object.
  9362. *
  9363. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  9364. * a pure rotation matrix (i.e, unscaled).
  9365. */
  9366. setRotationFromMatrix( m ) {
  9367. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9368. this.quaternion.setFromRotationMatrix( m );
  9369. }
  9370. /**
  9371. * Sets the given rotation represented as a Quaternion to the 3D object.
  9372. *
  9373. * @param {Quaternion} q - The Quaternion
  9374. */
  9375. setRotationFromQuaternion( q ) {
  9376. // assumes q is normalized
  9377. this.quaternion.copy( q );
  9378. }
  9379. /**
  9380. * Rotates the 3D object along an axis in local space.
  9381. *
  9382. * @param {Vector3} axis - The (normalized) axis vector.
  9383. * @param {number} angle - The angle in radians.
  9384. * @return {Object3D} A reference to this instance.
  9385. */
  9386. rotateOnAxis( axis, angle ) {
  9387. // rotate object on axis in object space
  9388. // axis is assumed to be normalized
  9389. _q1.setFromAxisAngle( axis, angle );
  9390. this.quaternion.multiply( _q1 );
  9391. return this;
  9392. }
  9393. /**
  9394. * Rotates the 3D object along an axis in world space.
  9395. *
  9396. * @param {Vector3} axis - The (normalized) axis vector.
  9397. * @param {number} angle - The angle in radians.
  9398. * @return {Object3D} A reference to this instance.
  9399. */
  9400. rotateOnWorldAxis( axis, angle ) {
  9401. // rotate object on axis in world space
  9402. // axis is assumed to be normalized
  9403. // method assumes no rotated parent
  9404. _q1.setFromAxisAngle( axis, angle );
  9405. this.quaternion.premultiply( _q1 );
  9406. return this;
  9407. }
  9408. /**
  9409. * Rotates the 3D object around its X axis in local space.
  9410. *
  9411. * @param {number} angle - The angle in radians.
  9412. * @return {Object3D} A reference to this instance.
  9413. */
  9414. rotateX( angle ) {
  9415. return this.rotateOnAxis( _xAxis, angle );
  9416. }
  9417. /**
  9418. * Rotates the 3D object around its Y axis in local space.
  9419. *
  9420. * @param {number} angle - The angle in radians.
  9421. * @return {Object3D} A reference to this instance.
  9422. */
  9423. rotateY( angle ) {
  9424. return this.rotateOnAxis( _yAxis, angle );
  9425. }
  9426. /**
  9427. * Rotates the 3D object around its Z axis in local space.
  9428. *
  9429. * @param {number} angle - The angle in radians.
  9430. * @return {Object3D} A reference to this instance.
  9431. */
  9432. rotateZ( angle ) {
  9433. return this.rotateOnAxis( _zAxis, angle );
  9434. }
  9435. /**
  9436. * Translate the 3D object by a distance along the given axis in local space.
  9437. *
  9438. * @param {Vector3} axis - The (normalized) axis vector.
  9439. * @param {number} distance - The distance in world units.
  9440. * @return {Object3D} A reference to this instance.
  9441. */
  9442. translateOnAxis( axis, distance ) {
  9443. // translate object by distance along axis in object space
  9444. // axis is assumed to be normalized
  9445. _v1$6.copy( axis ).applyQuaternion( this.quaternion );
  9446. this.position.add( _v1$6.multiplyScalar( distance ) );
  9447. return this;
  9448. }
  9449. /**
  9450. * Translate the 3D object by a distance along its X-axis in local space.
  9451. *
  9452. * @param {number} distance - The distance in world units.
  9453. * @return {Object3D} A reference to this instance.
  9454. */
  9455. translateX( distance ) {
  9456. return this.translateOnAxis( _xAxis, distance );
  9457. }
  9458. /**
  9459. * Translate the 3D object by a distance along its Y-axis in local space.
  9460. *
  9461. * @param {number} distance - The distance in world units.
  9462. * @return {Object3D} A reference to this instance.
  9463. */
  9464. translateY( distance ) {
  9465. return this.translateOnAxis( _yAxis, distance );
  9466. }
  9467. /**
  9468. * Translate the 3D object by a distance along its Z-axis in local space.
  9469. *
  9470. * @param {number} distance - The distance in world units.
  9471. * @return {Object3D} A reference to this instance.
  9472. */
  9473. translateZ( distance ) {
  9474. return this.translateOnAxis( _zAxis, distance );
  9475. }
  9476. /**
  9477. * Converts the given vector from this 3D object's local space to world space.
  9478. *
  9479. * @param {Vector3} vector - The vector to convert.
  9480. * @return {Vector3} The converted vector.
  9481. */
  9482. localToWorld( vector ) {
  9483. this.updateWorldMatrix( true, false );
  9484. return vector.applyMatrix4( this.matrixWorld );
  9485. }
  9486. /**
  9487. * Converts the given vector from this 3D object's world space to local space.
  9488. *
  9489. * @param {Vector3} vector - The vector to convert.
  9490. * @return {Vector3} The converted vector.
  9491. */
  9492. worldToLocal( vector ) {
  9493. this.updateWorldMatrix( true, false );
  9494. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  9495. }
  9496. /**
  9497. * Rotates the object to face a point in world space.
  9498. *
  9499. * This method does not support objects having non-uniformly-scaled parent(s).
  9500. *
  9501. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  9502. * @param {number} [y] - The y coordinate in world space.
  9503. * @param {number} [z] - The z coordinate in world space.
  9504. */
  9505. lookAt( x, y, z ) {
  9506. // This method does not support objects having non-uniformly-scaled parent(s)
  9507. if ( x.isVector3 ) {
  9508. _target.copy( x );
  9509. } else {
  9510. _target.set( x, y, z );
  9511. }
  9512. const parent = this.parent;
  9513. this.updateWorldMatrix( true, false );
  9514. _position$4.setFromMatrixPosition( this.matrixWorld );
  9515. if ( this.isCamera || this.isLight ) {
  9516. _m1$3.lookAt( _position$4, _target, this.up );
  9517. } else {
  9518. _m1$3.lookAt( _target, _position$4, this.up );
  9519. }
  9520. this.quaternion.setFromRotationMatrix( _m1$3 );
  9521. if ( parent ) {
  9522. _m1$3.extractRotation( parent.matrixWorld );
  9523. _q1.setFromRotationMatrix( _m1$3 );
  9524. this.quaternion.premultiply( _q1.invert() );
  9525. }
  9526. }
  9527. /**
  9528. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  9529. * objects may be added. Any current parent on an object passed in here will be
  9530. * removed, since an object can have at most one parent.
  9531. *
  9532. * @fires Object3D#added
  9533. * @fires Object3D#childadded
  9534. * @param {Object3D} object - The 3D object to add.
  9535. * @return {Object3D} A reference to this instance.
  9536. */
  9537. add( object ) {
  9538. if ( arguments.length > 1 ) {
  9539. for ( let i = 0; i < arguments.length; i ++ ) {
  9540. this.add( arguments[ i ] );
  9541. }
  9542. return this;
  9543. }
  9544. if ( object === this ) {
  9545. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  9546. return this;
  9547. }
  9548. if ( object && object.isObject3D ) {
  9549. object.removeFromParent();
  9550. object.parent = this;
  9551. this.children.push( object );
  9552. object.dispatchEvent( _addedEvent );
  9553. _childaddedEvent.child = object;
  9554. this.dispatchEvent( _childaddedEvent );
  9555. _childaddedEvent.child = null;
  9556. } else {
  9557. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  9558. }
  9559. return this;
  9560. }
  9561. /**
  9562. * Removes the given 3D object as child from this 3D object.
  9563. * An arbitrary number of objects may be removed.
  9564. *
  9565. * @fires Object3D#removed
  9566. * @fires Object3D#childremoved
  9567. * @param {Object3D} object - The 3D object to remove.
  9568. * @return {Object3D} A reference to this instance.
  9569. */
  9570. remove( object ) {
  9571. if ( arguments.length > 1 ) {
  9572. for ( let i = 0; i < arguments.length; i ++ ) {
  9573. this.remove( arguments[ i ] );
  9574. }
  9575. return this;
  9576. }
  9577. const index = this.children.indexOf( object );
  9578. if ( index !== -1 ) {
  9579. object.parent = null;
  9580. this.children.splice( index, 1 );
  9581. object.dispatchEvent( _removedEvent );
  9582. _childremovedEvent.child = object;
  9583. this.dispatchEvent( _childremovedEvent );
  9584. _childremovedEvent.child = null;
  9585. }
  9586. return this;
  9587. }
  9588. /**
  9589. * Removes this 3D object from its current parent.
  9590. *
  9591. * @fires Object3D#removed
  9592. * @fires Object3D#childremoved
  9593. * @return {Object3D} A reference to this instance.
  9594. */
  9595. removeFromParent() {
  9596. const parent = this.parent;
  9597. if ( parent !== null ) {
  9598. parent.remove( this );
  9599. }
  9600. return this;
  9601. }
  9602. /**
  9603. * Removes all child objects.
  9604. *
  9605. * @fires Object3D#removed
  9606. * @fires Object3D#childremoved
  9607. * @return {Object3D} A reference to this instance.
  9608. */
  9609. clear() {
  9610. return this.remove( ... this.children );
  9611. }
  9612. /**
  9613. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  9614. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  9615. *
  9616. * @fires Object3D#added
  9617. * @fires Object3D#childadded
  9618. * @param {Object3D} object - The 3D object to attach.
  9619. * @return {Object3D} A reference to this instance.
  9620. */
  9621. attach( object ) {
  9622. // adds object as a child of this, while maintaining the object's world transform
  9623. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  9624. this.updateWorldMatrix( true, false );
  9625. _m1$3.copy( this.matrixWorld ).invert();
  9626. if ( object.parent !== null ) {
  9627. object.parent.updateWorldMatrix( true, false );
  9628. _m1$3.multiply( object.parent.matrixWorld );
  9629. }
  9630. object.applyMatrix4( _m1$3 );
  9631. object.removeFromParent();
  9632. object.parent = this;
  9633. this.children.push( object );
  9634. object.updateWorldMatrix( false, true );
  9635. object.dispatchEvent( _addedEvent );
  9636. _childaddedEvent.child = object;
  9637. this.dispatchEvent( _childaddedEvent );
  9638. _childaddedEvent.child = null;
  9639. return this;
  9640. }
  9641. /**
  9642. * Searches through the 3D object and its children, starting with the 3D object
  9643. * itself, and returns the first with a matching ID.
  9644. *
  9645. * @param {number} id - The id.
  9646. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9647. */
  9648. getObjectById( id ) {
  9649. return this.getObjectByProperty( 'id', id );
  9650. }
  9651. /**
  9652. * Searches through the 3D object and its children, starting with the 3D object
  9653. * itself, and returns the first with a matching name.
  9654. *
  9655. * @param {string} name - The name.
  9656. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9657. */
  9658. getObjectByName( name ) {
  9659. return this.getObjectByProperty( 'name', name );
  9660. }
  9661. /**
  9662. * Searches through the 3D object and its children, starting with the 3D object
  9663. * itself, and returns the first with a matching property value.
  9664. *
  9665. * @param {string} name - The name of the property.
  9666. * @param {any} value - The value.
  9667. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9668. */
  9669. getObjectByProperty( name, value ) {
  9670. if ( this[ name ] === value ) return this;
  9671. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  9672. const child = this.children[ i ];
  9673. const object = child.getObjectByProperty( name, value );
  9674. if ( object !== undefined ) {
  9675. return object;
  9676. }
  9677. }
  9678. return undefined;
  9679. }
  9680. /**
  9681. * Searches through the 3D object and its children, starting with the 3D object
  9682. * itself, and returns all 3D objects with a matching property value.
  9683. *
  9684. * @param {string} name - The name of the property.
  9685. * @param {any} value - The value.
  9686. * @param {Array<Object3D>} result - The method stores the result in this array.
  9687. * @return {Array<Object3D>} The found 3D objects.
  9688. */
  9689. getObjectsByProperty( name, value, result = [] ) {
  9690. if ( this[ name ] === value ) result.push( this );
  9691. const children = this.children;
  9692. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9693. children[ i ].getObjectsByProperty( name, value, result );
  9694. }
  9695. return result;
  9696. }
  9697. /**
  9698. * Returns a vector representing the position of the 3D object in world space.
  9699. *
  9700. * @param {Vector3} target - The target vector the result is stored to.
  9701. * @return {Vector3} The 3D object's position in world space.
  9702. */
  9703. getWorldPosition( target ) {
  9704. this.updateWorldMatrix( true, false );
  9705. return target.setFromMatrixPosition( this.matrixWorld );
  9706. }
  9707. /**
  9708. * Returns a Quaternion representing the position of the 3D object in world space.
  9709. *
  9710. * @param {Quaternion} target - The target Quaternion the result is stored to.
  9711. * @return {Quaternion} The 3D object's rotation in world space.
  9712. */
  9713. getWorldQuaternion( target ) {
  9714. this.updateWorldMatrix( true, false );
  9715. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  9716. return target;
  9717. }
  9718. /**
  9719. * Returns a vector representing the scale of the 3D object in world space.
  9720. *
  9721. * @param {Vector3} target - The target vector the result is stored to.
  9722. * @return {Vector3} The 3D object's scale in world space.
  9723. */
  9724. getWorldScale( target ) {
  9725. this.updateWorldMatrix( true, false );
  9726. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  9727. return target;
  9728. }
  9729. /**
  9730. * Returns a vector representing the ("look") direction of the 3D object in world space.
  9731. *
  9732. * @param {Vector3} target - The target vector the result is stored to.
  9733. * @return {Vector3} The 3D object's direction in world space.
  9734. */
  9735. getWorldDirection( target ) {
  9736. this.updateWorldMatrix( true, false );
  9737. const e = this.matrixWorld.elements;
  9738. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9739. }
  9740. /**
  9741. * Abstract method to get intersections between a casted ray and this
  9742. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  9743. * implement this method in order to use raycasting.
  9744. *
  9745. * @abstract
  9746. * @param {Raycaster} raycaster - The raycaster.
  9747. * @param {Array<Object>} intersects - An array holding the result of the method.
  9748. */
  9749. raycast( /* raycaster, intersects */ ) {}
  9750. /**
  9751. * Executes the callback on this 3D object and all descendants.
  9752. *
  9753. * Note: Modifying the scene graph inside the callback is discouraged.
  9754. *
  9755. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9756. */
  9757. traverse( callback ) {
  9758. callback( this );
  9759. const children = this.children;
  9760. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9761. children[ i ].traverse( callback );
  9762. }
  9763. }
  9764. /**
  9765. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  9766. * Descendants of invisible 3D objects are not traversed.
  9767. *
  9768. * Note: Modifying the scene graph inside the callback is discouraged.
  9769. *
  9770. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9771. */
  9772. traverseVisible( callback ) {
  9773. if ( this.visible === false ) return;
  9774. callback( this );
  9775. const children = this.children;
  9776. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9777. children[ i ].traverseVisible( callback );
  9778. }
  9779. }
  9780. /**
  9781. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  9782. *
  9783. * Note: Modifying the scene graph inside the callback is discouraged.
  9784. *
  9785. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9786. */
  9787. traverseAncestors( callback ) {
  9788. const parent = this.parent;
  9789. if ( parent !== null ) {
  9790. callback( parent );
  9791. parent.traverseAncestors( callback );
  9792. }
  9793. }
  9794. /**
  9795. * Updates the transformation matrix in local space by computing it from the current
  9796. * position, rotation and scale values.
  9797. */
  9798. updateMatrix() {
  9799. this.matrix.compose( this.position, this.quaternion, this.scale );
  9800. const pivot = this.pivot;
  9801. if ( pivot !== null ) {
  9802. const px = pivot.x, py = pivot.y, pz = pivot.z;
  9803. const te = this.matrix.elements;
  9804. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  9805. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  9806. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  9807. }
  9808. this.matrixWorldNeedsUpdate = true;
  9809. }
  9810. /**
  9811. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  9812. *
  9813. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  9814. * local space. The computation of the local and world matrix can be controlled with the
  9815. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  9816. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  9817. *
  9818. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9819. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9820. */
  9821. updateMatrixWorld( force ) {
  9822. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9823. if ( this.matrixWorldNeedsUpdate || force ) {
  9824. if ( this.matrixWorldAutoUpdate === true ) {
  9825. if ( this.parent === null ) {
  9826. this.matrixWorld.copy( this.matrix );
  9827. } else {
  9828. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9829. }
  9830. }
  9831. this.matrixWorldNeedsUpdate = false;
  9832. force = true;
  9833. }
  9834. // make sure descendants are updated if required
  9835. const children = this.children;
  9836. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9837. const child = children[ i ];
  9838. child.updateMatrixWorld( force );
  9839. }
  9840. }
  9841. /**
  9842. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  9843. * update of ancestor and descendant nodes.
  9844. *
  9845. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  9846. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  9847. */
  9848. updateWorldMatrix( updateParents, updateChildren ) {
  9849. const parent = this.parent;
  9850. if ( updateParents === true && parent !== null ) {
  9851. parent.updateWorldMatrix( true, false );
  9852. }
  9853. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9854. if ( this.matrixWorldAutoUpdate === true ) {
  9855. if ( this.parent === null ) {
  9856. this.matrixWorld.copy( this.matrix );
  9857. } else {
  9858. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9859. }
  9860. }
  9861. // make sure descendants are updated
  9862. if ( updateChildren === true ) {
  9863. const children = this.children;
  9864. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9865. const child = children[ i ];
  9866. child.updateWorldMatrix( false, true );
  9867. }
  9868. }
  9869. }
  9870. /**
  9871. * Serializes the 3D object into JSON.
  9872. *
  9873. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  9874. * @return {Object} A JSON object representing the serialized 3D object.
  9875. * @see {@link ObjectLoader#parse}
  9876. */
  9877. toJSON( meta ) {
  9878. // meta is a string when called from JSON.stringify
  9879. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  9880. const output = {};
  9881. // meta is a hash used to collect geometries, materials.
  9882. // not providing it implies that this is the root object
  9883. // being serialized.
  9884. if ( isRootObject ) {
  9885. // initialize meta obj
  9886. meta = {
  9887. geometries: {},
  9888. materials: {},
  9889. textures: {},
  9890. images: {},
  9891. shapes: {},
  9892. skeletons: {},
  9893. animations: {},
  9894. nodes: {}
  9895. };
  9896. output.metadata = {
  9897. version: 4.7,
  9898. type: 'Object',
  9899. generator: 'Object3D.toJSON'
  9900. };
  9901. }
  9902. // standard Object3D serialization
  9903. const object = {};
  9904. object.uuid = this.uuid;
  9905. object.type = this.type;
  9906. if ( this.name !== '' ) object.name = this.name;
  9907. if ( this.castShadow === true ) object.castShadow = true;
  9908. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9909. if ( this.visible === false ) object.visible = false;
  9910. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9911. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9912. if ( this.static !== false ) object.static = this.static;
  9913. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  9914. object.layers = this.layers.mask;
  9915. object.matrix = this.matrix.toArray();
  9916. object.up = this.up.toArray();
  9917. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  9918. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9919. if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary );
  9920. if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice();
  9921. // object specific properties
  9922. if ( this.isInstancedMesh ) {
  9923. object.type = 'InstancedMesh';
  9924. object.count = this.count;
  9925. object.instanceMatrix = this.instanceMatrix.toJSON();
  9926. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  9927. }
  9928. if ( this.isBatchedMesh ) {
  9929. object.type = 'BatchedMesh';
  9930. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  9931. object.sortObjects = this.sortObjects;
  9932. object.drawRanges = this._drawRanges;
  9933. object.reservedRanges = this._reservedRanges;
  9934. object.geometryInfo = this._geometryInfo.map( info => ( {
  9935. ...info,
  9936. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  9937. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  9938. } ) );
  9939. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  9940. object.availableInstanceIds = this._availableInstanceIds.slice();
  9941. object.availableGeometryIds = this._availableGeometryIds.slice();
  9942. object.nextIndexStart = this._nextIndexStart;
  9943. object.nextVertexStart = this._nextVertexStart;
  9944. object.geometryCount = this._geometryCount;
  9945. object.maxInstanceCount = this._maxInstanceCount;
  9946. object.maxVertexCount = this._maxVertexCount;
  9947. object.maxIndexCount = this._maxIndexCount;
  9948. object.geometryInitialized = this._geometryInitialized;
  9949. object.matricesTexture = this._matricesTexture.toJSON( meta );
  9950. object.indirectTexture = this._indirectTexture.toJSON( meta );
  9951. if ( this._colorsTexture !== null ) {
  9952. object.colorsTexture = this._colorsTexture.toJSON( meta );
  9953. }
  9954. if ( this.boundingSphere !== null ) {
  9955. object.boundingSphere = this.boundingSphere.toJSON();
  9956. }
  9957. if ( this.boundingBox !== null ) {
  9958. object.boundingBox = this.boundingBox.toJSON();
  9959. }
  9960. }
  9961. //
  9962. function serialize( library, element ) {
  9963. if ( library[ element.uuid ] === undefined ) {
  9964. library[ element.uuid ] = element.toJSON( meta );
  9965. }
  9966. return element.uuid;
  9967. }
  9968. if ( this.isScene ) {
  9969. if ( this.background ) {
  9970. if ( this.background.isColor ) {
  9971. object.background = this.background.toJSON();
  9972. } else if ( this.background.isTexture ) {
  9973. object.background = this.background.toJSON( meta ).uuid;
  9974. }
  9975. }
  9976. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  9977. object.environment = this.environment.toJSON( meta ).uuid;
  9978. }
  9979. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  9980. object.geometry = serialize( meta.geometries, this.geometry );
  9981. const parameters = this.geometry.parameters;
  9982. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  9983. const shapes = parameters.shapes;
  9984. if ( Array.isArray( shapes ) ) {
  9985. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  9986. const shape = shapes[ i ];
  9987. serialize( meta.shapes, shape );
  9988. }
  9989. } else {
  9990. serialize( meta.shapes, shapes );
  9991. }
  9992. }
  9993. }
  9994. if ( this.isSkinnedMesh ) {
  9995. object.bindMode = this.bindMode;
  9996. object.bindMatrix = this.bindMatrix.toArray();
  9997. if ( this.skeleton !== undefined ) {
  9998. serialize( meta.skeletons, this.skeleton );
  9999. object.skeleton = this.skeleton.uuid;
  10000. }
  10001. }
  10002. if ( this.material !== undefined ) {
  10003. if ( Array.isArray( this.material ) ) {
  10004. const uuids = [];
  10005. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10006. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10007. }
  10008. object.material = uuids;
  10009. } else {
  10010. object.material = serialize( meta.materials, this.material );
  10011. }
  10012. }
  10013. //
  10014. if ( this.children.length > 0 ) {
  10015. object.children = [];
  10016. for ( let i = 0; i < this.children.length; i ++ ) {
  10017. object.children.push( this.children[ i ].toJSON( meta ).object );
  10018. }
  10019. }
  10020. //
  10021. if ( this.animations.length > 0 ) {
  10022. object.animations = [];
  10023. for ( let i = 0; i < this.animations.length; i ++ ) {
  10024. const animation = this.animations[ i ];
  10025. object.animations.push( serialize( meta.animations, animation ) );
  10026. }
  10027. }
  10028. if ( isRootObject ) {
  10029. const geometries = extractFromCache( meta.geometries );
  10030. const materials = extractFromCache( meta.materials );
  10031. const textures = extractFromCache( meta.textures );
  10032. const images = extractFromCache( meta.images );
  10033. const shapes = extractFromCache( meta.shapes );
  10034. const skeletons = extractFromCache( meta.skeletons );
  10035. const animations = extractFromCache( meta.animations );
  10036. const nodes = extractFromCache( meta.nodes );
  10037. if ( geometries.length > 0 ) output.geometries = geometries;
  10038. if ( materials.length > 0 ) output.materials = materials;
  10039. if ( textures.length > 0 ) output.textures = textures;
  10040. if ( images.length > 0 ) output.images = images;
  10041. if ( shapes.length > 0 ) output.shapes = shapes;
  10042. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10043. if ( animations.length > 0 ) output.animations = animations;
  10044. if ( nodes.length > 0 ) output.nodes = nodes;
  10045. }
  10046. output.object = object;
  10047. return output;
  10048. // extract data from the cache hash
  10049. // remove metadata on each item
  10050. // and return as array
  10051. function extractFromCache( cache ) {
  10052. const values = [];
  10053. for ( const key in cache ) {
  10054. const data = cache[ key ];
  10055. delete data.metadata;
  10056. values.push( data );
  10057. }
  10058. return values;
  10059. }
  10060. }
  10061. /**
  10062. * Returns a new 3D object with copied values from this instance.
  10063. *
  10064. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10065. * @return {Object3D} A clone of this instance.
  10066. */
  10067. clone( recursive ) {
  10068. return new this.constructor().copy( this, recursive );
  10069. }
  10070. /**
  10071. * Copies the values of the given 3D object to this instance.
  10072. *
  10073. * @param {Object3D} source - The 3D object to copy.
  10074. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10075. * @return {Object3D} A reference to this instance.
  10076. */
  10077. copy( source, recursive = true ) {
  10078. this.name = source.name;
  10079. this.up.copy( source.up );
  10080. this.position.copy( source.position );
  10081. this.rotation.order = source.rotation.order;
  10082. this.quaternion.copy( source.quaternion );
  10083. this.scale.copy( source.scale );
  10084. if ( source.pivot !== null ) {
  10085. this.pivot = source.pivot.clone();
  10086. }
  10087. this.matrix.copy( source.matrix );
  10088. this.matrixWorld.copy( source.matrixWorld );
  10089. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10090. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10091. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10092. this.layers.mask = source.layers.mask;
  10093. this.visible = source.visible;
  10094. this.castShadow = source.castShadow;
  10095. this.receiveShadow = source.receiveShadow;
  10096. this.frustumCulled = source.frustumCulled;
  10097. this.renderOrder = source.renderOrder;
  10098. this.static = source.static;
  10099. this.animations = source.animations.slice();
  10100. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10101. if ( recursive === true ) {
  10102. for ( let i = 0; i < source.children.length; i ++ ) {
  10103. const child = source.children[ i ];
  10104. this.add( child.clone() );
  10105. }
  10106. }
  10107. return this;
  10108. }
  10109. }
  10110. /**
  10111. * The default up direction for objects, also used as the default
  10112. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10113. *
  10114. * @static
  10115. * @type {Vector3}
  10116. * @default (0,1,0)
  10117. */
  10118. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10119. /**
  10120. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10121. * newly created 3D objects.
  10122. *
  10123. * @static
  10124. * @type {boolean}
  10125. * @default true
  10126. */
  10127. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10128. /**
  10129. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10130. * newly created 3D objects.
  10131. *
  10132. * @static
  10133. * @type {boolean}
  10134. * @default true
  10135. */
  10136. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10137. /**
  10138. * This is almost identical to an {@link Object3D}. Its purpose is to
  10139. * make working with groups of objects syntactically clearer.
  10140. *
  10141. * ```js
  10142. * // Create a group and add the two cubes.
  10143. * // These cubes can now be rotated / scaled etc as a group.
  10144. * const group = new THREE.Group();
  10145. *
  10146. * group.add( meshA );
  10147. * group.add( meshB );
  10148. *
  10149. * scene.add( group );
  10150. * ```
  10151. *
  10152. * @augments Object3D
  10153. */
  10154. class Group extends Object3D {
  10155. constructor() {
  10156. super();
  10157. /**
  10158. * This flag can be used for type testing.
  10159. *
  10160. * @type {boolean}
  10161. * @readonly
  10162. * @default true
  10163. */
  10164. this.isGroup = true;
  10165. this.type = 'Group';
  10166. }
  10167. }
  10168. const _moveEvent = { type: 'move' };
  10169. /**
  10170. * Class for representing a XR controller with its
  10171. * different coordinate systems.
  10172. *
  10173. * @private
  10174. */
  10175. class WebXRController {
  10176. /**
  10177. * Constructs a new XR controller.
  10178. */
  10179. constructor() {
  10180. /**
  10181. * A group representing the target ray space
  10182. * of the XR controller.
  10183. *
  10184. * @private
  10185. * @type {?Group}
  10186. * @default null
  10187. */
  10188. this._targetRay = null;
  10189. /**
  10190. * A group representing the grip space
  10191. * of the XR controller.
  10192. *
  10193. * @private
  10194. * @type {?Group}
  10195. * @default null
  10196. */
  10197. this._grip = null;
  10198. /**
  10199. * A group representing the hand space
  10200. * of the XR controller.
  10201. *
  10202. * @private
  10203. * @type {?Group}
  10204. * @default null
  10205. */
  10206. this._hand = null;
  10207. }
  10208. /**
  10209. * Returns a group representing the hand space of the XR controller.
  10210. *
  10211. * @return {Group} A group representing the hand space of the XR controller.
  10212. */
  10213. getHandSpace() {
  10214. if ( this._hand === null ) {
  10215. this._hand = new Group();
  10216. this._hand.matrixAutoUpdate = false;
  10217. this._hand.visible = false;
  10218. this._hand.joints = {};
  10219. this._hand.inputState = { pinching: false };
  10220. }
  10221. return this._hand;
  10222. }
  10223. /**
  10224. * Returns a group representing the target ray space of the XR controller.
  10225. *
  10226. * @return {Group} A group representing the target ray space of the XR controller.
  10227. */
  10228. getTargetRaySpace() {
  10229. if ( this._targetRay === null ) {
  10230. this._targetRay = new Group();
  10231. this._targetRay.matrixAutoUpdate = false;
  10232. this._targetRay.visible = false;
  10233. this._targetRay.hasLinearVelocity = false;
  10234. this._targetRay.linearVelocity = new Vector3();
  10235. this._targetRay.hasAngularVelocity = false;
  10236. this._targetRay.angularVelocity = new Vector3();
  10237. }
  10238. return this._targetRay;
  10239. }
  10240. /**
  10241. * Returns a group representing the grip space of the XR controller.
  10242. *
  10243. * @return {Group} A group representing the grip space of the XR controller.
  10244. */
  10245. getGripSpace() {
  10246. if ( this._grip === null ) {
  10247. this._grip = new Group();
  10248. this._grip.matrixAutoUpdate = false;
  10249. this._grip.visible = false;
  10250. this._grip.hasLinearVelocity = false;
  10251. this._grip.linearVelocity = new Vector3();
  10252. this._grip.hasAngularVelocity = false;
  10253. this._grip.angularVelocity = new Vector3();
  10254. }
  10255. return this._grip;
  10256. }
  10257. /**
  10258. * Dispatches the given event to the groups representing
  10259. * the different coordinate spaces of the XR controller.
  10260. *
  10261. * @param {Object} event - The event to dispatch.
  10262. * @return {WebXRController} A reference to this instance.
  10263. */
  10264. dispatchEvent( event ) {
  10265. if ( this._targetRay !== null ) {
  10266. this._targetRay.dispatchEvent( event );
  10267. }
  10268. if ( this._grip !== null ) {
  10269. this._grip.dispatchEvent( event );
  10270. }
  10271. if ( this._hand !== null ) {
  10272. this._hand.dispatchEvent( event );
  10273. }
  10274. return this;
  10275. }
  10276. /**
  10277. * Connects the controller with the given XR input source.
  10278. *
  10279. * @param {XRInputSource} inputSource - The input source.
  10280. * @return {WebXRController} A reference to this instance.
  10281. */
  10282. connect( inputSource ) {
  10283. if ( inputSource && inputSource.hand ) {
  10284. const hand = this._hand;
  10285. if ( hand ) {
  10286. for ( const inputjoint of inputSource.hand.values() ) {
  10287. // Initialize hand with joints when connected
  10288. this._getHandJoint( hand, inputjoint );
  10289. }
  10290. }
  10291. }
  10292. this.dispatchEvent( { type: 'connected', data: inputSource } );
  10293. return this;
  10294. }
  10295. /**
  10296. * Disconnects the controller from the given XR input source.
  10297. *
  10298. * @param {XRInputSource} inputSource - The input source.
  10299. * @return {WebXRController} A reference to this instance.
  10300. */
  10301. disconnect( inputSource ) {
  10302. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  10303. if ( this._targetRay !== null ) {
  10304. this._targetRay.visible = false;
  10305. }
  10306. if ( this._grip !== null ) {
  10307. this._grip.visible = false;
  10308. }
  10309. if ( this._hand !== null ) {
  10310. this._hand.visible = false;
  10311. }
  10312. return this;
  10313. }
  10314. /**
  10315. * Updates the controller with the given input source, XR frame and reference space.
  10316. * This updates the transformations of the groups that represent the different
  10317. * coordinate systems of the controller.
  10318. *
  10319. * @param {XRInputSource} inputSource - The input source.
  10320. * @param {XRFrame} frame - The XR frame.
  10321. * @param {XRReferenceSpace} referenceSpace - The reference space.
  10322. * @return {WebXRController} A reference to this instance.
  10323. */
  10324. update( inputSource, frame, referenceSpace ) {
  10325. let inputPose = null;
  10326. let gripPose = null;
  10327. let handPose = null;
  10328. const targetRay = this._targetRay;
  10329. const grip = this._grip;
  10330. const hand = this._hand;
  10331. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  10332. if ( hand && inputSource.hand ) {
  10333. handPose = true;
  10334. for ( const inputjoint of inputSource.hand.values() ) {
  10335. // Update the joints groups with the XRJoint poses
  10336. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  10337. // The transform of this joint will be updated with the joint pose on each frame
  10338. const joint = this._getHandJoint( hand, inputjoint );
  10339. if ( jointPose !== null ) {
  10340. joint.matrix.fromArray( jointPose.transform.matrix );
  10341. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  10342. joint.matrixWorldNeedsUpdate = true;
  10343. joint.jointRadius = jointPose.radius;
  10344. }
  10345. joint.visible = jointPose !== null;
  10346. }
  10347. // Custom events
  10348. // Check pinchz
  10349. const indexTip = hand.joints[ 'index-finger-tip' ];
  10350. const thumbTip = hand.joints[ 'thumb-tip' ];
  10351. const distance = indexTip.position.distanceTo( thumbTip.position );
  10352. const distanceToPinch = 0.02;
  10353. const threshold = 0.005;
  10354. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  10355. hand.inputState.pinching = false;
  10356. this.dispatchEvent( {
  10357. type: 'pinchend',
  10358. handedness: inputSource.handedness,
  10359. target: this
  10360. } );
  10361. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  10362. hand.inputState.pinching = true;
  10363. this.dispatchEvent( {
  10364. type: 'pinchstart',
  10365. handedness: inputSource.handedness,
  10366. target: this
  10367. } );
  10368. }
  10369. } else {
  10370. if ( grip !== null && inputSource.gripSpace ) {
  10371. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  10372. if ( gripPose !== null ) {
  10373. grip.matrix.fromArray( gripPose.transform.matrix );
  10374. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  10375. grip.matrixWorldNeedsUpdate = true;
  10376. if ( gripPose.linearVelocity ) {
  10377. grip.hasLinearVelocity = true;
  10378. grip.linearVelocity.copy( gripPose.linearVelocity );
  10379. } else {
  10380. grip.hasLinearVelocity = false;
  10381. }
  10382. if ( gripPose.angularVelocity ) {
  10383. grip.hasAngularVelocity = true;
  10384. grip.angularVelocity.copy( gripPose.angularVelocity );
  10385. } else {
  10386. grip.hasAngularVelocity = false;
  10387. }
  10388. }
  10389. }
  10390. }
  10391. if ( targetRay !== null ) {
  10392. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  10393. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  10394. if ( inputPose === null && gripPose !== null ) {
  10395. inputPose = gripPose;
  10396. }
  10397. if ( inputPose !== null ) {
  10398. targetRay.matrix.fromArray( inputPose.transform.matrix );
  10399. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  10400. targetRay.matrixWorldNeedsUpdate = true;
  10401. if ( inputPose.linearVelocity ) {
  10402. targetRay.hasLinearVelocity = true;
  10403. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  10404. } else {
  10405. targetRay.hasLinearVelocity = false;
  10406. }
  10407. if ( inputPose.angularVelocity ) {
  10408. targetRay.hasAngularVelocity = true;
  10409. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  10410. } else {
  10411. targetRay.hasAngularVelocity = false;
  10412. }
  10413. this.dispatchEvent( _moveEvent );
  10414. }
  10415. }
  10416. }
  10417. if ( targetRay !== null ) {
  10418. targetRay.visible = ( inputPose !== null );
  10419. }
  10420. if ( grip !== null ) {
  10421. grip.visible = ( gripPose !== null );
  10422. }
  10423. if ( hand !== null ) {
  10424. hand.visible = ( handPose !== null );
  10425. }
  10426. return this;
  10427. }
  10428. /**
  10429. * Returns a group representing the hand joint for the given input joint.
  10430. *
  10431. * @private
  10432. * @param {Group} hand - The group representing the hand space.
  10433. * @param {XRJointSpace} inputjoint - The hand joint data.
  10434. * @return {Group} A group representing the hand joint for the given input joint.
  10435. */
  10436. _getHandJoint( hand, inputjoint ) {
  10437. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  10438. const joint = new Group();
  10439. joint.matrixAutoUpdate = false;
  10440. joint.visible = false;
  10441. hand.joints[ inputjoint.jointName ] = joint;
  10442. hand.add( joint );
  10443. }
  10444. return hand.joints[ inputjoint.jointName ];
  10445. }
  10446. }
  10447. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10448. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10449. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10450. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10451. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10452. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10453. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10454. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10455. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10456. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10457. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10458. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10459. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10460. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10461. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10462. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10463. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10464. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10465. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10466. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10467. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10468. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10469. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10470. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10471. const _hslA = { h: 0, s: 0, l: 0 };
  10472. const _hslB = { h: 0, s: 0, l: 0 };
  10473. function hue2rgb( p, q, t ) {
  10474. if ( t < 0 ) t += 1;
  10475. if ( t > 1 ) t -= 1;
  10476. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  10477. if ( t < 1 / 2 ) return q;
  10478. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  10479. return p;
  10480. }
  10481. /**
  10482. * A Color instance is represented by RGB components in the linear <i>working
  10483. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  10484. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  10485. * strings) are converted to the working color space automatically.
  10486. *
  10487. * ```js
  10488. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  10489. * const color = new THREE.Color().setHex( 0x112233 );
  10490. * ```
  10491. * Source color spaces may be specified explicitly, to ensure correct conversions.
  10492. * ```js
  10493. * // assumed already LinearSRGBColorSpace; no conversion
  10494. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  10495. *
  10496. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  10497. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  10498. * ```
  10499. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  10500. * see <i>Color management</i>. Iterating through a Color instance will yield
  10501. * its components (r, g, b) in the corresponding order. A Color can be initialised
  10502. * in any of the following ways:
  10503. * ```js
  10504. * //empty constructor - will default white
  10505. * const color1 = new THREE.Color();
  10506. *
  10507. * //Hexadecimal color (recommended)
  10508. * const color2 = new THREE.Color( 0xff0000 );
  10509. *
  10510. * //RGB string
  10511. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  10512. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  10513. *
  10514. * //X11 color name - all 140 color names are supported.
  10515. * //Note the lack of CamelCase in the name
  10516. * const color5 = new THREE.Color( 'skyblue' );
  10517. * //HSL string
  10518. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  10519. *
  10520. * //Separate RGB values between 0 and 1
  10521. * const color7 = new THREE.Color( 1, 0, 0 );
  10522. * ```
  10523. */
  10524. class Color {
  10525. /**
  10526. * Constructs a new color.
  10527. *
  10528. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  10529. * and that method is used throughout the rest of the documentation.
  10530. *
  10531. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10532. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10533. * @param {number} [g] - The green component.
  10534. * @param {number} [b] - The blue component.
  10535. */
  10536. constructor( r, g, b ) {
  10537. /**
  10538. * This flag can be used for type testing.
  10539. *
  10540. * @type {boolean}
  10541. * @readonly
  10542. * @default true
  10543. */
  10544. this.isColor = true;
  10545. /**
  10546. * The red component.
  10547. *
  10548. * @type {number}
  10549. * @default 1
  10550. */
  10551. this.r = 1;
  10552. /**
  10553. * The green component.
  10554. *
  10555. * @type {number}
  10556. * @default 1
  10557. */
  10558. this.g = 1;
  10559. /**
  10560. * The blue component.
  10561. *
  10562. * @type {number}
  10563. * @default 1
  10564. */
  10565. this.b = 1;
  10566. return this.set( r, g, b );
  10567. }
  10568. /**
  10569. * Sets the colors's components from the given values.
  10570. *
  10571. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10572. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10573. * @param {number} [g] - The green component.
  10574. * @param {number} [b] - The blue component.
  10575. * @return {Color} A reference to this color.
  10576. */
  10577. set( r, g, b ) {
  10578. if ( g === undefined && b === undefined ) {
  10579. // r is THREE.Color, hex or string
  10580. const value = r;
  10581. if ( value && value.isColor ) {
  10582. this.copy( value );
  10583. } else if ( typeof value === 'number' ) {
  10584. this.setHex( value );
  10585. } else if ( typeof value === 'string' ) {
  10586. this.setStyle( value );
  10587. }
  10588. } else {
  10589. this.setRGB( r, g, b );
  10590. }
  10591. return this;
  10592. }
  10593. /**
  10594. * Sets the colors's components to the given scalar value.
  10595. *
  10596. * @param {number} scalar - The scalar value.
  10597. * @return {Color} A reference to this color.
  10598. */
  10599. setScalar( scalar ) {
  10600. this.r = scalar;
  10601. this.g = scalar;
  10602. this.b = scalar;
  10603. return this;
  10604. }
  10605. /**
  10606. * Sets this color from a hexadecimal value.
  10607. *
  10608. * @param {number} hex - The hexadecimal value.
  10609. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10610. * @return {Color} A reference to this color.
  10611. */
  10612. setHex( hex, colorSpace = SRGBColorSpace ) {
  10613. hex = Math.floor( hex );
  10614. this.r = ( hex >> 16 & 255 ) / 255;
  10615. this.g = ( hex >> 8 & 255 ) / 255;
  10616. this.b = ( hex & 255 ) / 255;
  10617. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10618. return this;
  10619. }
  10620. /**
  10621. * Sets this color from RGB values.
  10622. *
  10623. * @param {number} r - Red channel value between `0.0` and `1.0`.
  10624. * @param {number} g - Green channel value between `0.0` and `1.0`.
  10625. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  10626. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10627. * @return {Color} A reference to this color.
  10628. */
  10629. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  10630. this.r = r;
  10631. this.g = g;
  10632. this.b = b;
  10633. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10634. return this;
  10635. }
  10636. /**
  10637. * Sets this color from RGB values.
  10638. *
  10639. * @param {number} h - Hue value between `0.0` and `1.0`.
  10640. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10641. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10642. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10643. * @return {Color} A reference to this color.
  10644. */
  10645. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  10646. // h,s,l ranges are in 0.0 - 1.0
  10647. h = euclideanModulo( h, 1 );
  10648. s = clamp( s, 0, 1 );
  10649. l = clamp( l, 0, 1 );
  10650. if ( s === 0 ) {
  10651. this.r = this.g = this.b = l;
  10652. } else {
  10653. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10654. const q = ( 2 * l ) - p;
  10655. this.r = hue2rgb( q, p, h + 1 / 3 );
  10656. this.g = hue2rgb( q, p, h );
  10657. this.b = hue2rgb( q, p, h - 1 / 3 );
  10658. }
  10659. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10660. return this;
  10661. }
  10662. /**
  10663. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  10664. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  10665. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  10666. * all 140 color names are supported).
  10667. *
  10668. * @param {string} style - Color as a CSS-style string.
  10669. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10670. * @return {Color} A reference to this color.
  10671. */
  10672. setStyle( style, colorSpace = SRGBColorSpace ) {
  10673. function handleAlpha( string ) {
  10674. if ( string === undefined ) return;
  10675. if ( parseFloat( string ) < 1 ) {
  10676. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  10677. }
  10678. }
  10679. let m;
  10680. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  10681. // rgb / hsl
  10682. let color;
  10683. const name = m[ 1 ];
  10684. const components = m[ 2 ];
  10685. switch ( name ) {
  10686. case 'rgb':
  10687. case 'rgba':
  10688. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10689. // rgb(255,0,0) rgba(255,0,0,0.5)
  10690. handleAlpha( color[ 4 ] );
  10691. return this.setRGB(
  10692. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  10693. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  10694. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  10695. colorSpace
  10696. );
  10697. }
  10698. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10699. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10700. handleAlpha( color[ 4 ] );
  10701. return this.setRGB(
  10702. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  10703. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  10704. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  10705. colorSpace
  10706. );
  10707. }
  10708. break;
  10709. case 'hsl':
  10710. case 'hsla':
  10711. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10712. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10713. handleAlpha( color[ 4 ] );
  10714. return this.setHSL(
  10715. parseFloat( color[ 1 ] ) / 360,
  10716. parseFloat( color[ 2 ] ) / 100,
  10717. parseFloat( color[ 3 ] ) / 100,
  10718. colorSpace
  10719. );
  10720. }
  10721. break;
  10722. default:
  10723. warn( 'Color: Unknown color model ' + style );
  10724. }
  10725. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  10726. // hex color
  10727. const hex = m[ 1 ];
  10728. const size = hex.length;
  10729. if ( size === 3 ) {
  10730. // #ff0
  10731. return this.setRGB(
  10732. parseInt( hex.charAt( 0 ), 16 ) / 15,
  10733. parseInt( hex.charAt( 1 ), 16 ) / 15,
  10734. parseInt( hex.charAt( 2 ), 16 ) / 15,
  10735. colorSpace
  10736. );
  10737. } else if ( size === 6 ) {
  10738. // #ff0000
  10739. return this.setHex( parseInt( hex, 16 ), colorSpace );
  10740. } else {
  10741. warn( 'Color: Invalid hex color ' + style );
  10742. }
  10743. } else if ( style && style.length > 0 ) {
  10744. return this.setColorName( style, colorSpace );
  10745. }
  10746. return this;
  10747. }
  10748. /**
  10749. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  10750. * you don't need the other CSS-style formats.
  10751. *
  10752. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  10753. * ```js
  10754. * Color.NAMES.aliceblue // returns 0xF0F8FF
  10755. * ```
  10756. *
  10757. * @param {string} style - The color name.
  10758. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10759. * @return {Color} A reference to this color.
  10760. */
  10761. setColorName( style, colorSpace = SRGBColorSpace ) {
  10762. // color keywords
  10763. const hex = _colorKeywords[ style.toLowerCase() ];
  10764. if ( hex !== undefined ) {
  10765. // red
  10766. this.setHex( hex, colorSpace );
  10767. } else {
  10768. // unknown color
  10769. warn( 'Color: Unknown color ' + style );
  10770. }
  10771. return this;
  10772. }
  10773. /**
  10774. * Returns a new color with copied values from this instance.
  10775. *
  10776. * @return {Color} A clone of this instance.
  10777. */
  10778. clone() {
  10779. return new this.constructor( this.r, this.g, this.b );
  10780. }
  10781. /**
  10782. * Copies the values of the given color to this instance.
  10783. *
  10784. * @param {Color} color - The color to copy.
  10785. * @return {Color} A reference to this color.
  10786. */
  10787. copy( color ) {
  10788. this.r = color.r;
  10789. this.g = color.g;
  10790. this.b = color.b;
  10791. return this;
  10792. }
  10793. /**
  10794. * Copies the given color into this color, and then converts this color from
  10795. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10796. *
  10797. * @param {Color} color - The color to copy/convert.
  10798. * @return {Color} A reference to this color.
  10799. */
  10800. copySRGBToLinear( color ) {
  10801. this.r = SRGBToLinear( color.r );
  10802. this.g = SRGBToLinear( color.g );
  10803. this.b = SRGBToLinear( color.b );
  10804. return this;
  10805. }
  10806. /**
  10807. * Copies the given color into this color, and then converts this color from
  10808. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10809. *
  10810. * @param {Color} color - The color to copy/convert.
  10811. * @return {Color} A reference to this color.
  10812. */
  10813. copyLinearToSRGB( color ) {
  10814. this.r = LinearToSRGB( color.r );
  10815. this.g = LinearToSRGB( color.g );
  10816. this.b = LinearToSRGB( color.b );
  10817. return this;
  10818. }
  10819. /**
  10820. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10821. *
  10822. * @return {Color} A reference to this color.
  10823. */
  10824. convertSRGBToLinear() {
  10825. this.copySRGBToLinear( this );
  10826. return this;
  10827. }
  10828. /**
  10829. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10830. *
  10831. * @return {Color} A reference to this color.
  10832. */
  10833. convertLinearToSRGB() {
  10834. this.copyLinearToSRGB( this );
  10835. return this;
  10836. }
  10837. /**
  10838. * Returns the hexadecimal value of this color.
  10839. *
  10840. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10841. * @return {number} The hexadecimal value.
  10842. */
  10843. getHex( colorSpace = SRGBColorSpace ) {
  10844. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10845. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  10846. }
  10847. /**
  10848. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  10849. *
  10850. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10851. * @return {string} The hexadecimal value as a string.
  10852. */
  10853. getHexString( colorSpace = SRGBColorSpace ) {
  10854. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  10855. }
  10856. /**
  10857. * Converts the colors RGB values into the HSL format and stores them into the
  10858. * given target object.
  10859. *
  10860. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  10861. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10862. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  10863. */
  10864. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  10865. // h,s,l ranges are in 0.0 - 1.0
  10866. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10867. const r = _color.r, g = _color.g, b = _color.b;
  10868. const max = Math.max( r, g, b );
  10869. const min = Math.min( r, g, b );
  10870. let hue, saturation;
  10871. const lightness = ( min + max ) / 2.0;
  10872. if ( min === max ) {
  10873. hue = 0;
  10874. saturation = 0;
  10875. } else {
  10876. const delta = max - min;
  10877. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10878. switch ( max ) {
  10879. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10880. case g: hue = ( b - r ) / delta + 2; break;
  10881. case b: hue = ( r - g ) / delta + 4; break;
  10882. }
  10883. hue /= 6;
  10884. }
  10885. target.h = hue;
  10886. target.s = saturation;
  10887. target.l = lightness;
  10888. return target;
  10889. }
  10890. /**
  10891. * Returns the RGB values of this color and stores them into the given target object.
  10892. *
  10893. * @param {Color} target - The target color that is used to store the method's result.
  10894. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10895. * @return {Color} The RGB representation of this color.
  10896. */
  10897. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  10898. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10899. target.r = _color.r;
  10900. target.g = _color.g;
  10901. target.b = _color.b;
  10902. return target;
  10903. }
  10904. /**
  10905. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  10906. *
  10907. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10908. * @return {string} The CSS representation of this color.
  10909. */
  10910. getStyle( colorSpace = SRGBColorSpace ) {
  10911. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10912. const r = _color.r, g = _color.g, b = _color.b;
  10913. if ( colorSpace !== SRGBColorSpace ) {
  10914. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  10915. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  10916. }
  10917. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  10918. }
  10919. /**
  10920. * Adds the given HSL values to this color's values.
  10921. * Internally, this converts the color's RGB values to HSL, adds HSL
  10922. * and then converts the color back to RGB.
  10923. *
  10924. * @param {number} h - Hue value between `0.0` and `1.0`.
  10925. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10926. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10927. * @return {Color} A reference to this color.
  10928. */
  10929. offsetHSL( h, s, l ) {
  10930. this.getHSL( _hslA );
  10931. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  10932. }
  10933. /**
  10934. * Adds the RGB values of the given color to the RGB values of this color.
  10935. *
  10936. * @param {Color} color - The color to add.
  10937. * @return {Color} A reference to this color.
  10938. */
  10939. add( color ) {
  10940. this.r += color.r;
  10941. this.g += color.g;
  10942. this.b += color.b;
  10943. return this;
  10944. }
  10945. /**
  10946. * Adds the RGB values of the given colors and stores the result in this instance.
  10947. *
  10948. * @param {Color} color1 - The first color.
  10949. * @param {Color} color2 - The second color.
  10950. * @return {Color} A reference to this color.
  10951. */
  10952. addColors( color1, color2 ) {
  10953. this.r = color1.r + color2.r;
  10954. this.g = color1.g + color2.g;
  10955. this.b = color1.b + color2.b;
  10956. return this;
  10957. }
  10958. /**
  10959. * Adds the given scalar value to the RGB values of this color.
  10960. *
  10961. * @param {number} s - The scalar to add.
  10962. * @return {Color} A reference to this color.
  10963. */
  10964. addScalar( s ) {
  10965. this.r += s;
  10966. this.g += s;
  10967. this.b += s;
  10968. return this;
  10969. }
  10970. /**
  10971. * Subtracts the RGB values of the given color from the RGB values of this color.
  10972. *
  10973. * @param {Color} color - The color to subtract.
  10974. * @return {Color} A reference to this color.
  10975. */
  10976. sub( color ) {
  10977. this.r = Math.max( 0, this.r - color.r );
  10978. this.g = Math.max( 0, this.g - color.g );
  10979. this.b = Math.max( 0, this.b - color.b );
  10980. return this;
  10981. }
  10982. /**
  10983. * Multiplies the RGB values of the given color with the RGB values of this color.
  10984. *
  10985. * @param {Color} color - The color to multiply.
  10986. * @return {Color} A reference to this color.
  10987. */
  10988. multiply( color ) {
  10989. this.r *= color.r;
  10990. this.g *= color.g;
  10991. this.b *= color.b;
  10992. return this;
  10993. }
  10994. /**
  10995. * Multiplies the given scalar value with the RGB values of this color.
  10996. *
  10997. * @param {number} s - The scalar to multiply.
  10998. * @return {Color} A reference to this color.
  10999. */
  11000. multiplyScalar( s ) {
  11001. this.r *= s;
  11002. this.g *= s;
  11003. this.b *= s;
  11004. return this;
  11005. }
  11006. /**
  11007. * Linearly interpolates this color's RGB values toward the RGB values of the
  11008. * given color. The alpha argument can be thought of as the ratio between
  11009. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11010. *
  11011. * @param {Color} color - The color to converge on.
  11012. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11013. * @return {Color} A reference to this color.
  11014. */
  11015. lerp( color, alpha ) {
  11016. this.r += ( color.r - this.r ) * alpha;
  11017. this.g += ( color.g - this.g ) * alpha;
  11018. this.b += ( color.b - this.b ) * alpha;
  11019. return this;
  11020. }
  11021. /**
  11022. * Linearly interpolates between the given colors and stores the result in this instance.
  11023. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11024. * is the first and `1.0` is the second color.
  11025. *
  11026. * @param {Color} color1 - The first color.
  11027. * @param {Color} color2 - The second color.
  11028. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11029. * @return {Color} A reference to this color.
  11030. */
  11031. lerpColors( color1, color2, alpha ) {
  11032. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11033. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11034. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11035. return this;
  11036. }
  11037. /**
  11038. * Linearly interpolates this color's HSL values toward the HSL values of the
  11039. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11040. * from one color to the other, but instead going through all the hues in between
  11041. * those two colors. The alpha argument can be thought of as the ratio between
  11042. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11043. *
  11044. * @param {Color} color - The color to converge on.
  11045. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11046. * @return {Color} A reference to this color.
  11047. */
  11048. lerpHSL( color, alpha ) {
  11049. this.getHSL( _hslA );
  11050. color.getHSL( _hslB );
  11051. const h = lerp( _hslA.h, _hslB.h, alpha );
  11052. const s = lerp( _hslA.s, _hslB.s, alpha );
  11053. const l = lerp( _hslA.l, _hslB.l, alpha );
  11054. this.setHSL( h, s, l );
  11055. return this;
  11056. }
  11057. /**
  11058. * Sets the color's RGB components from the given 3D vector.
  11059. *
  11060. * @param {Vector3} v - The vector to set.
  11061. * @return {Color} A reference to this color.
  11062. */
  11063. setFromVector3( v ) {
  11064. this.r = v.x;
  11065. this.g = v.y;
  11066. this.b = v.z;
  11067. return this;
  11068. }
  11069. /**
  11070. * Transforms this color with the given 3x3 matrix.
  11071. *
  11072. * @param {Matrix3} m - The matrix.
  11073. * @return {Color} A reference to this color.
  11074. */
  11075. applyMatrix3( m ) {
  11076. const r = this.r, g = this.g, b = this.b;
  11077. const e = m.elements;
  11078. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11079. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11080. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11081. return this;
  11082. }
  11083. /**
  11084. * Returns `true` if this color is equal with the given one.
  11085. *
  11086. * @param {Color} c - The color to test for equality.
  11087. * @return {boolean} Whether this bounding color is equal with the given one.
  11088. */
  11089. equals( c ) {
  11090. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11091. }
  11092. /**
  11093. * Sets this color's RGB components from the given array.
  11094. *
  11095. * @param {Array<number>} array - An array holding the RGB values.
  11096. * @param {number} [offset=0] - The offset into the array.
  11097. * @return {Color} A reference to this color.
  11098. */
  11099. fromArray( array, offset = 0 ) {
  11100. this.r = array[ offset ];
  11101. this.g = array[ offset + 1 ];
  11102. this.b = array[ offset + 2 ];
  11103. return this;
  11104. }
  11105. /**
  11106. * Writes the RGB components of this color to the given array. If no array is provided,
  11107. * the method returns a new instance.
  11108. *
  11109. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11110. * @param {number} [offset=0] - Index of the first element in the array.
  11111. * @return {Array<number>} The color components.
  11112. */
  11113. toArray( array = [], offset = 0 ) {
  11114. array[ offset ] = this.r;
  11115. array[ offset + 1 ] = this.g;
  11116. array[ offset + 2 ] = this.b;
  11117. return array;
  11118. }
  11119. /**
  11120. * Sets the components of this color from the given buffer attribute.
  11121. *
  11122. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  11123. * @param {number} index - The index into the attribute.
  11124. * @return {Color} A reference to this color.
  11125. */
  11126. fromBufferAttribute( attribute, index ) {
  11127. this.r = attribute.getX( index );
  11128. this.g = attribute.getY( index );
  11129. this.b = attribute.getZ( index );
  11130. return this;
  11131. }
  11132. /**
  11133. * This methods defines the serialization result of this class. Returns the color
  11134. * as a hexadecimal value.
  11135. *
  11136. * @return {number} The hexadecimal value.
  11137. */
  11138. toJSON() {
  11139. return this.getHex();
  11140. }
  11141. *[ Symbol.iterator ]() {
  11142. yield this.r;
  11143. yield this.g;
  11144. yield this.b;
  11145. }
  11146. }
  11147. const _color = /*@__PURE__*/ new Color();
  11148. /**
  11149. * A dictionary with X11 color names.
  11150. *
  11151. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  11152. *
  11153. * @static
  11154. * @type {Object}
  11155. */
  11156. Color.NAMES = _colorKeywords;
  11157. /**
  11158. * This class can be used to define an exponential squared fog,
  11159. * which gives a clear view near the camera and a faster than exponentially
  11160. * densening fog farther from the camera.
  11161. *
  11162. * ```js
  11163. * const scene = new THREE.Scene();
  11164. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  11165. * ```
  11166. */
  11167. class FogExp2 {
  11168. /**
  11169. * Constructs a new fog.
  11170. *
  11171. * @param {number|Color} color - The fog's color.
  11172. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  11173. */
  11174. constructor( color, density = 0.00025 ) {
  11175. /**
  11176. * This flag can be used for type testing.
  11177. *
  11178. * @type {boolean}
  11179. * @readonly
  11180. * @default true
  11181. */
  11182. this.isFogExp2 = true;
  11183. /**
  11184. * The name of the fog.
  11185. *
  11186. * @type {string}
  11187. */
  11188. this.name = '';
  11189. /**
  11190. * The fog's color.
  11191. *
  11192. * @type {Color}
  11193. */
  11194. this.color = new Color( color );
  11195. /**
  11196. * Defines how fast the fog will grow dense.
  11197. *
  11198. * @type {number}
  11199. * @default 0.00025
  11200. */
  11201. this.density = density;
  11202. }
  11203. /**
  11204. * Returns a new fog with copied values from this instance.
  11205. *
  11206. * @return {FogExp2} A clone of this instance.
  11207. */
  11208. clone() {
  11209. return new FogExp2( this.color, this.density );
  11210. }
  11211. /**
  11212. * Serializes the fog into JSON.
  11213. *
  11214. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11215. * @return {Object} A JSON object representing the serialized fog
  11216. */
  11217. toJSON( /* meta */ ) {
  11218. return {
  11219. type: 'FogExp2',
  11220. name: this.name,
  11221. color: this.color.getHex(),
  11222. density: this.density
  11223. };
  11224. }
  11225. }
  11226. /**
  11227. * This class can be used to define a linear fog that grows linearly denser
  11228. * with the distance.
  11229. *
  11230. * ```js
  11231. * const scene = new THREE.Scene();
  11232. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  11233. * ```
  11234. */
  11235. class Fog {
  11236. /**
  11237. * Constructs a new fog.
  11238. *
  11239. * @param {number|Color} color - The fog's color.
  11240. * @param {number} [near=1] - The minimum distance to start applying fog.
  11241. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  11242. */
  11243. constructor( color, near = 1, far = 1000 ) {
  11244. /**
  11245. * This flag can be used for type testing.
  11246. *
  11247. * @type {boolean}
  11248. * @readonly
  11249. * @default true
  11250. */
  11251. this.isFog = true;
  11252. /**
  11253. * The name of the fog.
  11254. *
  11255. * @type {string}
  11256. */
  11257. this.name = '';
  11258. /**
  11259. * The fog's color.
  11260. *
  11261. * @type {Color}
  11262. */
  11263. this.color = new Color( color );
  11264. /**
  11265. * The minimum distance to start applying fog. Objects that are less than
  11266. * `near` units from the active camera won't be affected by fog.
  11267. *
  11268. * @type {number}
  11269. * @default 1
  11270. */
  11271. this.near = near;
  11272. /**
  11273. * The maximum distance at which fog stops being calculated and applied.
  11274. * Objects that are more than `far` units away from the active camera won't
  11275. * be affected by fog.
  11276. *
  11277. * @type {number}
  11278. * @default 1000
  11279. */
  11280. this.far = far;
  11281. }
  11282. /**
  11283. * Returns a new fog with copied values from this instance.
  11284. *
  11285. * @return {Fog} A clone of this instance.
  11286. */
  11287. clone() {
  11288. return new Fog( this.color, this.near, this.far );
  11289. }
  11290. /**
  11291. * Serializes the fog into JSON.
  11292. *
  11293. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11294. * @return {Object} A JSON object representing the serialized fog
  11295. */
  11296. toJSON( /* meta */ ) {
  11297. return {
  11298. type: 'Fog',
  11299. name: this.name,
  11300. color: this.color.getHex(),
  11301. near: this.near,
  11302. far: this.far
  11303. };
  11304. }
  11305. }
  11306. /**
  11307. * Scenes allow you to set up what is to be rendered and where by three.js.
  11308. * This is where you place 3D objects like meshes, lines or lights.
  11309. *
  11310. * @augments Object3D
  11311. */
  11312. class Scene extends Object3D {
  11313. /**
  11314. * Constructs a new scene.
  11315. */
  11316. constructor() {
  11317. super();
  11318. /**
  11319. * This flag can be used for type testing.
  11320. *
  11321. * @type {boolean}
  11322. * @readonly
  11323. * @default true
  11324. */
  11325. this.isScene = true;
  11326. this.type = 'Scene';
  11327. /**
  11328. * Defines the background of the scene. Valid inputs are:
  11329. *
  11330. * - A color for defining a uniform colored background.
  11331. * - A texture for defining a (flat) textured background.
  11332. * - Cube textures or equirectangular textures for defining a skybox.
  11333. *
  11334. * @type {?(Color|Texture)}
  11335. * @default null
  11336. */
  11337. this.background = null;
  11338. /**
  11339. * Sets the environment map for all physical materials in the scene. However,
  11340. * it's not possible to overwrite an existing texture assigned to the `envMap`
  11341. * material property.
  11342. *
  11343. * @type {?Texture}
  11344. * @default null
  11345. */
  11346. this.environment = null;
  11347. /**
  11348. * A fog instance defining the type of fog that affects everything
  11349. * rendered in the scene.
  11350. *
  11351. * @type {?(Fog|FogExp2)}
  11352. * @default null
  11353. */
  11354. this.fog = null;
  11355. /**
  11356. * Sets the blurriness of the background. Only influences environment maps
  11357. * assigned to {@link Scene#background}. Valid input is a float between `0`
  11358. * and `1`.
  11359. *
  11360. * @type {number}
  11361. * @default 0
  11362. */
  11363. this.backgroundBlurriness = 0;
  11364. /**
  11365. * Attenuates the color of the background. Only applies to background textures.
  11366. *
  11367. * @type {number}
  11368. * @default 1
  11369. */
  11370. this.backgroundIntensity = 1;
  11371. /**
  11372. * The rotation of the background in radians. Only influences environment maps
  11373. * assigned to {@link Scene#background}.
  11374. *
  11375. * @type {Euler}
  11376. * @default (0,0,0)
  11377. */
  11378. this.backgroundRotation = new Euler();
  11379. /**
  11380. * Attenuates the color of the environment. Only influences environment maps
  11381. * assigned to {@link Scene#environment}.
  11382. *
  11383. * @type {number}
  11384. * @default 1
  11385. */
  11386. this.environmentIntensity = 1;
  11387. /**
  11388. * The rotation of the environment map in radians. Only influences physical materials
  11389. * in the scene when {@link Scene#environment} is used.
  11390. *
  11391. * @type {Euler}
  11392. * @default (0,0,0)
  11393. */
  11394. this.environmentRotation = new Euler();
  11395. /**
  11396. * Forces everything in the scene to be rendered with the defined material. It is possible
  11397. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  11398. *
  11399. * @type {?Material}
  11400. * @default null
  11401. */
  11402. this.overrideMaterial = null;
  11403. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11404. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11405. }
  11406. }
  11407. copy( source, recursive ) {
  11408. super.copy( source, recursive );
  11409. if ( source.background !== null ) this.background = source.background.clone();
  11410. if ( source.environment !== null ) this.environment = source.environment.clone();
  11411. if ( source.fog !== null ) this.fog = source.fog.clone();
  11412. this.backgroundBlurriness = source.backgroundBlurriness;
  11413. this.backgroundIntensity = source.backgroundIntensity;
  11414. this.backgroundRotation.copy( source.backgroundRotation );
  11415. this.environmentIntensity = source.environmentIntensity;
  11416. this.environmentRotation.copy( source.environmentRotation );
  11417. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11418. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11419. return this;
  11420. }
  11421. toJSON( meta ) {
  11422. const data = super.toJSON( meta );
  11423. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  11424. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  11425. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  11426. data.object.backgroundRotation = this.backgroundRotation.toArray();
  11427. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  11428. data.object.environmentRotation = this.environmentRotation.toArray();
  11429. return data;
  11430. }
  11431. }
  11432. const _v0$3 = /*@__PURE__*/ new Vector3();
  11433. const _v1$5 = /*@__PURE__*/ new Vector3();
  11434. const _v2$4 = /*@__PURE__*/ new Vector3();
  11435. const _v3$2 = /*@__PURE__*/ new Vector3();
  11436. const _vab = /*@__PURE__*/ new Vector3();
  11437. const _vac = /*@__PURE__*/ new Vector3();
  11438. const _vbc = /*@__PURE__*/ new Vector3();
  11439. const _vap = /*@__PURE__*/ new Vector3();
  11440. const _vbp = /*@__PURE__*/ new Vector3();
  11441. const _vcp = /*@__PURE__*/ new Vector3();
  11442. const _v40 = /*@__PURE__*/ new Vector4();
  11443. const _v41 = /*@__PURE__*/ new Vector4();
  11444. const _v42 = /*@__PURE__*/ new Vector4();
  11445. /**
  11446. * A geometric triangle as defined by three vectors representing its three corners.
  11447. */
  11448. class Triangle {
  11449. /**
  11450. * Constructs a new triangle.
  11451. *
  11452. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11453. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11454. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11455. */
  11456. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11457. /**
  11458. * The first corner of the triangle.
  11459. *
  11460. * @type {Vector3}
  11461. */
  11462. this.a = a;
  11463. /**
  11464. * The second corner of the triangle.
  11465. *
  11466. * @type {Vector3}
  11467. */
  11468. this.b = b;
  11469. /**
  11470. * The third corner of the triangle.
  11471. *
  11472. * @type {Vector3}
  11473. */
  11474. this.c = c;
  11475. }
  11476. /**
  11477. * Computes the normal vector of a triangle.
  11478. *
  11479. * @param {Vector3} a - The first corner of the triangle.
  11480. * @param {Vector3} b - The second corner of the triangle.
  11481. * @param {Vector3} c - The third corner of the triangle.
  11482. * @param {Vector3} target - The target vector that is used to store the method's result.
  11483. * @return {Vector3} The triangle's normal.
  11484. */
  11485. static getNormal( a, b, c, target ) {
  11486. target.subVectors( c, b );
  11487. _v0$3.subVectors( a, b );
  11488. target.cross( _v0$3 );
  11489. const targetLengthSq = target.lengthSq();
  11490. if ( targetLengthSq > 0 ) {
  11491. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11492. }
  11493. return target.set( 0, 0, 0 );
  11494. }
  11495. /**
  11496. * Computes a barycentric coordinates from the given vector.
  11497. * Returns `null` if the triangle is degenerate.
  11498. *
  11499. * @param {Vector3} point - A point in 3D space.
  11500. * @param {Vector3} a - The first corner of the triangle.
  11501. * @param {Vector3} b - The second corner of the triangle.
  11502. * @param {Vector3} c - The third corner of the triangle.
  11503. * @param {Vector3} target - The target vector that is used to store the method's result.
  11504. * @return {?Vector3} The barycentric coordinates for the given point
  11505. */
  11506. static getBarycoord( point, a, b, c, target ) {
  11507. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11508. _v0$3.subVectors( c, a );
  11509. _v1$5.subVectors( b, a );
  11510. _v2$4.subVectors( point, a );
  11511. const dot00 = _v0$3.dot( _v0$3 );
  11512. const dot01 = _v0$3.dot( _v1$5 );
  11513. const dot02 = _v0$3.dot( _v2$4 );
  11514. const dot11 = _v1$5.dot( _v1$5 );
  11515. const dot12 = _v1$5.dot( _v2$4 );
  11516. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11517. // collinear or singular triangle
  11518. if ( denom === 0 ) {
  11519. target.set( 0, 0, 0 );
  11520. return null;
  11521. }
  11522. const invDenom = 1 / denom;
  11523. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11524. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11525. // barycentric coordinates must always sum to 1
  11526. return target.set( 1 - u - v, v, u );
  11527. }
  11528. /**
  11529. * Returns `true` if the given point, when projected onto the plane of the
  11530. * triangle, lies within the triangle.
  11531. *
  11532. * @param {Vector3} point - The point in 3D space to test.
  11533. * @param {Vector3} a - The first corner of the triangle.
  11534. * @param {Vector3} b - The second corner of the triangle.
  11535. * @param {Vector3} c - The third corner of the triangle.
  11536. * @return {boolean} Whether the given point, when projected onto the plane of the
  11537. * triangle, lies within the triangle or not.
  11538. */
  11539. static containsPoint( point, a, b, c ) {
  11540. // if the triangle is degenerate then we can't contain a point
  11541. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11542. return false;
  11543. }
  11544. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11545. }
  11546. /**
  11547. * Computes the value barycentrically interpolated for the given point on the
  11548. * triangle. Returns `null` if the triangle is degenerate.
  11549. *
  11550. * @param {Vector3} point - Position of interpolated point.
  11551. * @param {Vector3} p1 - The first corner of the triangle.
  11552. * @param {Vector3} p2 - The second corner of the triangle.
  11553. * @param {Vector3} p3 - The third corner of the triangle.
  11554. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11555. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11556. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11557. * @param {Vector3} target - The target vector that is used to store the method's result.
  11558. * @return {?Vector3} The interpolated value.
  11559. */
  11560. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11561. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11562. target.x = 0;
  11563. target.y = 0;
  11564. if ( 'z' in target ) target.z = 0;
  11565. if ( 'w' in target ) target.w = 0;
  11566. return null;
  11567. }
  11568. target.setScalar( 0 );
  11569. target.addScaledVector( v1, _v3$2.x );
  11570. target.addScaledVector( v2, _v3$2.y );
  11571. target.addScaledVector( v3, _v3$2.z );
  11572. return target;
  11573. }
  11574. /**
  11575. * Computes the value barycentrically interpolated for the given attribute and indices.
  11576. *
  11577. * @param {BufferAttribute} attr - The attribute to interpolate.
  11578. * @param {number} i1 - Index of first vertex.
  11579. * @param {number} i2 - Index of second vertex.
  11580. * @param {number} i3 - Index of third vertex.
  11581. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11582. * @param {Vector3} target - The target vector that is used to store the method's result.
  11583. * @return {Vector3} The interpolated attribute value.
  11584. */
  11585. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11586. _v40.setScalar( 0 );
  11587. _v41.setScalar( 0 );
  11588. _v42.setScalar( 0 );
  11589. _v40.fromBufferAttribute( attr, i1 );
  11590. _v41.fromBufferAttribute( attr, i2 );
  11591. _v42.fromBufferAttribute( attr, i3 );
  11592. target.setScalar( 0 );
  11593. target.addScaledVector( _v40, barycoord.x );
  11594. target.addScaledVector( _v41, barycoord.y );
  11595. target.addScaledVector( _v42, barycoord.z );
  11596. return target;
  11597. }
  11598. /**
  11599. * Returns `true` if the triangle is oriented towards the given direction.
  11600. *
  11601. * @param {Vector3} a - The first corner of the triangle.
  11602. * @param {Vector3} b - The second corner of the triangle.
  11603. * @param {Vector3} c - The third corner of the triangle.
  11604. * @param {Vector3} direction - The (normalized) direction vector.
  11605. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11606. */
  11607. static isFrontFacing( a, b, c, direction ) {
  11608. _v0$3.subVectors( c, b );
  11609. _v1$5.subVectors( a, b );
  11610. // strictly front facing
  11611. return ( _v0$3.cross( _v1$5 ).dot( direction ) < 0 ) ? true : false;
  11612. }
  11613. /**
  11614. * Sets the triangle's vertices by copying the given values.
  11615. *
  11616. * @param {Vector3} a - The first corner of the triangle.
  11617. * @param {Vector3} b - The second corner of the triangle.
  11618. * @param {Vector3} c - The third corner of the triangle.
  11619. * @return {Triangle} A reference to this triangle.
  11620. */
  11621. set( a, b, c ) {
  11622. this.a.copy( a );
  11623. this.b.copy( b );
  11624. this.c.copy( c );
  11625. return this;
  11626. }
  11627. /**
  11628. * Sets the triangle's vertices by copying the given array values.
  11629. *
  11630. * @param {Array<Vector3>} points - An array with 3D points.
  11631. * @param {number} i0 - The array index representing the first corner of the triangle.
  11632. * @param {number} i1 - The array index representing the second corner of the triangle.
  11633. * @param {number} i2 - The array index representing the third corner of the triangle.
  11634. * @return {Triangle} A reference to this triangle.
  11635. */
  11636. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11637. this.a.copy( points[ i0 ] );
  11638. this.b.copy( points[ i1 ] );
  11639. this.c.copy( points[ i2 ] );
  11640. return this;
  11641. }
  11642. /**
  11643. * Sets the triangle's vertices by copying the given attribute values.
  11644. *
  11645. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11646. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11647. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11648. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11649. * @return {Triangle} A reference to this triangle.
  11650. */
  11651. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11652. this.a.fromBufferAttribute( attribute, i0 );
  11653. this.b.fromBufferAttribute( attribute, i1 );
  11654. this.c.fromBufferAttribute( attribute, i2 );
  11655. return this;
  11656. }
  11657. /**
  11658. * Returns a new triangle with copied values from this instance.
  11659. *
  11660. * @return {Triangle} A clone of this instance.
  11661. */
  11662. clone() {
  11663. return new this.constructor().copy( this );
  11664. }
  11665. /**
  11666. * Copies the values of the given triangle to this instance.
  11667. *
  11668. * @param {Triangle} triangle - The triangle to copy.
  11669. * @return {Triangle} A reference to this triangle.
  11670. */
  11671. copy( triangle ) {
  11672. this.a.copy( triangle.a );
  11673. this.b.copy( triangle.b );
  11674. this.c.copy( triangle.c );
  11675. return this;
  11676. }
  11677. /**
  11678. * Computes the area of the triangle.
  11679. *
  11680. * @return {number} The triangle's area.
  11681. */
  11682. getArea() {
  11683. _v0$3.subVectors( this.c, this.b );
  11684. _v1$5.subVectors( this.a, this.b );
  11685. return _v0$3.cross( _v1$5 ).length() * 0.5;
  11686. }
  11687. /**
  11688. * Computes the midpoint of the triangle.
  11689. *
  11690. * @param {Vector3} target - The target vector that is used to store the method's result.
  11691. * @return {Vector3} The triangle's midpoint.
  11692. */
  11693. getMidpoint( target ) {
  11694. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11695. }
  11696. /**
  11697. * Computes the normal of the triangle.
  11698. *
  11699. * @param {Vector3} target - The target vector that is used to store the method's result.
  11700. * @return {Vector3} The triangle's normal.
  11701. */
  11702. getNormal( target ) {
  11703. return Triangle.getNormal( this.a, this.b, this.c, target );
  11704. }
  11705. /**
  11706. * Computes a plane the triangle lies within.
  11707. *
  11708. * @param {Plane} target - The target vector that is used to store the method's result.
  11709. * @return {Plane} The plane the triangle lies within.
  11710. */
  11711. getPlane( target ) {
  11712. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11713. }
  11714. /**
  11715. * Computes a barycentric coordinates from the given vector.
  11716. * Returns `null` if the triangle is degenerate.
  11717. *
  11718. * @param {Vector3} point - A point in 3D space.
  11719. * @param {Vector3} target - The target vector that is used to store the method's result.
  11720. * @return {?Vector3} The barycentric coordinates for the given point
  11721. */
  11722. getBarycoord( point, target ) {
  11723. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11724. }
  11725. /**
  11726. * Computes the value barycentrically interpolated for the given point on the
  11727. * triangle. Returns `null` if the triangle is degenerate.
  11728. *
  11729. * @param {Vector3} point - Position of interpolated point.
  11730. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11731. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11732. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11733. * @param {Vector3} target - The target vector that is used to store the method's result.
  11734. * @return {?Vector3} The interpolated value.
  11735. */
  11736. getInterpolation( point, v1, v2, v3, target ) {
  11737. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11738. }
  11739. /**
  11740. * Returns `true` if the given point, when projected onto the plane of the
  11741. * triangle, lies within the triangle.
  11742. *
  11743. * @param {Vector3} point - The point in 3D space to test.
  11744. * @return {boolean} Whether the given point, when projected onto the plane of the
  11745. * triangle, lies within the triangle or not.
  11746. */
  11747. containsPoint( point ) {
  11748. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11749. }
  11750. /**
  11751. * Returns `true` if the triangle is oriented towards the given direction.
  11752. *
  11753. * @param {Vector3} direction - The (normalized) direction vector.
  11754. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11755. */
  11756. isFrontFacing( direction ) {
  11757. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11758. }
  11759. /**
  11760. * Returns `true` if this triangle intersects with the given box.
  11761. *
  11762. * @param {Box3} box - The box to intersect.
  11763. * @return {boolean} Whether this triangle intersects with the given box or not.
  11764. */
  11765. intersectsBox( box ) {
  11766. return box.intersectsTriangle( this );
  11767. }
  11768. /**
  11769. * Returns the closest point on the triangle to the given point.
  11770. *
  11771. * @param {Vector3} p - The point to compute the closest point for.
  11772. * @param {Vector3} target - The target vector that is used to store the method's result.
  11773. * @return {Vector3} The closest point on the triangle.
  11774. */
  11775. closestPointToPoint( p, target ) {
  11776. const a = this.a, b = this.b, c = this.c;
  11777. let v, w;
  11778. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11779. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11780. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11781. // basically, we're distinguishing which of the voronoi regions of the triangle
  11782. // the point lies in with the minimum amount of redundant computation.
  11783. _vab.subVectors( b, a );
  11784. _vac.subVectors( c, a );
  11785. _vap.subVectors( p, a );
  11786. const d1 = _vab.dot( _vap );
  11787. const d2 = _vac.dot( _vap );
  11788. if ( d1 <= 0 && d2 <= 0 ) {
  11789. // vertex region of A; barycentric coords (1, 0, 0)
  11790. return target.copy( a );
  11791. }
  11792. _vbp.subVectors( p, b );
  11793. const d3 = _vab.dot( _vbp );
  11794. const d4 = _vac.dot( _vbp );
  11795. if ( d3 >= 0 && d4 <= d3 ) {
  11796. // vertex region of B; barycentric coords (0, 1, 0)
  11797. return target.copy( b );
  11798. }
  11799. const vc = d1 * d4 - d3 * d2;
  11800. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11801. v = d1 / ( d1 - d3 );
  11802. // edge region of AB; barycentric coords (1-v, v, 0)
  11803. return target.copy( a ).addScaledVector( _vab, v );
  11804. }
  11805. _vcp.subVectors( p, c );
  11806. const d5 = _vab.dot( _vcp );
  11807. const d6 = _vac.dot( _vcp );
  11808. if ( d6 >= 0 && d5 <= d6 ) {
  11809. // vertex region of C; barycentric coords (0, 0, 1)
  11810. return target.copy( c );
  11811. }
  11812. const vb = d5 * d2 - d1 * d6;
  11813. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11814. w = d2 / ( d2 - d6 );
  11815. // edge region of AC; barycentric coords (1-w, 0, w)
  11816. return target.copy( a ).addScaledVector( _vac, w );
  11817. }
  11818. const va = d3 * d6 - d5 * d4;
  11819. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11820. _vbc.subVectors( c, b );
  11821. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11822. // edge region of BC; barycentric coords (0, 1-w, w)
  11823. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11824. }
  11825. // face region
  11826. const denom = 1 / ( va + vb + vc );
  11827. // u = va * denom
  11828. v = vb * denom;
  11829. w = vc * denom;
  11830. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11831. }
  11832. /**
  11833. * Returns `true` if this triangle is equal with the given one.
  11834. *
  11835. * @param {Triangle} triangle - The triangle to test for equality.
  11836. * @return {boolean} Whether this triangle is equal with the given one.
  11837. */
  11838. equals( triangle ) {
  11839. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11840. }
  11841. }
  11842. /**
  11843. * Represents an axis-aligned bounding box (AABB) in 3D space.
  11844. */
  11845. class Box3 {
  11846. /**
  11847. * Constructs a new bounding box.
  11848. *
  11849. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  11850. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  11851. */
  11852. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  11853. /**
  11854. * This flag can be used for type testing.
  11855. *
  11856. * @type {boolean}
  11857. * @readonly
  11858. * @default true
  11859. */
  11860. this.isBox3 = true;
  11861. /**
  11862. * The lower boundary of the box.
  11863. *
  11864. * @type {Vector3}
  11865. */
  11866. this.min = min;
  11867. /**
  11868. * The upper boundary of the box.
  11869. *
  11870. * @type {Vector3}
  11871. */
  11872. this.max = max;
  11873. }
  11874. /**
  11875. * Sets the lower and upper boundaries of this box.
  11876. * Please note that this method only copies the values from the given objects.
  11877. *
  11878. * @param {Vector3} min - The lower boundary of the box.
  11879. * @param {Vector3} max - The upper boundary of the box.
  11880. * @return {Box3} A reference to this bounding box.
  11881. */
  11882. set( min, max ) {
  11883. this.min.copy( min );
  11884. this.max.copy( max );
  11885. return this;
  11886. }
  11887. /**
  11888. * Sets the upper and lower bounds of this box so it encloses the position data
  11889. * in the given array.
  11890. *
  11891. * @param {Array<number>} array - An array holding 3D position data.
  11892. * @return {Box3} A reference to this bounding box.
  11893. */
  11894. setFromArray( array ) {
  11895. this.makeEmpty();
  11896. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  11897. this.expandByPoint( _vector$b.fromArray( array, i ) );
  11898. }
  11899. return this;
  11900. }
  11901. /**
  11902. * Sets the upper and lower bounds of this box so it encloses the position data
  11903. * in the given buffer attribute.
  11904. *
  11905. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  11906. * @return {Box3} A reference to this bounding box.
  11907. */
  11908. setFromBufferAttribute( attribute ) {
  11909. this.makeEmpty();
  11910. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  11911. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  11912. }
  11913. return this;
  11914. }
  11915. /**
  11916. * Sets the upper and lower bounds of this box so it encloses the position data
  11917. * in the given array.
  11918. *
  11919. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  11920. * @return {Box3} A reference to this bounding box.
  11921. */
  11922. setFromPoints( points ) {
  11923. this.makeEmpty();
  11924. for ( let i = 0, il = points.length; i < il; i ++ ) {
  11925. this.expandByPoint( points[ i ] );
  11926. }
  11927. return this;
  11928. }
  11929. /**
  11930. * Centers this box on the given center vector and sets this box's width, height and
  11931. * depth to the given size values.
  11932. *
  11933. * @param {Vector3} center - The center of the box.
  11934. * @param {Vector3} size - The x, y and z dimensions of the box.
  11935. * @return {Box3} A reference to this bounding box.
  11936. */
  11937. setFromCenterAndSize( center, size ) {
  11938. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  11939. this.min.copy( center ).sub( halfSize );
  11940. this.max.copy( center ).add( halfSize );
  11941. return this;
  11942. }
  11943. /**
  11944. * Computes the world-axis-aligned bounding box for the given 3D object
  11945. * (including its children), accounting for the object's, and children's,
  11946. * world transforms. The function may result in a larger box than strictly necessary.
  11947. *
  11948. * @param {Object3D} object - The 3D object to compute the bounding box for.
  11949. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  11950. * world-axis-aligned bounding box at the expense of more computation.
  11951. * @return {Box3} A reference to this bounding box.
  11952. */
  11953. setFromObject( object, precise = false ) {
  11954. this.makeEmpty();
  11955. return this.expandByObject( object, precise );
  11956. }
  11957. /**
  11958. * Returns a new box with copied values from this instance.
  11959. *
  11960. * @return {Box3} A clone of this instance.
  11961. */
  11962. clone() {
  11963. return new this.constructor().copy( this );
  11964. }
  11965. /**
  11966. * Copies the values of the given box to this instance.
  11967. *
  11968. * @param {Box3} box - The box to copy.
  11969. * @return {Box3} A reference to this bounding box.
  11970. */
  11971. copy( box ) {
  11972. this.min.copy( box.min );
  11973. this.max.copy( box.max );
  11974. return this;
  11975. }
  11976. /**
  11977. * Makes this box empty which means in encloses a zero space in 3D.
  11978. *
  11979. * @return {Box3} A reference to this bounding box.
  11980. */
  11981. makeEmpty() {
  11982. this.min.x = this.min.y = this.min.z = + Infinity;
  11983. this.max.x = this.max.y = this.max.z = - Infinity;
  11984. return this;
  11985. }
  11986. /**
  11987. * Returns true if this box includes zero points within its bounds.
  11988. * Note that a box with equal lower and upper bounds still includes one
  11989. * point, the one both bounds share.
  11990. *
  11991. * @return {boolean} Whether this box is empty or not.
  11992. */
  11993. isEmpty() {
  11994. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  11995. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  11996. }
  11997. /**
  11998. * Returns the center point of this box.
  11999. *
  12000. * @param {Vector3} target - The target vector that is used to store the method's result.
  12001. * @return {Vector3} The center point.
  12002. */
  12003. getCenter( target ) {
  12004. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  12005. }
  12006. /**
  12007. * Returns the dimensions of this box.
  12008. *
  12009. * @param {Vector3} target - The target vector that is used to store the method's result.
  12010. * @return {Vector3} The size.
  12011. */
  12012. getSize( target ) {
  12013. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  12014. }
  12015. /**
  12016. * Expands the boundaries of this box to include the given point.
  12017. *
  12018. * @param {Vector3} point - The point that should be included by the bounding box.
  12019. * @return {Box3} A reference to this bounding box.
  12020. */
  12021. expandByPoint( point ) {
  12022. this.min.min( point );
  12023. this.max.max( point );
  12024. return this;
  12025. }
  12026. /**
  12027. * Expands this box equilaterally by the given vector. The width of this
  12028. * box will be expanded by the x component of the vector in both
  12029. * directions. The height of this box will be expanded by the y component of
  12030. * the vector in both directions. The depth of this box will be
  12031. * expanded by the z component of the vector in both directions.
  12032. *
  12033. * @param {Vector3} vector - The vector that should expand the bounding box.
  12034. * @return {Box3} A reference to this bounding box.
  12035. */
  12036. expandByVector( vector ) {
  12037. this.min.sub( vector );
  12038. this.max.add( vector );
  12039. return this;
  12040. }
  12041. /**
  12042. * Expands each dimension of the box by the given scalar. If negative, the
  12043. * dimensions of the box will be contracted.
  12044. *
  12045. * @param {number} scalar - The scalar value that should expand the bounding box.
  12046. * @return {Box3} A reference to this bounding box.
  12047. */
  12048. expandByScalar( scalar ) {
  12049. this.min.addScalar( - scalar );
  12050. this.max.addScalar( scalar );
  12051. return this;
  12052. }
  12053. /**
  12054. * Expands the boundaries of this box to include the given 3D object and
  12055. * its children, accounting for the object's, and children's, world
  12056. * transforms. The function may result in a larger box than strictly
  12057. * necessary (unless the precise parameter is set to true).
  12058. *
  12059. * @param {Object3D} object - The 3D object that should expand the bounding box.
  12060. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  12061. * as little as necessary at the expense of more computation.
  12062. * @return {Box3} A reference to this bounding box.
  12063. */
  12064. expandByObject( object, precise = false ) {
  12065. // Computes the world-axis-aligned bounding box of an object (including its children),
  12066. // accounting for both the object's, and children's, world transforms
  12067. object.updateWorldMatrix( false, false );
  12068. const geometry = object.geometry;
  12069. if ( geometry !== undefined ) {
  12070. const positionAttribute = geometry.getAttribute( 'position' );
  12071. // precise AABB computation based on vertex data requires at least a position attribute.
  12072. // instancing isn't supported so far and uses the normal (conservative) code path.
  12073. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  12074. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  12075. if ( object.isMesh === true ) {
  12076. object.getVertexPosition( i, _vector$b );
  12077. } else {
  12078. _vector$b.fromBufferAttribute( positionAttribute, i );
  12079. }
  12080. _vector$b.applyMatrix4( object.matrixWorld );
  12081. this.expandByPoint( _vector$b );
  12082. }
  12083. } else {
  12084. if ( object.boundingBox !== undefined ) {
  12085. // object-level bounding box
  12086. if ( object.boundingBox === null ) {
  12087. object.computeBoundingBox();
  12088. }
  12089. _box$4.copy( object.boundingBox );
  12090. } else {
  12091. // geometry-level bounding box
  12092. if ( geometry.boundingBox === null ) {
  12093. geometry.computeBoundingBox();
  12094. }
  12095. _box$4.copy( geometry.boundingBox );
  12096. }
  12097. _box$4.applyMatrix4( object.matrixWorld );
  12098. this.union( _box$4 );
  12099. }
  12100. }
  12101. const children = object.children;
  12102. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12103. this.expandByObject( children[ i ], precise );
  12104. }
  12105. return this;
  12106. }
  12107. /**
  12108. * Returns `true` if the given point lies within or on the boundaries of this box.
  12109. *
  12110. * @param {Vector3} point - The point to test.
  12111. * @return {boolean} Whether the bounding box contains the given point or not.
  12112. */
  12113. containsPoint( point ) {
  12114. return point.x >= this.min.x && point.x <= this.max.x &&
  12115. point.y >= this.min.y && point.y <= this.max.y &&
  12116. point.z >= this.min.z && point.z <= this.max.z;
  12117. }
  12118. /**
  12119. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  12120. * If this box and the given one are identical, this function also returns `true`.
  12121. *
  12122. * @param {Box3} box - The bounding box to test.
  12123. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  12124. */
  12125. containsBox( box ) {
  12126. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  12127. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  12128. this.min.z <= box.min.z && box.max.z <= this.max.z;
  12129. }
  12130. /**
  12131. * Returns a point as a proportion of this box's width, height and depth.
  12132. *
  12133. * @param {Vector3} point - A point in 3D space.
  12134. * @param {Vector3} target - The target vector that is used to store the method's result.
  12135. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  12136. */
  12137. getParameter( point, target ) {
  12138. // This can potentially have a divide by zero if the box
  12139. // has a size dimension of 0.
  12140. return target.set(
  12141. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  12142. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  12143. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  12144. );
  12145. }
  12146. /**
  12147. * Returns `true` if the given bounding box intersects with this bounding box.
  12148. *
  12149. * @param {Box3} box - The bounding box to test.
  12150. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  12151. */
  12152. intersectsBox( box ) {
  12153. // using 6 splitting planes to rule out intersections.
  12154. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  12155. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  12156. box.max.z >= this.min.z && box.min.z <= this.max.z;
  12157. }
  12158. /**
  12159. * Returns `true` if the given bounding sphere intersects with this bounding box.
  12160. *
  12161. * @param {Sphere} sphere - The bounding sphere to test.
  12162. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  12163. */
  12164. intersectsSphere( sphere ) {
  12165. // Find the point on the AABB closest to the sphere center.
  12166. this.clampPoint( sphere.center, _vector$b );
  12167. // If that point is inside the sphere, the AABB and sphere intersect.
  12168. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  12169. }
  12170. /**
  12171. * Returns `true` if the given plane intersects with this bounding box.
  12172. *
  12173. * @param {Plane} plane - The plane to test.
  12174. * @return {boolean} Whether the given plane intersects with this bounding box.
  12175. */
  12176. intersectsPlane( plane ) {
  12177. // We compute the minimum and maximum dot product values. If those values
  12178. // are on the same side (back or front) of the plane, then there is no intersection.
  12179. let min, max;
  12180. if ( plane.normal.x > 0 ) {
  12181. min = plane.normal.x * this.min.x;
  12182. max = plane.normal.x * this.max.x;
  12183. } else {
  12184. min = plane.normal.x * this.max.x;
  12185. max = plane.normal.x * this.min.x;
  12186. }
  12187. if ( plane.normal.y > 0 ) {
  12188. min += plane.normal.y * this.min.y;
  12189. max += plane.normal.y * this.max.y;
  12190. } else {
  12191. min += plane.normal.y * this.max.y;
  12192. max += plane.normal.y * this.min.y;
  12193. }
  12194. if ( plane.normal.z > 0 ) {
  12195. min += plane.normal.z * this.min.z;
  12196. max += plane.normal.z * this.max.z;
  12197. } else {
  12198. min += plane.normal.z * this.max.z;
  12199. max += plane.normal.z * this.min.z;
  12200. }
  12201. return ( min <= - plane.constant && max >= - plane.constant );
  12202. }
  12203. /**
  12204. * Returns `true` if the given triangle intersects with this bounding box.
  12205. *
  12206. * @param {Triangle} triangle - The triangle to test.
  12207. * @return {boolean} Whether the given triangle intersects with this bounding box.
  12208. */
  12209. intersectsTriangle( triangle ) {
  12210. if ( this.isEmpty() ) {
  12211. return false;
  12212. }
  12213. // compute box center and extents
  12214. this.getCenter( _center );
  12215. _extents.subVectors( this.max, _center );
  12216. // translate triangle to aabb origin
  12217. _v0$2.subVectors( triangle.a, _center );
  12218. _v1$4.subVectors( triangle.b, _center );
  12219. _v2$3.subVectors( triangle.c, _center );
  12220. // compute edge vectors for triangle
  12221. _f0.subVectors( _v1$4, _v0$2 );
  12222. _f1.subVectors( _v2$3, _v1$4 );
  12223. _f2.subVectors( _v0$2, _v2$3 );
  12224. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  12225. // 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
  12226. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  12227. let axes = [
  12228. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  12229. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  12230. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  12231. ];
  12232. if ( ! satForAxes( axes, _v0$2, _v1$4, _v2$3, _extents ) ) {
  12233. return false;
  12234. }
  12235. // test 3 face normals from the aabb
  12236. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  12237. if ( ! satForAxes( axes, _v0$2, _v1$4, _v2$3, _extents ) ) {
  12238. return false;
  12239. }
  12240. // finally testing the face normal of the triangle
  12241. // use already existing triangle edge vectors here
  12242. _triangleNormal.crossVectors( _f0, _f1 );
  12243. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  12244. return satForAxes( axes, _v0$2, _v1$4, _v2$3, _extents );
  12245. }
  12246. /**
  12247. * Clamps the given point within the bounds of this box.
  12248. *
  12249. * @param {Vector3} point - The point to clamp.
  12250. * @param {Vector3} target - The target vector that is used to store the method's result.
  12251. * @return {Vector3} The clamped point.
  12252. */
  12253. clampPoint( point, target ) {
  12254. return target.copy( point ).clamp( this.min, this.max );
  12255. }
  12256. /**
  12257. * Returns the euclidean distance from any edge of this box to the specified point. If
  12258. * the given point lies inside of this box, the distance will be `0`.
  12259. *
  12260. * @param {Vector3} point - The point to compute the distance to.
  12261. * @return {number} The euclidean distance.
  12262. */
  12263. distanceToPoint( point ) {
  12264. return this.clampPoint( point, _vector$b ).distanceTo( point );
  12265. }
  12266. /**
  12267. * Returns a bounding sphere that encloses this bounding box.
  12268. *
  12269. * @param {Sphere} target - The target sphere that is used to store the method's result.
  12270. * @return {Sphere} The bounding sphere that encloses this bounding box.
  12271. */
  12272. getBoundingSphere( target ) {
  12273. if ( this.isEmpty() ) {
  12274. target.makeEmpty();
  12275. } else {
  12276. this.getCenter( target.center );
  12277. target.radius = this.getSize( _vector$b ).length() * 0.5;
  12278. }
  12279. return target;
  12280. }
  12281. /**
  12282. * Computes the intersection of this bounding box and the given one, setting the upper
  12283. * bound of this box to the lesser of the two boxes' upper bounds and the
  12284. * lower bound of this box to the greater of the two boxes' lower bounds. If
  12285. * there's no overlap, makes this box empty.
  12286. *
  12287. * @param {Box3} box - The bounding box to intersect with.
  12288. * @return {Box3} A reference to this bounding box.
  12289. */
  12290. intersect( box ) {
  12291. this.min.max( box.min );
  12292. this.max.min( box.max );
  12293. // 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.
  12294. if ( this.isEmpty() ) this.makeEmpty();
  12295. return this;
  12296. }
  12297. /**
  12298. * Computes the union of this box and another and the given one, setting the upper
  12299. * bound of this box to the greater of the two boxes' upper bounds and the
  12300. * lower bound of this box to the lesser of the two boxes' lower bounds.
  12301. *
  12302. * @param {Box3} box - The bounding box that will be unioned with this instance.
  12303. * @return {Box3} A reference to this bounding box.
  12304. */
  12305. union( box ) {
  12306. this.min.min( box.min );
  12307. this.max.max( box.max );
  12308. return this;
  12309. }
  12310. /**
  12311. * Transforms this bounding box by the given 4x4 transformation matrix.
  12312. *
  12313. * @param {Matrix4} matrix - The transformation matrix.
  12314. * @return {Box3} A reference to this bounding box.
  12315. */
  12316. applyMatrix4( matrix ) {
  12317. // transform of empty box is an empty box.
  12318. if ( this.isEmpty() ) return this;
  12319. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  12320. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  12321. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  12322. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  12323. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  12324. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  12325. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  12326. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  12327. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  12328. this.setFromPoints( _points );
  12329. return this;
  12330. }
  12331. /**
  12332. * Adds the given offset to both the upper and lower bounds of this bounding box,
  12333. * effectively moving it in 3D space.
  12334. *
  12335. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  12336. * @return {Box3} A reference to this bounding box.
  12337. */
  12338. translate( offset ) {
  12339. this.min.add( offset );
  12340. this.max.add( offset );
  12341. return this;
  12342. }
  12343. /**
  12344. * Returns `true` if this bounding box is equal with the given one.
  12345. *
  12346. * @param {Box3} box - The box to test for equality.
  12347. * @return {boolean} Whether this bounding box is equal with the given one.
  12348. */
  12349. equals( box ) {
  12350. return box.min.equals( this.min ) && box.max.equals( this.max );
  12351. }
  12352. /**
  12353. * Returns a serialized structure of the bounding box.
  12354. *
  12355. * @return {Object} Serialized structure with fields representing the object state.
  12356. */
  12357. toJSON() {
  12358. return {
  12359. min: this.min.toArray(),
  12360. max: this.max.toArray()
  12361. };
  12362. }
  12363. /**
  12364. * Returns a serialized structure of the bounding box.
  12365. *
  12366. * @param {Object} json - The serialized json to set the box from.
  12367. * @return {Box3} A reference to this bounding box.
  12368. */
  12369. fromJSON( json ) {
  12370. this.min.fromArray( json.min );
  12371. this.max.fromArray( json.max );
  12372. return this;
  12373. }
  12374. }
  12375. const _points = [
  12376. /*@__PURE__*/ new Vector3(),
  12377. /*@__PURE__*/ new Vector3(),
  12378. /*@__PURE__*/ new Vector3(),
  12379. /*@__PURE__*/ new Vector3(),
  12380. /*@__PURE__*/ new Vector3(),
  12381. /*@__PURE__*/ new Vector3(),
  12382. /*@__PURE__*/ new Vector3(),
  12383. /*@__PURE__*/ new Vector3()
  12384. ];
  12385. const _vector$b = /*@__PURE__*/ new Vector3();
  12386. const _box$4 = /*@__PURE__*/ new Box3();
  12387. // triangle centered vertices
  12388. const _v0$2 = /*@__PURE__*/ new Vector3();
  12389. const _v1$4 = /*@__PURE__*/ new Vector3();
  12390. const _v2$3 = /*@__PURE__*/ new Vector3();
  12391. // triangle edge vectors
  12392. const _f0 = /*@__PURE__*/ new Vector3();
  12393. const _f1 = /*@__PURE__*/ new Vector3();
  12394. const _f2 = /*@__PURE__*/ new Vector3();
  12395. const _center = /*@__PURE__*/ new Vector3();
  12396. const _extents = /*@__PURE__*/ new Vector3();
  12397. const _triangleNormal = /*@__PURE__*/ new Vector3();
  12398. const _testAxis = /*@__PURE__*/ new Vector3();
  12399. function satForAxes( axes, v0, v1, v2, extents ) {
  12400. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  12401. _testAxis.fromArray( axes, i );
  12402. // project the aabb onto the separating axis
  12403. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  12404. // project all 3 vertices of the triangle onto the separating axis
  12405. const p0 = v0.dot( _testAxis );
  12406. const p1 = v1.dot( _testAxis );
  12407. const p2 = v2.dot( _testAxis );
  12408. // actual test, basically see if either of the most extreme of the triangle points intersects r
  12409. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  12410. // points of the projected triangle are outside the projected half-length of the aabb
  12411. // the axis is separating and we can exit
  12412. return false;
  12413. }
  12414. }
  12415. return true;
  12416. }
  12417. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  12418. const _tables = /*@__PURE__*/ _generateTables();
  12419. function _generateTables() {
  12420. // float32 to float16 helpers
  12421. const buffer = new ArrayBuffer( 4 );
  12422. const floatView = new Float32Array( buffer );
  12423. const uint32View = new Uint32Array( buffer );
  12424. const baseTable = new Uint32Array( 512 );
  12425. const shiftTable = new Uint32Array( 512 );
  12426. for ( let i = 0; i < 256; ++ i ) {
  12427. const e = i - 127;
  12428. // very small number (0, -0)
  12429. if ( e < -27 ) {
  12430. baseTable[ i ] = 0x0000;
  12431. baseTable[ i | 0x100 ] = 0x8000;
  12432. shiftTable[ i ] = 24;
  12433. shiftTable[ i | 0x100 ] = 24;
  12434. // small number (denorm)
  12435. } else if ( e < -14 ) {
  12436. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  12437. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  12438. shiftTable[ i ] = - e - 1;
  12439. shiftTable[ i | 0x100 ] = - e - 1;
  12440. // normal number
  12441. } else if ( e <= 15 ) {
  12442. baseTable[ i ] = ( e + 15 ) << 10;
  12443. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  12444. shiftTable[ i ] = 13;
  12445. shiftTable[ i | 0x100 ] = 13;
  12446. // large number (Infinity, -Infinity)
  12447. } else if ( e < 128 ) {
  12448. baseTable[ i ] = 0x7c00;
  12449. baseTable[ i | 0x100 ] = 0xfc00;
  12450. shiftTable[ i ] = 24;
  12451. shiftTable[ i | 0x100 ] = 24;
  12452. // stay (NaN, Infinity, -Infinity)
  12453. } else {
  12454. baseTable[ i ] = 0x7c00;
  12455. baseTable[ i | 0x100 ] = 0xfc00;
  12456. shiftTable[ i ] = 13;
  12457. shiftTable[ i | 0x100 ] = 13;
  12458. }
  12459. }
  12460. // float16 to float32 helpers
  12461. const mantissaTable = new Uint32Array( 2048 );
  12462. const exponentTable = new Uint32Array( 64 );
  12463. const offsetTable = new Uint32Array( 64 );
  12464. for ( let i = 1; i < 1024; ++ i ) {
  12465. let m = i << 13; // zero pad mantissa bits
  12466. let e = 0; // zero exponent
  12467. // normalized
  12468. while ( ( m & 0x00800000 ) === 0 ) {
  12469. m <<= 1;
  12470. e -= 0x00800000; // decrement exponent
  12471. }
  12472. m &= -8388609; // clear leading 1 bit
  12473. e += 0x38800000; // adjust bias
  12474. mantissaTable[ i ] = m | e;
  12475. }
  12476. for ( let i = 1024; i < 2048; ++ i ) {
  12477. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  12478. }
  12479. for ( let i = 1; i < 31; ++ i ) {
  12480. exponentTable[ i ] = i << 23;
  12481. }
  12482. exponentTable[ 31 ] = 0x47800000;
  12483. exponentTable[ 32 ] = 0x80000000;
  12484. for ( let i = 33; i < 63; ++ i ) {
  12485. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  12486. }
  12487. exponentTable[ 63 ] = 0xc7800000;
  12488. for ( let i = 1; i < 64; ++ i ) {
  12489. if ( i !== 32 ) {
  12490. offsetTable[ i ] = 1024;
  12491. }
  12492. }
  12493. return {
  12494. floatView: floatView,
  12495. uint32View: uint32View,
  12496. baseTable: baseTable,
  12497. shiftTable: shiftTable,
  12498. mantissaTable: mantissaTable,
  12499. exponentTable: exponentTable,
  12500. offsetTable: offsetTable
  12501. };
  12502. }
  12503. /**
  12504. * Returns a half precision floating point value (FP16) from the given single
  12505. * precision floating point value (FP32).
  12506. *
  12507. * @param {number} val - A single precision floating point value.
  12508. * @return {number} The FP16 value.
  12509. */
  12510. function toHalfFloat( val ) {
  12511. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  12512. val = clamp( val, -65504, 65504 );
  12513. _tables.floatView[ 0 ] = val;
  12514. const f = _tables.uint32View[ 0 ];
  12515. const e = ( f >> 23 ) & 0x1ff;
  12516. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  12517. }
  12518. /**
  12519. * Returns a single precision floating point value (FP32) from the given half
  12520. * precision floating point value (FP16).
  12521. *
  12522. * @param {number} val - A half precision floating point value.
  12523. * @return {number} The FP32 value.
  12524. */
  12525. function fromHalfFloat( val ) {
  12526. const m = val >> 10;
  12527. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  12528. return _tables.floatView[ 0 ];
  12529. }
  12530. /**
  12531. * A class containing utility functions for data.
  12532. *
  12533. * @hideconstructor
  12534. */
  12535. class DataUtils {
  12536. /**
  12537. * Returns a half precision floating point value (FP16) from the given single
  12538. * precision floating point value (FP32).
  12539. *
  12540. * @param {number} val - A single precision floating point value.
  12541. * @return {number} The FP16 value.
  12542. */
  12543. static toHalfFloat( val ) {
  12544. return toHalfFloat( val );
  12545. }
  12546. /**
  12547. * Returns a single precision floating point value (FP32) from the given half
  12548. * precision floating point value (FP16).
  12549. *
  12550. * @param {number} val - A half precision floating point value.
  12551. * @return {number} The FP32 value.
  12552. */
  12553. static fromHalfFloat( val ) {
  12554. return fromHalfFloat( val );
  12555. }
  12556. }
  12557. const _vector$a = /*@__PURE__*/ new Vector3();
  12558. const _vector2$1 = /*@__PURE__*/ new Vector2();
  12559. let _id$3 = 0;
  12560. /**
  12561. * This class stores data for an attribute (such as vertex positions, face
  12562. * indices, normals, colors, UVs, and any custom attributes ) associated with
  12563. * a geometry, which allows for more efficient passing of data to the GPU.
  12564. *
  12565. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  12566. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  12567. */
  12568. class BufferAttribute {
  12569. /**
  12570. * Constructs a new buffer attribute.
  12571. *
  12572. * @param {TypedArray} array - The array holding the attribute data.
  12573. * @param {number} itemSize - The item size.
  12574. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  12575. */
  12576. constructor( array, itemSize, normalized = false ) {
  12577. if ( Array.isArray( array ) ) {
  12578. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12579. }
  12580. /**
  12581. * This flag can be used for type testing.
  12582. *
  12583. * @type {boolean}
  12584. * @readonly
  12585. * @default true
  12586. */
  12587. this.isBufferAttribute = true;
  12588. /**
  12589. * The ID of the buffer attribute.
  12590. *
  12591. * @name BufferAttribute#id
  12592. * @type {number}
  12593. * @readonly
  12594. */
  12595. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  12596. /**
  12597. * The name of the buffer attribute.
  12598. *
  12599. * @type {string}
  12600. */
  12601. this.name = '';
  12602. /**
  12603. * The array holding the attribute data. It should have `itemSize * numVertices`
  12604. * elements, where `numVertices` is the number of vertices in the associated geometry.
  12605. *
  12606. * @type {TypedArray}
  12607. */
  12608. this.array = array;
  12609. /**
  12610. * The number of values of the array that should be associated with a particular vertex.
  12611. * For instance, if this attribute is storing a 3-component vector (such as a position,
  12612. * normal, or color), then the value should be `3`.
  12613. *
  12614. * @type {number}
  12615. */
  12616. this.itemSize = itemSize;
  12617. /**
  12618. * Represents the number of items this buffer attribute stores. It is internally computed
  12619. * by dividing the `array` length by the `itemSize`.
  12620. *
  12621. * @type {number}
  12622. * @readonly
  12623. */
  12624. this.count = array !== undefined ? array.length / itemSize : 0;
  12625. /**
  12626. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  12627. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  12628. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  12629. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  12630. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  12631. *
  12632. * @type {boolean}
  12633. */
  12634. this.normalized = normalized;
  12635. /**
  12636. * Defines the intended usage pattern of the data store for optimization purposes.
  12637. *
  12638. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  12639. * instantiate a new one and set the desired usage before the next render.
  12640. *
  12641. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  12642. * @default StaticDrawUsage
  12643. */
  12644. this.usage = StaticDrawUsage;
  12645. /**
  12646. * This can be used to only update some components of stored vectors (for example, just the
  12647. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  12648. *
  12649. * @type {Array<Object>}
  12650. */
  12651. this.updateRanges = [];
  12652. /**
  12653. * Configures the bound GPU type for use in shaders.
  12654. *
  12655. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  12656. * For lower precision float types, use `Float16BufferAttribute`.
  12657. *
  12658. * @type {(FloatType|IntType)}
  12659. * @default FloatType
  12660. */
  12661. this.gpuType = FloatType;
  12662. /**
  12663. * A version number, incremented every time the `needsUpdate` is set to `true`.
  12664. *
  12665. * @type {number}
  12666. */
  12667. this.version = 0;
  12668. }
  12669. /**
  12670. * A callback function that is executed after the renderer has transferred the attribute
  12671. * array data to the GPU.
  12672. */
  12673. onUploadCallback() {}
  12674. /**
  12675. * Flag to indicate that this attribute has changed and should be re-sent to
  12676. * the GPU. Set this to `true` when you modify the value of the array.
  12677. *
  12678. * @type {number}
  12679. * @default false
  12680. * @param {boolean} value
  12681. */
  12682. set needsUpdate( value ) {
  12683. if ( value === true ) this.version ++;
  12684. }
  12685. /**
  12686. * Sets the usage of this buffer attribute.
  12687. *
  12688. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  12689. * @return {BufferAttribute} A reference to this buffer attribute.
  12690. */
  12691. setUsage( value ) {
  12692. this.usage = value;
  12693. return this;
  12694. }
  12695. /**
  12696. * Adds a range of data in the data array to be updated on the GPU.
  12697. *
  12698. * @param {number} start - Position at which to start update.
  12699. * @param {number} count - The number of components to update.
  12700. */
  12701. addUpdateRange( start, count ) {
  12702. this.updateRanges.push( { start, count } );
  12703. }
  12704. /**
  12705. * Clears the update ranges.
  12706. */
  12707. clearUpdateRanges() {
  12708. this.updateRanges.length = 0;
  12709. }
  12710. /**
  12711. * Copies the values of the given buffer attribute to this instance.
  12712. *
  12713. * @param {BufferAttribute} source - The buffer attribute to copy.
  12714. * @return {BufferAttribute} A reference to this instance.
  12715. */
  12716. copy( source ) {
  12717. this.name = source.name;
  12718. this.array = new source.array.constructor( source.array );
  12719. this.itemSize = source.itemSize;
  12720. this.count = source.count;
  12721. this.normalized = source.normalized;
  12722. this.usage = source.usage;
  12723. this.gpuType = source.gpuType;
  12724. return this;
  12725. }
  12726. /**
  12727. * Copies a vector from the given buffer attribute to this one. The start
  12728. * and destination position in the attribute buffers are represented by the
  12729. * given indices.
  12730. *
  12731. * @param {number} index1 - The destination index into this buffer attribute.
  12732. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  12733. * @param {number} index2 - The source index into the given buffer attribute.
  12734. * @return {BufferAttribute} A reference to this instance.
  12735. */
  12736. copyAt( index1, attribute, index2 ) {
  12737. index1 *= this.itemSize;
  12738. index2 *= attribute.itemSize;
  12739. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  12740. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12741. }
  12742. return this;
  12743. }
  12744. /**
  12745. * Copies the given array data into this buffer attribute.
  12746. *
  12747. * @param {(TypedArray|Array)} array - The array to copy.
  12748. * @return {BufferAttribute} A reference to this instance.
  12749. */
  12750. copyArray( array ) {
  12751. this.array.set( array );
  12752. return this;
  12753. }
  12754. /**
  12755. * Applies the given 3x3 matrix to the given attribute. Works with
  12756. * item size `2` and `3`.
  12757. *
  12758. * @param {Matrix3} m - The matrix to apply.
  12759. * @return {BufferAttribute} A reference to this instance.
  12760. */
  12761. applyMatrix3( m ) {
  12762. if ( this.itemSize === 2 ) {
  12763. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12764. _vector2$1.fromBufferAttribute( this, i );
  12765. _vector2$1.applyMatrix3( m );
  12766. this.setXY( i, _vector2$1.x, _vector2$1.y );
  12767. }
  12768. } else if ( this.itemSize === 3 ) {
  12769. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12770. _vector$a.fromBufferAttribute( this, i );
  12771. _vector$a.applyMatrix3( m );
  12772. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12773. }
  12774. }
  12775. return this;
  12776. }
  12777. /**
  12778. * Applies the given 4x4 matrix to the given attribute. Only works with
  12779. * item size `3`.
  12780. *
  12781. * @param {Matrix4} m - The matrix to apply.
  12782. * @return {BufferAttribute} A reference to this instance.
  12783. */
  12784. applyMatrix4( m ) {
  12785. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12786. _vector$a.fromBufferAttribute( this, i );
  12787. _vector$a.applyMatrix4( m );
  12788. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12789. }
  12790. return this;
  12791. }
  12792. /**
  12793. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  12794. * item size `3`.
  12795. *
  12796. * @param {Matrix3} m - The normal matrix to apply.
  12797. * @return {BufferAttribute} A reference to this instance.
  12798. */
  12799. applyNormalMatrix( m ) {
  12800. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12801. _vector$a.fromBufferAttribute( this, i );
  12802. _vector$a.applyNormalMatrix( m );
  12803. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12804. }
  12805. return this;
  12806. }
  12807. /**
  12808. * Applies the given 4x4 matrix to the given attribute. Only works with
  12809. * item size `3` and with direction vectors.
  12810. *
  12811. * @param {Matrix4} m - The matrix to apply.
  12812. * @return {BufferAttribute} A reference to this instance.
  12813. */
  12814. transformDirection( m ) {
  12815. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12816. _vector$a.fromBufferAttribute( this, i );
  12817. _vector$a.transformDirection( m );
  12818. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12819. }
  12820. return this;
  12821. }
  12822. /**
  12823. * Sets the given array data in the buffer attribute.
  12824. *
  12825. * @param {(TypedArray|Array)} value - The array data to set.
  12826. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  12827. * @return {BufferAttribute} A reference to this instance.
  12828. */
  12829. set( value, offset = 0 ) {
  12830. // Matching BufferAttribute constructor, do not normalize the array.
  12831. this.array.set( value, offset );
  12832. return this;
  12833. }
  12834. /**
  12835. * Returns the given component of the vector at the given index.
  12836. *
  12837. * @param {number} index - The index into the buffer attribute.
  12838. * @param {number} component - The component index.
  12839. * @return {number} The returned value.
  12840. */
  12841. getComponent( index, component ) {
  12842. let value = this.array[ index * this.itemSize + component ];
  12843. if ( this.normalized ) value = denormalize( value, this.array );
  12844. return value;
  12845. }
  12846. /**
  12847. * Sets the given value to the given component of the vector at the given index.
  12848. *
  12849. * @param {number} index - The index into the buffer attribute.
  12850. * @param {number} component - The component index.
  12851. * @param {number} value - The value to set.
  12852. * @return {BufferAttribute} A reference to this instance.
  12853. */
  12854. setComponent( index, component, value ) {
  12855. if ( this.normalized ) value = normalize( value, this.array );
  12856. this.array[ index * this.itemSize + component ] = value;
  12857. return this;
  12858. }
  12859. /**
  12860. * Returns the x component of the vector at the given index.
  12861. *
  12862. * @param {number} index - The index into the buffer attribute.
  12863. * @return {number} The x component.
  12864. */
  12865. getX( index ) {
  12866. let x = this.array[ index * this.itemSize ];
  12867. if ( this.normalized ) x = denormalize( x, this.array );
  12868. return x;
  12869. }
  12870. /**
  12871. * Sets the x component of the vector at the given index.
  12872. *
  12873. * @param {number} index - The index into the buffer attribute.
  12874. * @param {number} x - The value to set.
  12875. * @return {BufferAttribute} A reference to this instance.
  12876. */
  12877. setX( index, x ) {
  12878. if ( this.normalized ) x = normalize( x, this.array );
  12879. this.array[ index * this.itemSize ] = x;
  12880. return this;
  12881. }
  12882. /**
  12883. * Returns the y component of the vector at the given index.
  12884. *
  12885. * @param {number} index - The index into the buffer attribute.
  12886. * @return {number} The y component.
  12887. */
  12888. getY( index ) {
  12889. let y = this.array[ index * this.itemSize + 1 ];
  12890. if ( this.normalized ) y = denormalize( y, this.array );
  12891. return y;
  12892. }
  12893. /**
  12894. * Sets the y component of the vector at the given index.
  12895. *
  12896. * @param {number} index - The index into the buffer attribute.
  12897. * @param {number} y - The value to set.
  12898. * @return {BufferAttribute} A reference to this instance.
  12899. */
  12900. setY( index, y ) {
  12901. if ( this.normalized ) y = normalize( y, this.array );
  12902. this.array[ index * this.itemSize + 1 ] = y;
  12903. return this;
  12904. }
  12905. /**
  12906. * Returns the z component of the vector at the given index.
  12907. *
  12908. * @param {number} index - The index into the buffer attribute.
  12909. * @return {number} The z component.
  12910. */
  12911. getZ( index ) {
  12912. let z = this.array[ index * this.itemSize + 2 ];
  12913. if ( this.normalized ) z = denormalize( z, this.array );
  12914. return z;
  12915. }
  12916. /**
  12917. * Sets the z component of the vector at the given index.
  12918. *
  12919. * @param {number} index - The index into the buffer attribute.
  12920. * @param {number} z - The value to set.
  12921. * @return {BufferAttribute} A reference to this instance.
  12922. */
  12923. setZ( index, z ) {
  12924. if ( this.normalized ) z = normalize( z, this.array );
  12925. this.array[ index * this.itemSize + 2 ] = z;
  12926. return this;
  12927. }
  12928. /**
  12929. * Returns the w component of the vector at the given index.
  12930. *
  12931. * @param {number} index - The index into the buffer attribute.
  12932. * @return {number} The w component.
  12933. */
  12934. getW( index ) {
  12935. let w = this.array[ index * this.itemSize + 3 ];
  12936. if ( this.normalized ) w = denormalize( w, this.array );
  12937. return w;
  12938. }
  12939. /**
  12940. * Sets the w component of the vector at the given index.
  12941. *
  12942. * @param {number} index - The index into the buffer attribute.
  12943. * @param {number} w - The value to set.
  12944. * @return {BufferAttribute} A reference to this instance.
  12945. */
  12946. setW( index, w ) {
  12947. if ( this.normalized ) w = normalize( w, this.array );
  12948. this.array[ index * this.itemSize + 3 ] = w;
  12949. return this;
  12950. }
  12951. /**
  12952. * Sets the x and y component of the vector at the given index.
  12953. *
  12954. * @param {number} index - The index into the buffer attribute.
  12955. * @param {number} x - The value for the x component to set.
  12956. * @param {number} y - The value for the y component to set.
  12957. * @return {BufferAttribute} A reference to this instance.
  12958. */
  12959. setXY( index, x, y ) {
  12960. index *= this.itemSize;
  12961. if ( this.normalized ) {
  12962. x = normalize( x, this.array );
  12963. y = normalize( y, this.array );
  12964. }
  12965. this.array[ index + 0 ] = x;
  12966. this.array[ index + 1 ] = y;
  12967. return this;
  12968. }
  12969. /**
  12970. * Sets the x, y and z component of the vector at the given index.
  12971. *
  12972. * @param {number} index - The index into the buffer attribute.
  12973. * @param {number} x - The value for the x component to set.
  12974. * @param {number} y - The value for the y component to set.
  12975. * @param {number} z - The value for the z component to set.
  12976. * @return {BufferAttribute} A reference to this instance.
  12977. */
  12978. setXYZ( index, x, y, z ) {
  12979. index *= this.itemSize;
  12980. if ( this.normalized ) {
  12981. x = normalize( x, this.array );
  12982. y = normalize( y, this.array );
  12983. z = normalize( z, this.array );
  12984. }
  12985. this.array[ index + 0 ] = x;
  12986. this.array[ index + 1 ] = y;
  12987. this.array[ index + 2 ] = z;
  12988. return this;
  12989. }
  12990. /**
  12991. * Sets the x, y, z and w component of the vector at the given index.
  12992. *
  12993. * @param {number} index - The index into the buffer attribute.
  12994. * @param {number} x - The value for the x component to set.
  12995. * @param {number} y - The value for the y component to set.
  12996. * @param {number} z - The value for the z component to set.
  12997. * @param {number} w - The value for the w component to set.
  12998. * @return {BufferAttribute} A reference to this instance.
  12999. */
  13000. setXYZW( index, x, y, z, w ) {
  13001. index *= this.itemSize;
  13002. if ( this.normalized ) {
  13003. x = normalize( x, this.array );
  13004. y = normalize( y, this.array );
  13005. z = normalize( z, this.array );
  13006. w = normalize( w, this.array );
  13007. }
  13008. this.array[ index + 0 ] = x;
  13009. this.array[ index + 1 ] = y;
  13010. this.array[ index + 2 ] = z;
  13011. this.array[ index + 3 ] = w;
  13012. return this;
  13013. }
  13014. /**
  13015. * Sets the given callback function that is executed after the Renderer has transferred
  13016. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13017. * the upload when attribute data are not needed anymore on the CPU side.
  13018. *
  13019. * @param {Function} callback - The `onUpload()` callback.
  13020. * @return {BufferAttribute} A reference to this instance.
  13021. */
  13022. onUpload( callback ) {
  13023. this.onUploadCallback = callback;
  13024. return this;
  13025. }
  13026. /**
  13027. * Returns a new buffer attribute with copied values from this instance.
  13028. *
  13029. * @return {BufferAttribute} A clone of this instance.
  13030. */
  13031. clone() {
  13032. return new this.constructor( this.array, this.itemSize ).copy( this );
  13033. }
  13034. /**
  13035. * Serializes the buffer attribute into JSON.
  13036. *
  13037. * @return {Object} A JSON object representing the serialized buffer attribute.
  13038. */
  13039. toJSON() {
  13040. const data = {
  13041. itemSize: this.itemSize,
  13042. type: this.array.constructor.name,
  13043. array: Array.from( this.array ),
  13044. normalized: this.normalized
  13045. };
  13046. if ( this.name !== '' ) data.name = this.name;
  13047. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13048. return data;
  13049. }
  13050. }
  13051. /**
  13052. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13053. * a plain `Array` instance.
  13054. *
  13055. * @augments BufferAttribute
  13056. */
  13057. class Int8BufferAttribute extends BufferAttribute {
  13058. /**
  13059. * Constructs a new buffer attribute.
  13060. *
  13061. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13062. * @param {number} itemSize - The item size.
  13063. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13064. */
  13065. constructor( array, itemSize, normalized ) {
  13066. super( new Int8Array( array ), itemSize, normalized );
  13067. }
  13068. }
  13069. /**
  13070. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13071. * a plain `Array` instance.
  13072. *
  13073. * @augments BufferAttribute
  13074. */
  13075. class Uint8BufferAttribute extends BufferAttribute {
  13076. /**
  13077. * Constructs a new buffer attribute.
  13078. *
  13079. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13080. * @param {number} itemSize - The item size.
  13081. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13082. */
  13083. constructor( array, itemSize, normalized ) {
  13084. super( new Uint8Array( array ), itemSize, normalized );
  13085. }
  13086. }
  13087. /**
  13088. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13089. * a plain `Array` instance.
  13090. *
  13091. * @augments BufferAttribute
  13092. */
  13093. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13094. /**
  13095. * Constructs a new buffer attribute.
  13096. *
  13097. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13098. * @param {number} itemSize - The item size.
  13099. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13100. */
  13101. constructor( array, itemSize, normalized ) {
  13102. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13103. }
  13104. }
  13105. /**
  13106. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13107. * a plain `Array` instance.
  13108. *
  13109. * @augments BufferAttribute
  13110. */
  13111. class Int16BufferAttribute extends BufferAttribute {
  13112. /**
  13113. * Constructs a new buffer attribute.
  13114. *
  13115. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13116. * @param {number} itemSize - The item size.
  13117. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13118. */
  13119. constructor( array, itemSize, normalized ) {
  13120. super( new Int16Array( array ), itemSize, normalized );
  13121. }
  13122. }
  13123. /**
  13124. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13125. * a plain `Array` instance.
  13126. *
  13127. * @augments BufferAttribute
  13128. */
  13129. class Uint16BufferAttribute extends BufferAttribute {
  13130. /**
  13131. * Constructs a new buffer attribute.
  13132. *
  13133. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13134. * @param {number} itemSize - The item size.
  13135. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13136. */
  13137. constructor( array, itemSize, normalized ) {
  13138. super( new Uint16Array( array ), itemSize, normalized );
  13139. }
  13140. }
  13141. /**
  13142. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13143. * a plain `Array` instance.
  13144. *
  13145. * @augments BufferAttribute
  13146. */
  13147. class Int32BufferAttribute extends BufferAttribute {
  13148. /**
  13149. * Constructs a new buffer attribute.
  13150. *
  13151. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13152. * @param {number} itemSize - The item size.
  13153. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13154. */
  13155. constructor( array, itemSize, normalized ) {
  13156. super( new Int32Array( array ), itemSize, normalized );
  13157. }
  13158. }
  13159. /**
  13160. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13161. * a plain `Array` instance.
  13162. *
  13163. * @augments BufferAttribute
  13164. */
  13165. class Uint32BufferAttribute extends BufferAttribute {
  13166. /**
  13167. * Constructs a new buffer attribute.
  13168. *
  13169. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13170. * @param {number} itemSize - The item size.
  13171. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13172. */
  13173. constructor( array, itemSize, normalized ) {
  13174. super( new Uint32Array( array ), itemSize, normalized );
  13175. }
  13176. }
  13177. /**
  13178. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13179. * a plain `Array` instance.
  13180. *
  13181. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13182. * browser support is still problematic.
  13183. *
  13184. * @augments BufferAttribute
  13185. */
  13186. class Float16BufferAttribute extends BufferAttribute {
  13187. /**
  13188. * Constructs a new buffer attribute.
  13189. *
  13190. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13191. * @param {number} itemSize - The item size.
  13192. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13193. */
  13194. constructor( array, itemSize, normalized ) {
  13195. super( new Uint16Array( array ), itemSize, normalized );
  13196. this.isFloat16BufferAttribute = true;
  13197. }
  13198. getX( index ) {
  13199. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13200. if ( this.normalized ) x = denormalize( x, this.array );
  13201. return x;
  13202. }
  13203. setX( index, x ) {
  13204. if ( this.normalized ) x = normalize( x, this.array );
  13205. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13206. return this;
  13207. }
  13208. getY( index ) {
  13209. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13210. if ( this.normalized ) y = denormalize( y, this.array );
  13211. return y;
  13212. }
  13213. setY( index, y ) {
  13214. if ( this.normalized ) y = normalize( y, this.array );
  13215. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13216. return this;
  13217. }
  13218. getZ( index ) {
  13219. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13220. if ( this.normalized ) z = denormalize( z, this.array );
  13221. return z;
  13222. }
  13223. setZ( index, z ) {
  13224. if ( this.normalized ) z = normalize( z, this.array );
  13225. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13226. return this;
  13227. }
  13228. getW( index ) {
  13229. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13230. if ( this.normalized ) w = denormalize( w, this.array );
  13231. return w;
  13232. }
  13233. setW( index, w ) {
  13234. if ( this.normalized ) w = normalize( w, this.array );
  13235. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13236. return this;
  13237. }
  13238. setXY( index, x, y ) {
  13239. index *= this.itemSize;
  13240. if ( this.normalized ) {
  13241. x = normalize( x, this.array );
  13242. y = normalize( y, this.array );
  13243. }
  13244. this.array[ index + 0 ] = toHalfFloat( x );
  13245. this.array[ index + 1 ] = toHalfFloat( y );
  13246. return this;
  13247. }
  13248. setXYZ( index, x, y, z ) {
  13249. index *= this.itemSize;
  13250. if ( this.normalized ) {
  13251. x = normalize( x, this.array );
  13252. y = normalize( y, this.array );
  13253. z = normalize( z, this.array );
  13254. }
  13255. this.array[ index + 0 ] = toHalfFloat( x );
  13256. this.array[ index + 1 ] = toHalfFloat( y );
  13257. this.array[ index + 2 ] = toHalfFloat( z );
  13258. return this;
  13259. }
  13260. setXYZW( index, x, y, z, w ) {
  13261. index *= this.itemSize;
  13262. if ( this.normalized ) {
  13263. x = normalize( x, this.array );
  13264. y = normalize( y, this.array );
  13265. z = normalize( z, this.array );
  13266. w = normalize( w, this.array );
  13267. }
  13268. this.array[ index + 0 ] = toHalfFloat( x );
  13269. this.array[ index + 1 ] = toHalfFloat( y );
  13270. this.array[ index + 2 ] = toHalfFloat( z );
  13271. this.array[ index + 3 ] = toHalfFloat( w );
  13272. return this;
  13273. }
  13274. }
  13275. /**
  13276. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13277. * a plain `Array` instance.
  13278. *
  13279. * @augments BufferAttribute
  13280. */
  13281. class Float32BufferAttribute extends BufferAttribute {
  13282. /**
  13283. * Constructs a new buffer attribute.
  13284. *
  13285. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13286. * @param {number} itemSize - The item size.
  13287. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13288. */
  13289. constructor( array, itemSize, normalized ) {
  13290. super( new Float32Array( array ), itemSize, normalized );
  13291. }
  13292. }
  13293. const _box$3 = /*@__PURE__*/ new Box3();
  13294. const _v1$3 = /*@__PURE__*/ new Vector3();
  13295. const _v2$2 = /*@__PURE__*/ new Vector3();
  13296. /**
  13297. * An analytical 3D sphere defined by a center and radius. This class is mainly
  13298. * used as a Bounding Sphere for 3D objects.
  13299. */
  13300. class Sphere {
  13301. /**
  13302. * Constructs a new sphere.
  13303. *
  13304. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  13305. * @param {number} [radius=-1] - The radius of the sphere.
  13306. */
  13307. constructor( center = new Vector3(), radius = -1 ) {
  13308. /**
  13309. * This flag can be used for type testing.
  13310. *
  13311. * @type {boolean}
  13312. * @readonly
  13313. * @default true
  13314. */
  13315. this.isSphere = true;
  13316. /**
  13317. * The center of the sphere
  13318. *
  13319. * @type {Vector3}
  13320. */
  13321. this.center = center;
  13322. /**
  13323. * The radius of the sphere.
  13324. *
  13325. * @type {number}
  13326. */
  13327. this.radius = radius;
  13328. }
  13329. /**
  13330. * Sets the sphere's components by copying the given values.
  13331. *
  13332. * @param {Vector3} center - The center.
  13333. * @param {number} radius - The radius.
  13334. * @return {Sphere} A reference to this sphere.
  13335. */
  13336. set( center, radius ) {
  13337. this.center.copy( center );
  13338. this.radius = radius;
  13339. return this;
  13340. }
  13341. /**
  13342. * Computes the minimum bounding sphere for list of points.
  13343. * If the optional center point is given, it is used as the sphere's
  13344. * center. Otherwise, the center of the axis-aligned bounding box
  13345. * encompassing the points is calculated.
  13346. *
  13347. * @param {Array<Vector3>} points - A list of points in 3D space.
  13348. * @param {Vector3} [optionalCenter] - The center of the sphere.
  13349. * @return {Sphere} A reference to this sphere.
  13350. */
  13351. setFromPoints( points, optionalCenter ) {
  13352. const center = this.center;
  13353. if ( optionalCenter !== undefined ) {
  13354. center.copy( optionalCenter );
  13355. } else {
  13356. _box$3.setFromPoints( points ).getCenter( center );
  13357. }
  13358. let maxRadiusSq = 0;
  13359. for ( let i = 0, il = points.length; i < il; i ++ ) {
  13360. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  13361. }
  13362. this.radius = Math.sqrt( maxRadiusSq );
  13363. return this;
  13364. }
  13365. /**
  13366. * Copies the values of the given sphere to this instance.
  13367. *
  13368. * @param {Sphere} sphere - The sphere to copy.
  13369. * @return {Sphere} A reference to this sphere.
  13370. */
  13371. copy( sphere ) {
  13372. this.center.copy( sphere.center );
  13373. this.radius = sphere.radius;
  13374. return this;
  13375. }
  13376. /**
  13377. * Returns `true` if the sphere is empty (the radius set to a negative number).
  13378. *
  13379. * Spheres with a radius of `0` contain only their center point and are not
  13380. * considered to be empty.
  13381. *
  13382. * @return {boolean} Whether this sphere is empty or not.
  13383. */
  13384. isEmpty() {
  13385. return ( this.radius < 0 );
  13386. }
  13387. /**
  13388. * Makes this sphere empty which means in encloses a zero space in 3D.
  13389. *
  13390. * @return {Sphere} A reference to this sphere.
  13391. */
  13392. makeEmpty() {
  13393. this.center.set( 0, 0, 0 );
  13394. this.radius = -1;
  13395. return this;
  13396. }
  13397. /**
  13398. * Returns `true` if this sphere contains the given point inclusive of
  13399. * the surface of the sphere.
  13400. *
  13401. * @param {Vector3} point - The point to check.
  13402. * @return {boolean} Whether this sphere contains the given point or not.
  13403. */
  13404. containsPoint( point ) {
  13405. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  13406. }
  13407. /**
  13408. * Returns the closest distance from the boundary of the sphere to the
  13409. * given point. If the sphere contains the point, the distance will
  13410. * be negative.
  13411. *
  13412. * @param {Vector3} point - The point to compute the distance to.
  13413. * @return {number} The distance to the point.
  13414. */
  13415. distanceToPoint( point ) {
  13416. return ( point.distanceTo( this.center ) - this.radius );
  13417. }
  13418. /**
  13419. * Returns `true` if this sphere intersects with the given one.
  13420. *
  13421. * @param {Sphere} sphere - The sphere to test.
  13422. * @return {boolean} Whether this sphere intersects with the given one or not.
  13423. */
  13424. intersectsSphere( sphere ) {
  13425. const radiusSum = this.radius + sphere.radius;
  13426. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  13427. }
  13428. /**
  13429. * Returns `true` if this sphere intersects with the given box.
  13430. *
  13431. * @param {Box3} box - The box to test.
  13432. * @return {boolean} Whether this sphere intersects with the given box or not.
  13433. */
  13434. intersectsBox( box ) {
  13435. return box.intersectsSphere( this );
  13436. }
  13437. /**
  13438. * Returns `true` if this sphere intersects with the given plane.
  13439. *
  13440. * @param {Plane} plane - The plane to test.
  13441. * @return {boolean} Whether this sphere intersects with the given plane or not.
  13442. */
  13443. intersectsPlane( plane ) {
  13444. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  13445. }
  13446. /**
  13447. * Clamps a point within the sphere. If the point is outside the sphere, it
  13448. * will clamp it to the closest point on the edge of the sphere. Points
  13449. * already inside the sphere will not be affected.
  13450. *
  13451. * @param {Vector3} point - The plane to clamp.
  13452. * @param {Vector3} target - The target vector that is used to store the method's result.
  13453. * @return {Vector3} The clamped point.
  13454. */
  13455. clampPoint( point, target ) {
  13456. const deltaLengthSq = this.center.distanceToSquared( point );
  13457. target.copy( point );
  13458. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  13459. target.sub( this.center ).normalize();
  13460. target.multiplyScalar( this.radius ).add( this.center );
  13461. }
  13462. return target;
  13463. }
  13464. /**
  13465. * Returns a bounding box that encloses this sphere.
  13466. *
  13467. * @param {Box3} target - The target box that is used to store the method's result.
  13468. * @return {Box3} The bounding box that encloses this sphere.
  13469. */
  13470. getBoundingBox( target ) {
  13471. if ( this.isEmpty() ) {
  13472. // Empty sphere produces empty bounding box
  13473. target.makeEmpty();
  13474. return target;
  13475. }
  13476. target.set( this.center, this.center );
  13477. target.expandByScalar( this.radius );
  13478. return target;
  13479. }
  13480. /**
  13481. * Transforms this sphere with the given 4x4 transformation matrix.
  13482. *
  13483. * @param {Matrix4} matrix - The transformation matrix.
  13484. * @return {Sphere} A reference to this sphere.
  13485. */
  13486. applyMatrix4( matrix ) {
  13487. this.center.applyMatrix4( matrix );
  13488. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  13489. return this;
  13490. }
  13491. /**
  13492. * Translates the sphere's center by the given offset.
  13493. *
  13494. * @param {Vector3} offset - The offset.
  13495. * @return {Sphere} A reference to this sphere.
  13496. */
  13497. translate( offset ) {
  13498. this.center.add( offset );
  13499. return this;
  13500. }
  13501. /**
  13502. * Expands the boundaries of this sphere to include the given point.
  13503. *
  13504. * @param {Vector3} point - The point to include.
  13505. * @return {Sphere} A reference to this sphere.
  13506. */
  13507. expandByPoint( point ) {
  13508. if ( this.isEmpty() ) {
  13509. this.center.copy( point );
  13510. this.radius = 0;
  13511. return this;
  13512. }
  13513. _v1$3.subVectors( point, this.center );
  13514. const lengthSq = _v1$3.lengthSq();
  13515. if ( lengthSq > ( this.radius * this.radius ) ) {
  13516. // calculate the minimal sphere
  13517. const length = Math.sqrt( lengthSq );
  13518. const delta = ( length - this.radius ) * 0.5;
  13519. this.center.addScaledVector( _v1$3, delta / length );
  13520. this.radius += delta;
  13521. }
  13522. return this;
  13523. }
  13524. /**
  13525. * Expands this sphere to enclose both the original sphere and the given sphere.
  13526. *
  13527. * @param {Sphere} sphere - The sphere to include.
  13528. * @return {Sphere} A reference to this sphere.
  13529. */
  13530. union( sphere ) {
  13531. if ( sphere.isEmpty() ) {
  13532. return this;
  13533. }
  13534. if ( this.isEmpty() ) {
  13535. this.copy( sphere );
  13536. return this;
  13537. }
  13538. if ( this.center.equals( sphere.center ) === true ) {
  13539. this.radius = Math.max( this.radius, sphere.radius );
  13540. } else {
  13541. _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  13542. this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) );
  13543. this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) );
  13544. }
  13545. return this;
  13546. }
  13547. /**
  13548. * Returns `true` if this sphere is equal with the given one.
  13549. *
  13550. * @param {Sphere} sphere - The sphere to test for equality.
  13551. * @return {boolean} Whether this bounding sphere is equal with the given one.
  13552. */
  13553. equals( sphere ) {
  13554. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  13555. }
  13556. /**
  13557. * Returns a new sphere with copied values from this instance.
  13558. *
  13559. * @return {Sphere} A clone of this instance.
  13560. */
  13561. clone() {
  13562. return new this.constructor().copy( this );
  13563. }
  13564. /**
  13565. * Returns a serialized structure of the bounding sphere.
  13566. *
  13567. * @return {Object} Serialized structure with fields representing the object state.
  13568. */
  13569. toJSON() {
  13570. return {
  13571. radius: this.radius,
  13572. center: this.center.toArray()
  13573. };
  13574. }
  13575. /**
  13576. * Returns a serialized structure of the bounding sphere.
  13577. *
  13578. * @param {Object} json - The serialized json to set the sphere from.
  13579. * @return {Sphere} A reference to this bounding sphere.
  13580. */
  13581. fromJSON( json ) {
  13582. this.radius = json.radius;
  13583. this.center.fromArray( json.center );
  13584. return this;
  13585. }
  13586. }
  13587. let _id$2 = 0;
  13588. const _m1$2 = /*@__PURE__*/ new Matrix4();
  13589. const _obj = /*@__PURE__*/ new Object3D();
  13590. const _offset = /*@__PURE__*/ new Vector3();
  13591. const _box$2 = /*@__PURE__*/ new Box3();
  13592. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13593. const _vector$9 = /*@__PURE__*/ new Vector3();
  13594. /**
  13595. * A representation of mesh, line, or point geometry. Includes vertex
  13596. * positions, face indices, normals, colors, UVs, and custom attributes
  13597. * within buffers, reducing the cost of passing all this data to the GPU.
  13598. *
  13599. * ```js
  13600. * const geometry = new THREE.BufferGeometry();
  13601. * // create a simple square shape. We duplicate the top left and bottom right
  13602. * // vertices because each vertex needs to appear once per triangle.
  13603. * const vertices = new Float32Array( [
  13604. * -1.0, -1.0, 1.0, // v0
  13605. * 1.0, -1.0, 1.0, // v1
  13606. * 1.0, 1.0, 1.0, // v2
  13607. *
  13608. * 1.0, 1.0, 1.0, // v3
  13609. * -1.0, 1.0, 1.0, // v4
  13610. * -1.0, -1.0, 1.0 // v5
  13611. * ] );
  13612. * // itemSize = 3 because there are 3 values (components) per vertex
  13613. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13614. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13615. * const mesh = new THREE.Mesh( geometry, material );
  13616. * ```
  13617. *
  13618. * @augments EventDispatcher
  13619. */
  13620. class BufferGeometry extends EventDispatcher {
  13621. /**
  13622. * Constructs a new geometry.
  13623. */
  13624. constructor() {
  13625. super();
  13626. /**
  13627. * This flag can be used for type testing.
  13628. *
  13629. * @type {boolean}
  13630. * @readonly
  13631. * @default true
  13632. */
  13633. this.isBufferGeometry = true;
  13634. /**
  13635. * The ID of the geometry.
  13636. *
  13637. * @name BufferGeometry#id
  13638. * @type {number}
  13639. * @readonly
  13640. */
  13641. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13642. /**
  13643. * The UUID of the geometry.
  13644. *
  13645. * @type {string}
  13646. * @readonly
  13647. */
  13648. this.uuid = generateUUID();
  13649. /**
  13650. * The name of the geometry.
  13651. *
  13652. * @type {string}
  13653. */
  13654. this.name = '';
  13655. this.type = 'BufferGeometry';
  13656. /**
  13657. * Allows for vertices to be re-used across multiple triangles; this is
  13658. * called using "indexed triangles". Each triangle is associated with the
  13659. * indices of three vertices. This attribute therefore stores the index of
  13660. * each vertex for each triangular face. If this attribute is not set, the
  13661. * renderer assumes that each three contiguous positions represent a single triangle.
  13662. *
  13663. * @type {?BufferAttribute}
  13664. * @default null
  13665. */
  13666. this.index = null;
  13667. /**
  13668. * A (storage) buffer attribute which was generated with a compute shader and
  13669. * now defines indirect draw calls.
  13670. *
  13671. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13672. *
  13673. * @type {?BufferAttribute}
  13674. * @default null
  13675. */
  13676. this.indirect = null;
  13677. /**
  13678. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  13679. *
  13680. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13681. *
  13682. * @type {number|Array<number>}
  13683. * @default 0
  13684. */
  13685. this.indirectOffset = 0;
  13686. /**
  13687. * This dictionary has as id the name of the attribute to be set and as value
  13688. * the buffer attribute to set it to. Rather than accessing this property directly,
  13689. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13690. *
  13691. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13692. */
  13693. this.attributes = {};
  13694. /**
  13695. * This dictionary holds the morph targets of the geometry.
  13696. *
  13697. * Note: Once the geometry has been rendered, the morph attribute data cannot
  13698. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  13699. *
  13700. * @type {Object}
  13701. */
  13702. this.morphAttributes = {};
  13703. /**
  13704. * Used to control the morph target behavior; when set to `true`, the morph
  13705. * target data is treated as relative offsets, rather than as absolute
  13706. * positions/normals.
  13707. *
  13708. * @type {boolean}
  13709. * @default false
  13710. */
  13711. this.morphTargetsRelative = false;
  13712. /**
  13713. * Split the geometry into groups, each of which will be rendered in a
  13714. * separate draw call. This allows an array of materials to be used with the geometry.
  13715. *
  13716. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  13717. *
  13718. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  13719. * indices, and must not leave vertices or indices unused.
  13720. *
  13721. * @type {Array<Object>}
  13722. */
  13723. this.groups = [];
  13724. /**
  13725. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  13726. *
  13727. * @type {?Box3}
  13728. * @default null
  13729. */
  13730. this.boundingBox = null;
  13731. /**
  13732. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  13733. *
  13734. * @type {?Sphere}
  13735. * @default null
  13736. */
  13737. this.boundingSphere = null;
  13738. /**
  13739. * Determines the part of the geometry to render. This should not be set directly,
  13740. * instead use `setDrawRange()`.
  13741. *
  13742. * @type {{start:number,count:number}}
  13743. */
  13744. this.drawRange = { start: 0, count: Infinity };
  13745. /**
  13746. * An object that can be used to store custom data about the geometry.
  13747. * It should not hold references to functions as these will not be cloned.
  13748. *
  13749. * @type {Object}
  13750. */
  13751. this.userData = {};
  13752. }
  13753. /**
  13754. * Returns the index of this geometry.
  13755. *
  13756. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  13757. */
  13758. getIndex() {
  13759. return this.index;
  13760. }
  13761. /**
  13762. * Sets the given index to this geometry.
  13763. *
  13764. * @param {Array<number>|BufferAttribute} index - The index to set.
  13765. * @return {BufferGeometry} A reference to this instance.
  13766. */
  13767. setIndex( index ) {
  13768. if ( Array.isArray( index ) ) {
  13769. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  13770. } else {
  13771. this.index = index;
  13772. }
  13773. return this;
  13774. }
  13775. /**
  13776. * Sets the given indirect attribute to this geometry.
  13777. *
  13778. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  13779. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  13780. * @return {BufferGeometry} A reference to this instance.
  13781. */
  13782. setIndirect( indirect, indirectOffset = 0 ) {
  13783. this.indirect = indirect;
  13784. this.indirectOffset = indirectOffset;
  13785. return this;
  13786. }
  13787. /**
  13788. * Returns the indirect attribute of this geometry.
  13789. *
  13790. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  13791. */
  13792. getIndirect() {
  13793. return this.indirect;
  13794. }
  13795. /**
  13796. * Returns the buffer attribute for the given name.
  13797. *
  13798. * @param {string} name - The attribute name.
  13799. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  13800. * Returns `undefined` if not attribute has been found.
  13801. */
  13802. getAttribute( name ) {
  13803. return this.attributes[ name ];
  13804. }
  13805. /**
  13806. * Sets the given attribute for the given name.
  13807. *
  13808. * @param {string} name - The attribute name.
  13809. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  13810. * @return {BufferGeometry} A reference to this instance.
  13811. */
  13812. setAttribute( name, attribute ) {
  13813. this.attributes[ name ] = attribute;
  13814. return this;
  13815. }
  13816. /**
  13817. * Deletes the attribute for the given name.
  13818. *
  13819. * @param {string} name - The attribute name to delete.
  13820. * @return {BufferGeometry} A reference to this instance.
  13821. */
  13822. deleteAttribute( name ) {
  13823. delete this.attributes[ name ];
  13824. return this;
  13825. }
  13826. /**
  13827. * Returns `true` if this geometry has an attribute for the given name.
  13828. *
  13829. * @param {string} name - The attribute name.
  13830. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  13831. */
  13832. hasAttribute( name ) {
  13833. return this.attributes[ name ] !== undefined;
  13834. }
  13835. /**
  13836. * Adds a group to this geometry.
  13837. *
  13838. * @param {number} start - The first element in this draw call. That is the first
  13839. * vertex for non-indexed geometry, otherwise the first triangle index.
  13840. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  13841. * @param {number} [materialIndex=0] - The material array index to use.
  13842. */
  13843. addGroup( start, count, materialIndex = 0 ) {
  13844. this.groups.push( {
  13845. start: start,
  13846. count: count,
  13847. materialIndex: materialIndex
  13848. } );
  13849. }
  13850. /**
  13851. * Clears all groups.
  13852. */
  13853. clearGroups() {
  13854. this.groups = [];
  13855. }
  13856. /**
  13857. * Sets the draw range for this geometry.
  13858. *
  13859. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  13860. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  13861. * For indexed BufferGeometry, `count` is the number of indices to render.
  13862. */
  13863. setDrawRange( start, count ) {
  13864. this.drawRange.start = start;
  13865. this.drawRange.count = count;
  13866. }
  13867. /**
  13868. * Applies the given 4x4 transformation matrix to the geometry.
  13869. *
  13870. * @param {Matrix4} matrix - The matrix to apply.
  13871. * @return {BufferGeometry} A reference to this instance.
  13872. */
  13873. applyMatrix4( matrix ) {
  13874. const position = this.attributes.position;
  13875. if ( position !== undefined ) {
  13876. position.applyMatrix4( matrix );
  13877. position.needsUpdate = true;
  13878. }
  13879. const normal = this.attributes.normal;
  13880. if ( normal !== undefined ) {
  13881. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  13882. normal.applyNormalMatrix( normalMatrix );
  13883. normal.needsUpdate = true;
  13884. }
  13885. const tangent = this.attributes.tangent;
  13886. if ( tangent !== undefined ) {
  13887. tangent.transformDirection( matrix );
  13888. tangent.needsUpdate = true;
  13889. }
  13890. if ( this.boundingBox !== null ) {
  13891. this.computeBoundingBox();
  13892. }
  13893. if ( this.boundingSphere !== null ) {
  13894. this.computeBoundingSphere();
  13895. }
  13896. return this;
  13897. }
  13898. /**
  13899. * Applies the rotation represented by the Quaternion to the geometry.
  13900. *
  13901. * @param {Quaternion} q - The Quaternion to apply.
  13902. * @return {BufferGeometry} A reference to this instance.
  13903. */
  13904. applyQuaternion( q ) {
  13905. _m1$2.makeRotationFromQuaternion( q );
  13906. this.applyMatrix4( _m1$2 );
  13907. return this;
  13908. }
  13909. /**
  13910. * Rotates the geometry about the X axis. This is typically done as a one time
  13911. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13912. * real-time mesh rotation.
  13913. *
  13914. * @param {number} angle - The angle in radians.
  13915. * @return {BufferGeometry} A reference to this instance.
  13916. */
  13917. rotateX( angle ) {
  13918. // rotate geometry around world x-axis
  13919. _m1$2.makeRotationX( angle );
  13920. this.applyMatrix4( _m1$2 );
  13921. return this;
  13922. }
  13923. /**
  13924. * Rotates the geometry about the Y axis. This is typically done as a one time
  13925. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13926. * real-time mesh rotation.
  13927. *
  13928. * @param {number} angle - The angle in radians.
  13929. * @return {BufferGeometry} A reference to this instance.
  13930. */
  13931. rotateY( angle ) {
  13932. // rotate geometry around world y-axis
  13933. _m1$2.makeRotationY( angle );
  13934. this.applyMatrix4( _m1$2 );
  13935. return this;
  13936. }
  13937. /**
  13938. * Rotates the geometry about the Z axis. This is typically done as a one time
  13939. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13940. * real-time mesh rotation.
  13941. *
  13942. * @param {number} angle - The angle in radians.
  13943. * @return {BufferGeometry} A reference to this instance.
  13944. */
  13945. rotateZ( angle ) {
  13946. // rotate geometry around world z-axis
  13947. _m1$2.makeRotationZ( angle );
  13948. this.applyMatrix4( _m1$2 );
  13949. return this;
  13950. }
  13951. /**
  13952. * Translates the geometry. This is typically done as a one time
  13953. * operation, and not during a loop. Use {@link Object3D#position} for typical
  13954. * real-time mesh rotation.
  13955. *
  13956. * @param {number} x - The x offset.
  13957. * @param {number} y - The y offset.
  13958. * @param {number} z - The z offset.
  13959. * @return {BufferGeometry} A reference to this instance.
  13960. */
  13961. translate( x, y, z ) {
  13962. // translate geometry
  13963. _m1$2.makeTranslation( x, y, z );
  13964. this.applyMatrix4( _m1$2 );
  13965. return this;
  13966. }
  13967. /**
  13968. * Scales the geometry. This is typically done as a one time
  13969. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  13970. * real-time mesh rotation.
  13971. *
  13972. * @param {number} x - The x scale.
  13973. * @param {number} y - The y scale.
  13974. * @param {number} z - The z scale.
  13975. * @return {BufferGeometry} A reference to this instance.
  13976. */
  13977. scale( x, y, z ) {
  13978. // scale geometry
  13979. _m1$2.makeScale( x, y, z );
  13980. this.applyMatrix4( _m1$2 );
  13981. return this;
  13982. }
  13983. /**
  13984. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  13985. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  13986. * real-time mesh rotation.
  13987. *
  13988. * @param {Vector3} vector - The target point.
  13989. * @return {BufferGeometry} A reference to this instance.
  13990. */
  13991. lookAt( vector ) {
  13992. _obj.lookAt( vector );
  13993. _obj.updateMatrix();
  13994. this.applyMatrix4( _obj.matrix );
  13995. return this;
  13996. }
  13997. /**
  13998. * Center the geometry based on its bounding box.
  13999. *
  14000. * @return {BufferGeometry} A reference to this instance.
  14001. */
  14002. center() {
  14003. this.computeBoundingBox();
  14004. this.boundingBox.getCenter( _offset ).negate();
  14005. this.translate( _offset.x, _offset.y, _offset.z );
  14006. return this;
  14007. }
  14008. /**
  14009. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14010. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14011. * set to `0`.
  14012. *
  14013. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14014. * data from the array. The length of the array must match the vertex count.
  14015. *
  14016. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14017. * @return {BufferGeometry} A reference to this instance.
  14018. */
  14019. setFromPoints( points ) {
  14020. const positionAttribute = this.getAttribute( 'position' );
  14021. if ( positionAttribute === undefined ) {
  14022. const position = [];
  14023. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14024. const point = points[ i ];
  14025. position.push( point.x, point.y, point.z || 0 );
  14026. }
  14027. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14028. } else {
  14029. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14030. for ( let i = 0; i < l; i ++ ) {
  14031. const point = points[ i ];
  14032. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14033. }
  14034. if ( points.length > positionAttribute.count ) {
  14035. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14036. }
  14037. positionAttribute.needsUpdate = true;
  14038. }
  14039. return this;
  14040. }
  14041. /**
  14042. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14043. * The bounding box is not computed by the engine; it must be computed by your app.
  14044. * You may need to recompute the bounding box if the geometry vertices are modified.
  14045. */
  14046. computeBoundingBox() {
  14047. if ( this.boundingBox === null ) {
  14048. this.boundingBox = new Box3();
  14049. }
  14050. const position = this.attributes.position;
  14051. const morphAttributesPosition = this.morphAttributes.position;
  14052. if ( position && position.isGLBufferAttribute ) {
  14053. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14054. this.boundingBox.set(
  14055. new Vector3( - Infinity, - Infinity, - Infinity ),
  14056. new Vector3( + Infinity, + Infinity, + Infinity )
  14057. );
  14058. return;
  14059. }
  14060. if ( position !== undefined ) {
  14061. this.boundingBox.setFromBufferAttribute( position );
  14062. // process morph attributes if present
  14063. if ( morphAttributesPosition ) {
  14064. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14065. const morphAttribute = morphAttributesPosition[ i ];
  14066. _box$2.setFromBufferAttribute( morphAttribute );
  14067. if ( this.morphTargetsRelative ) {
  14068. _vector$9.addVectors( this.boundingBox.min, _box$2.min );
  14069. this.boundingBox.expandByPoint( _vector$9 );
  14070. _vector$9.addVectors( this.boundingBox.max, _box$2.max );
  14071. this.boundingBox.expandByPoint( _vector$9 );
  14072. } else {
  14073. this.boundingBox.expandByPoint( _box$2.min );
  14074. this.boundingBox.expandByPoint( _box$2.max );
  14075. }
  14076. }
  14077. }
  14078. } else {
  14079. this.boundingBox.makeEmpty();
  14080. }
  14081. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14082. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14083. }
  14084. }
  14085. /**
  14086. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14087. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14088. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14089. */
  14090. computeBoundingSphere() {
  14091. if ( this.boundingSphere === null ) {
  14092. this.boundingSphere = new Sphere();
  14093. }
  14094. const position = this.attributes.position;
  14095. const morphAttributesPosition = this.morphAttributes.position;
  14096. if ( position && position.isGLBufferAttribute ) {
  14097. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14098. this.boundingSphere.set( new Vector3(), Infinity );
  14099. return;
  14100. }
  14101. if ( position ) {
  14102. // first, find the center of the bounding sphere
  14103. const center = this.boundingSphere.center;
  14104. _box$2.setFromBufferAttribute( position );
  14105. // process morph attributes if present
  14106. if ( morphAttributesPosition ) {
  14107. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14108. const morphAttribute = morphAttributesPosition[ i ];
  14109. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14110. if ( this.morphTargetsRelative ) {
  14111. _vector$9.addVectors( _box$2.min, _boxMorphTargets.min );
  14112. _box$2.expandByPoint( _vector$9 );
  14113. _vector$9.addVectors( _box$2.max, _boxMorphTargets.max );
  14114. _box$2.expandByPoint( _vector$9 );
  14115. } else {
  14116. _box$2.expandByPoint( _boxMorphTargets.min );
  14117. _box$2.expandByPoint( _boxMorphTargets.max );
  14118. }
  14119. }
  14120. }
  14121. _box$2.getCenter( center );
  14122. // second, try to find a boundingSphere with a radius smaller than the
  14123. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14124. let maxRadiusSq = 0;
  14125. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14126. _vector$9.fromBufferAttribute( position, i );
  14127. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14128. }
  14129. // process morph attributes if present
  14130. if ( morphAttributesPosition ) {
  14131. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14132. const morphAttribute = morphAttributesPosition[ i ];
  14133. const morphTargetsRelative = this.morphTargetsRelative;
  14134. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14135. _vector$9.fromBufferAttribute( morphAttribute, j );
  14136. if ( morphTargetsRelative ) {
  14137. _offset.fromBufferAttribute( position, j );
  14138. _vector$9.add( _offset );
  14139. }
  14140. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14141. }
  14142. }
  14143. }
  14144. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14145. if ( isNaN( this.boundingSphere.radius ) ) {
  14146. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14147. }
  14148. }
  14149. }
  14150. /**
  14151. * Calculates and adds a tangent attribute to this geometry.
  14152. *
  14153. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14154. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14155. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14156. */
  14157. computeTangents() {
  14158. const index = this.index;
  14159. const attributes = this.attributes;
  14160. // based on http://www.terathon.com/code/tangent.html
  14161. // (per vertex tangents)
  14162. if ( index === null ||
  14163. attributes.position === undefined ||
  14164. attributes.normal === undefined ||
  14165. attributes.uv === undefined ) {
  14166. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14167. return;
  14168. }
  14169. const positionAttribute = attributes.position;
  14170. const normalAttribute = attributes.normal;
  14171. const uvAttribute = attributes.uv;
  14172. if ( this.hasAttribute( 'tangent' ) === false ) {
  14173. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14174. }
  14175. const tangentAttribute = this.getAttribute( 'tangent' );
  14176. const tan1 = [], tan2 = [];
  14177. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14178. tan1[ i ] = new Vector3();
  14179. tan2[ i ] = new Vector3();
  14180. }
  14181. const vA = new Vector3(),
  14182. vB = new Vector3(),
  14183. vC = new Vector3(),
  14184. uvA = new Vector2(),
  14185. uvB = new Vector2(),
  14186. uvC = new Vector2(),
  14187. sdir = new Vector3(),
  14188. tdir = new Vector3();
  14189. function handleTriangle( a, b, c ) {
  14190. vA.fromBufferAttribute( positionAttribute, a );
  14191. vB.fromBufferAttribute( positionAttribute, b );
  14192. vC.fromBufferAttribute( positionAttribute, c );
  14193. uvA.fromBufferAttribute( uvAttribute, a );
  14194. uvB.fromBufferAttribute( uvAttribute, b );
  14195. uvC.fromBufferAttribute( uvAttribute, c );
  14196. vB.sub( vA );
  14197. vC.sub( vA );
  14198. uvB.sub( uvA );
  14199. uvC.sub( uvA );
  14200. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14201. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14202. if ( ! isFinite( r ) ) return;
  14203. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14204. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14205. tan1[ a ].add( sdir );
  14206. tan1[ b ].add( sdir );
  14207. tan1[ c ].add( sdir );
  14208. tan2[ a ].add( tdir );
  14209. tan2[ b ].add( tdir );
  14210. tan2[ c ].add( tdir );
  14211. }
  14212. let groups = this.groups;
  14213. if ( groups.length === 0 ) {
  14214. groups = [ {
  14215. start: 0,
  14216. count: index.count
  14217. } ];
  14218. }
  14219. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14220. const group = groups[ i ];
  14221. const start = group.start;
  14222. const count = group.count;
  14223. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14224. handleTriangle(
  14225. index.getX( j + 0 ),
  14226. index.getX( j + 1 ),
  14227. index.getX( j + 2 )
  14228. );
  14229. }
  14230. }
  14231. const tmp = new Vector3(), tmp2 = new Vector3();
  14232. const n = new Vector3(), n2 = new Vector3();
  14233. function handleVertex( v ) {
  14234. n.fromBufferAttribute( normalAttribute, v );
  14235. n2.copy( n );
  14236. const t = tan1[ v ];
  14237. // Gram-Schmidt orthogonalize
  14238. tmp.copy( t );
  14239. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14240. // Calculate handedness
  14241. tmp2.crossVectors( n2, t );
  14242. const test = tmp2.dot( tan2[ v ] );
  14243. const w = ( test < 0.0 ) ? -1 : 1.0;
  14244. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14245. }
  14246. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14247. const group = groups[ i ];
  14248. const start = group.start;
  14249. const count = group.count;
  14250. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14251. handleVertex( index.getX( j + 0 ) );
  14252. handleVertex( index.getX( j + 1 ) );
  14253. handleVertex( index.getX( j + 2 ) );
  14254. }
  14255. }
  14256. }
  14257. /**
  14258. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14259. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14260. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14261. * to be the same as the face normal.
  14262. */
  14263. computeVertexNormals() {
  14264. const index = this.index;
  14265. const positionAttribute = this.getAttribute( 'position' );
  14266. if ( positionAttribute !== undefined ) {
  14267. let normalAttribute = this.getAttribute( 'normal' );
  14268. if ( normalAttribute === undefined ) {
  14269. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14270. this.setAttribute( 'normal', normalAttribute );
  14271. } else {
  14272. // reset existing normals to zero
  14273. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14274. normalAttribute.setXYZ( i, 0, 0, 0 );
  14275. }
  14276. }
  14277. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14278. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14279. const cb = new Vector3(), ab = new Vector3();
  14280. // indexed elements
  14281. if ( index ) {
  14282. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14283. const vA = index.getX( i + 0 );
  14284. const vB = index.getX( i + 1 );
  14285. const vC = index.getX( i + 2 );
  14286. pA.fromBufferAttribute( positionAttribute, vA );
  14287. pB.fromBufferAttribute( positionAttribute, vB );
  14288. pC.fromBufferAttribute( positionAttribute, vC );
  14289. cb.subVectors( pC, pB );
  14290. ab.subVectors( pA, pB );
  14291. cb.cross( ab );
  14292. nA.fromBufferAttribute( normalAttribute, vA );
  14293. nB.fromBufferAttribute( normalAttribute, vB );
  14294. nC.fromBufferAttribute( normalAttribute, vC );
  14295. nA.add( cb );
  14296. nB.add( cb );
  14297. nC.add( cb );
  14298. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14299. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14300. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14301. }
  14302. } else {
  14303. // non-indexed elements (unconnected triangle soup)
  14304. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14305. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14306. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14307. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14308. cb.subVectors( pC, pB );
  14309. ab.subVectors( pA, pB );
  14310. cb.cross( ab );
  14311. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14312. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14313. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14314. }
  14315. }
  14316. this.normalizeNormals();
  14317. normalAttribute.needsUpdate = true;
  14318. }
  14319. }
  14320. /**
  14321. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14322. * correct lighting on the geometry surfaces.
  14323. */
  14324. normalizeNormals() {
  14325. const normals = this.attributes.normal;
  14326. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14327. _vector$9.fromBufferAttribute( normals, i );
  14328. _vector$9.normalize();
  14329. normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  14330. }
  14331. }
  14332. /**
  14333. * Return a new non-index version of this indexed geometry. If the geometry
  14334. * is already non-indexed, the method is a NOOP.
  14335. *
  14336. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14337. */
  14338. toNonIndexed() {
  14339. function convertBufferAttribute( attribute, indices ) {
  14340. const array = attribute.array;
  14341. const itemSize = attribute.itemSize;
  14342. const normalized = attribute.normalized;
  14343. const array2 = new array.constructor( indices.length * itemSize );
  14344. let index = 0, index2 = 0;
  14345. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14346. if ( attribute.isInterleavedBufferAttribute ) {
  14347. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14348. } else {
  14349. index = indices[ i ] * itemSize;
  14350. }
  14351. for ( let j = 0; j < itemSize; j ++ ) {
  14352. array2[ index2 ++ ] = array[ index ++ ];
  14353. }
  14354. }
  14355. return new BufferAttribute( array2, itemSize, normalized );
  14356. }
  14357. //
  14358. if ( this.index === null ) {
  14359. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14360. return this;
  14361. }
  14362. const geometry2 = new BufferGeometry();
  14363. const indices = this.index.array;
  14364. const attributes = this.attributes;
  14365. // attributes
  14366. for ( const name in attributes ) {
  14367. const attribute = attributes[ name ];
  14368. const newAttribute = convertBufferAttribute( attribute, indices );
  14369. geometry2.setAttribute( name, newAttribute );
  14370. }
  14371. // morph attributes
  14372. const morphAttributes = this.morphAttributes;
  14373. for ( const name in morphAttributes ) {
  14374. const morphArray = [];
  14375. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14376. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14377. const attribute = morphAttribute[ i ];
  14378. const newAttribute = convertBufferAttribute( attribute, indices );
  14379. morphArray.push( newAttribute );
  14380. }
  14381. geometry2.morphAttributes[ name ] = morphArray;
  14382. }
  14383. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14384. // groups
  14385. const groups = this.groups;
  14386. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14387. const group = groups[ i ];
  14388. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14389. }
  14390. return geometry2;
  14391. }
  14392. /**
  14393. * Serializes the geometry into JSON.
  14394. *
  14395. * @return {Object} A JSON object representing the serialized geometry.
  14396. */
  14397. toJSON() {
  14398. const data = {
  14399. metadata: {
  14400. version: 4.7,
  14401. type: 'BufferGeometry',
  14402. generator: 'BufferGeometry.toJSON'
  14403. }
  14404. };
  14405. // standard BufferGeometry serialization
  14406. data.uuid = this.uuid;
  14407. data.type = this.type;
  14408. if ( this.name !== '' ) data.name = this.name;
  14409. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14410. if ( this.parameters !== undefined ) {
  14411. const parameters = this.parameters;
  14412. for ( const key in parameters ) {
  14413. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14414. }
  14415. return data;
  14416. }
  14417. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14418. data.data = { attributes: {} };
  14419. const index = this.index;
  14420. if ( index !== null ) {
  14421. data.data.index = {
  14422. type: index.array.constructor.name,
  14423. array: Array.prototype.slice.call( index.array )
  14424. };
  14425. }
  14426. const attributes = this.attributes;
  14427. for ( const key in attributes ) {
  14428. const attribute = attributes[ key ];
  14429. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14430. }
  14431. const morphAttributes = {};
  14432. let hasMorphAttributes = false;
  14433. for ( const key in this.morphAttributes ) {
  14434. const attributeArray = this.morphAttributes[ key ];
  14435. const array = [];
  14436. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14437. const attribute = attributeArray[ i ];
  14438. array.push( attribute.toJSON( data.data ) );
  14439. }
  14440. if ( array.length > 0 ) {
  14441. morphAttributes[ key ] = array;
  14442. hasMorphAttributes = true;
  14443. }
  14444. }
  14445. if ( hasMorphAttributes ) {
  14446. data.data.morphAttributes = morphAttributes;
  14447. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14448. }
  14449. const groups = this.groups;
  14450. if ( groups.length > 0 ) {
  14451. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14452. }
  14453. const boundingSphere = this.boundingSphere;
  14454. if ( boundingSphere !== null ) {
  14455. data.data.boundingSphere = boundingSphere.toJSON();
  14456. }
  14457. return data;
  14458. }
  14459. /**
  14460. * Returns a new geometry with copied values from this instance.
  14461. *
  14462. * @return {BufferGeometry} A clone of this instance.
  14463. */
  14464. clone() {
  14465. return new this.constructor().copy( this );
  14466. }
  14467. /**
  14468. * Copies the values of the given geometry to this instance.
  14469. *
  14470. * @param {BufferGeometry} source - The geometry to copy.
  14471. * @return {BufferGeometry} A reference to this instance.
  14472. */
  14473. copy( source ) {
  14474. // reset
  14475. this.index = null;
  14476. this.attributes = {};
  14477. this.morphAttributes = {};
  14478. this.groups = [];
  14479. this.boundingBox = null;
  14480. this.boundingSphere = null;
  14481. // used for storing cloned, shared data
  14482. const data = {};
  14483. // name
  14484. this.name = source.name;
  14485. // index
  14486. const index = source.index;
  14487. if ( index !== null ) {
  14488. this.setIndex( index.clone() );
  14489. }
  14490. // attributes
  14491. const attributes = source.attributes;
  14492. for ( const name in attributes ) {
  14493. const attribute = attributes[ name ];
  14494. this.setAttribute( name, attribute.clone( data ) );
  14495. }
  14496. // morph attributes
  14497. const morphAttributes = source.morphAttributes;
  14498. for ( const name in morphAttributes ) {
  14499. const array = [];
  14500. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14501. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14502. array.push( morphAttribute[ i ].clone( data ) );
  14503. }
  14504. this.morphAttributes[ name ] = array;
  14505. }
  14506. this.morphTargetsRelative = source.morphTargetsRelative;
  14507. // groups
  14508. const groups = source.groups;
  14509. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14510. const group = groups[ i ];
  14511. this.addGroup( group.start, group.count, group.materialIndex );
  14512. }
  14513. // bounding box
  14514. const boundingBox = source.boundingBox;
  14515. if ( boundingBox !== null ) {
  14516. this.boundingBox = boundingBox.clone();
  14517. }
  14518. // bounding sphere
  14519. const boundingSphere = source.boundingSphere;
  14520. if ( boundingSphere !== null ) {
  14521. this.boundingSphere = boundingSphere.clone();
  14522. }
  14523. // draw range
  14524. this.drawRange.start = source.drawRange.start;
  14525. this.drawRange.count = source.drawRange.count;
  14526. // user data
  14527. this.userData = source.userData;
  14528. return this;
  14529. }
  14530. /**
  14531. * Frees the GPU-related resources allocated by this instance. Call this
  14532. * method whenever this instance is no longer used in your app.
  14533. *
  14534. * @fires BufferGeometry#dispose
  14535. */
  14536. dispose() {
  14537. this.dispatchEvent( { type: 'dispose' } );
  14538. }
  14539. }
  14540. /**
  14541. * "Interleaved" means that multiple attributes, possibly of different types,
  14542. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  14543. *
  14544. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  14545. */
  14546. class InterleavedBuffer {
  14547. /**
  14548. * Constructs a new interleaved buffer.
  14549. *
  14550. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  14551. * @param {number} stride - The number of typed-array elements per vertex.
  14552. */
  14553. constructor( array, stride ) {
  14554. /**
  14555. * This flag can be used for type testing.
  14556. *
  14557. * @type {boolean}
  14558. * @readonly
  14559. * @default true
  14560. */
  14561. this.isInterleavedBuffer = true;
  14562. /**
  14563. * A typed array with a shared buffer storing attribute data.
  14564. *
  14565. * @type {TypedArray}
  14566. */
  14567. this.array = array;
  14568. /**
  14569. * The number of typed-array elements per vertex.
  14570. *
  14571. * @type {number}
  14572. */
  14573. this.stride = stride;
  14574. /**
  14575. * The total number of elements in the array
  14576. *
  14577. * @type {number}
  14578. * @readonly
  14579. */
  14580. this.count = array !== undefined ? array.length / stride : 0;
  14581. /**
  14582. * Defines the intended usage pattern of the data store for optimization purposes.
  14583. *
  14584. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  14585. * instantiate a new one and set the desired usage before the next render.
  14586. *
  14587. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  14588. * @default StaticDrawUsage
  14589. */
  14590. this.usage = StaticDrawUsage;
  14591. /**
  14592. * This can be used to only update some components of stored vectors (for example, just the
  14593. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  14594. *
  14595. * @type {Array<Object>}
  14596. */
  14597. this.updateRanges = [];
  14598. /**
  14599. * A version number, incremented every time the `needsUpdate` is set to `true`.
  14600. *
  14601. * @type {number}
  14602. */
  14603. this.version = 0;
  14604. /**
  14605. * The UUID of the interleaved buffer.
  14606. *
  14607. * @type {string}
  14608. * @readonly
  14609. */
  14610. this.uuid = generateUUID();
  14611. }
  14612. /**
  14613. * A callback function that is executed after the renderer has transferred the attribute array
  14614. * data to the GPU.
  14615. */
  14616. onUploadCallback() {}
  14617. /**
  14618. * Flag to indicate that this attribute has changed and should be re-sent to
  14619. * the GPU. Set this to `true` when you modify the value of the array.
  14620. *
  14621. * @type {number}
  14622. * @default false
  14623. * @param {boolean} value
  14624. */
  14625. set needsUpdate( value ) {
  14626. if ( value === true ) this.version ++;
  14627. }
  14628. /**
  14629. * Sets the usage of this interleaved buffer.
  14630. *
  14631. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  14632. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  14633. */
  14634. setUsage( value ) {
  14635. this.usage = value;
  14636. return this;
  14637. }
  14638. /**
  14639. * Adds a range of data in the data array to be updated on the GPU.
  14640. *
  14641. * @param {number} start - Position at which to start update.
  14642. * @param {number} count - The number of components to update.
  14643. */
  14644. addUpdateRange( start, count ) {
  14645. this.updateRanges.push( { start, count } );
  14646. }
  14647. /**
  14648. * Clears the update ranges.
  14649. */
  14650. clearUpdateRanges() {
  14651. this.updateRanges.length = 0;
  14652. }
  14653. /**
  14654. * Copies the values of the given interleaved buffer to this instance.
  14655. *
  14656. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  14657. * @return {InterleavedBuffer} A reference to this instance.
  14658. */
  14659. copy( source ) {
  14660. this.array = new source.array.constructor( source.array );
  14661. this.count = source.count;
  14662. this.stride = source.stride;
  14663. this.usage = source.usage;
  14664. return this;
  14665. }
  14666. /**
  14667. * Copies a vector from the given interleaved buffer to this one. The start
  14668. * and destination position in the attribute buffers are represented by the
  14669. * given indices.
  14670. *
  14671. * @param {number} index1 - The destination index into this interleaved buffer.
  14672. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  14673. * @param {number} index2 - The source index into the given interleaved buffer.
  14674. * @return {InterleavedBuffer} A reference to this instance.
  14675. */
  14676. copyAt( index1, interleavedBuffer, index2 ) {
  14677. index1 *= this.stride;
  14678. index2 *= interleavedBuffer.stride;
  14679. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  14680. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  14681. }
  14682. return this;
  14683. }
  14684. /**
  14685. * Sets the given array data in the interleaved buffer.
  14686. *
  14687. * @param {(TypedArray|Array)} value - The array data to set.
  14688. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  14689. * @return {InterleavedBuffer} A reference to this instance.
  14690. */
  14691. set( value, offset = 0 ) {
  14692. this.array.set( value, offset );
  14693. return this;
  14694. }
  14695. /**
  14696. * Returns a new interleaved buffer with copied values from this instance.
  14697. *
  14698. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  14699. * @return {InterleavedBuffer} A clone of this instance.
  14700. */
  14701. clone( data ) {
  14702. if ( data.arrayBuffers === undefined ) {
  14703. data.arrayBuffers = {};
  14704. }
  14705. if ( this.array.buffer._uuid === undefined ) {
  14706. this.array.buffer._uuid = generateUUID();
  14707. }
  14708. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14709. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  14710. }
  14711. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  14712. const ib = new this.constructor( array, this.stride );
  14713. ib.setUsage( this.usage );
  14714. return ib;
  14715. }
  14716. /**
  14717. * Sets the given callback function that is executed after the Renderer has transferred
  14718. * the array data to the GPU. Can be used to perform clean-up operations after
  14719. * the upload when data are not needed anymore on the CPU side.
  14720. *
  14721. * @param {Function} callback - The `onUpload()` callback.
  14722. * @return {InterleavedBuffer} A reference to this instance.
  14723. */
  14724. onUpload( callback ) {
  14725. this.onUploadCallback = callback;
  14726. return this;
  14727. }
  14728. /**
  14729. * Serializes the interleaved buffer into JSON.
  14730. *
  14731. * @param {Object} [data] - An optional value holding meta information about the serialization.
  14732. * @return {Object} A JSON object representing the serialized interleaved buffer.
  14733. */
  14734. toJSON( data ) {
  14735. if ( data.arrayBuffers === undefined ) {
  14736. data.arrayBuffers = {};
  14737. }
  14738. // generate UUID for array buffer if necessary
  14739. if ( this.array.buffer._uuid === undefined ) {
  14740. this.array.buffer._uuid = generateUUID();
  14741. }
  14742. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14743. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  14744. }
  14745. //
  14746. return {
  14747. uuid: this.uuid,
  14748. buffer: this.array.buffer._uuid,
  14749. type: this.array.constructor.name,
  14750. stride: this.stride
  14751. };
  14752. }
  14753. }
  14754. const _vector$8 = /*@__PURE__*/ new Vector3();
  14755. /**
  14756. * An alternative version of a buffer attribute with interleaved data. Interleaved
  14757. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  14758. * different offsets into the buffer.
  14759. */
  14760. class InterleavedBufferAttribute {
  14761. /**
  14762. * Constructs a new interleaved buffer attribute.
  14763. *
  14764. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  14765. * @param {number} itemSize - The item size.
  14766. * @param {number} offset - The attribute offset into the buffer.
  14767. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14768. */
  14769. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  14770. /**
  14771. * This flag can be used for type testing.
  14772. *
  14773. * @type {boolean}
  14774. * @readonly
  14775. * @default true
  14776. */
  14777. this.isInterleavedBufferAttribute = true;
  14778. /**
  14779. * The name of the buffer attribute.
  14780. *
  14781. * @type {string}
  14782. */
  14783. this.name = '';
  14784. /**
  14785. * The buffer holding the interleaved data.
  14786. *
  14787. * @type {InterleavedBuffer}
  14788. */
  14789. this.data = interleavedBuffer;
  14790. /**
  14791. * The item size, see {@link BufferAttribute#itemSize}.
  14792. *
  14793. * @type {number}
  14794. */
  14795. this.itemSize = itemSize;
  14796. /**
  14797. * The attribute offset into the buffer.
  14798. *
  14799. * @type {number}
  14800. */
  14801. this.offset = offset;
  14802. /**
  14803. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  14804. *
  14805. * @type {InterleavedBuffer}
  14806. */
  14807. this.normalized = normalized;
  14808. }
  14809. /**
  14810. * The item count of this buffer attribute.
  14811. *
  14812. * @type {number}
  14813. * @readonly
  14814. */
  14815. get count() {
  14816. return this.data.count;
  14817. }
  14818. /**
  14819. * The array holding the interleaved buffer attribute data.
  14820. *
  14821. * @type {TypedArray}
  14822. */
  14823. get array() {
  14824. return this.data.array;
  14825. }
  14826. /**
  14827. * Flag to indicate that this attribute has changed and should be re-sent to
  14828. * the GPU. Set this to `true` when you modify the value of the array.
  14829. *
  14830. * @type {number}
  14831. * @default false
  14832. * @param {boolean} value
  14833. */
  14834. set needsUpdate( value ) {
  14835. this.data.needsUpdate = value;
  14836. }
  14837. /**
  14838. * Applies the given 4x4 matrix to the given attribute. Only works with
  14839. * item size `3`.
  14840. *
  14841. * @param {Matrix4} m - The matrix to apply.
  14842. * @return {InterleavedBufferAttribute} A reference to this instance.
  14843. */
  14844. applyMatrix4( m ) {
  14845. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  14846. _vector$8.fromBufferAttribute( this, i );
  14847. _vector$8.applyMatrix4( m );
  14848. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14849. }
  14850. return this;
  14851. }
  14852. /**
  14853. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  14854. * item size `3`.
  14855. *
  14856. * @param {Matrix3} m - The normal matrix to apply.
  14857. * @return {InterleavedBufferAttribute} A reference to this instance.
  14858. */
  14859. applyNormalMatrix( m ) {
  14860. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14861. _vector$8.fromBufferAttribute( this, i );
  14862. _vector$8.applyNormalMatrix( m );
  14863. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14864. }
  14865. return this;
  14866. }
  14867. /**
  14868. * Applies the given 4x4 matrix to the given attribute. Only works with
  14869. * item size `3` and with direction vectors.
  14870. *
  14871. * @param {Matrix4} m - The matrix to apply.
  14872. * @return {InterleavedBufferAttribute} A reference to this instance.
  14873. */
  14874. transformDirection( m ) {
  14875. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14876. _vector$8.fromBufferAttribute( this, i );
  14877. _vector$8.transformDirection( m );
  14878. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14879. }
  14880. return this;
  14881. }
  14882. /**
  14883. * Returns the given component of the vector at the given index.
  14884. *
  14885. * @param {number} index - The index into the buffer attribute.
  14886. * @param {number} component - The component index.
  14887. * @return {number} The returned value.
  14888. */
  14889. getComponent( index, component ) {
  14890. let value = this.array[ index * this.data.stride + this.offset + component ];
  14891. if ( this.normalized ) value = denormalize( value, this.array );
  14892. return value;
  14893. }
  14894. /**
  14895. * Sets the given value to the given component of the vector at the given index.
  14896. *
  14897. * @param {number} index - The index into the buffer attribute.
  14898. * @param {number} component - The component index.
  14899. * @param {number} value - The value to set.
  14900. * @return {InterleavedBufferAttribute} A reference to this instance.
  14901. */
  14902. setComponent( index, component, value ) {
  14903. if ( this.normalized ) value = normalize( value, this.array );
  14904. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  14905. return this;
  14906. }
  14907. /**
  14908. * Sets the x component of the vector at the given index.
  14909. *
  14910. * @param {number} index - The index into the buffer attribute.
  14911. * @param {number} x - The value to set.
  14912. * @return {InterleavedBufferAttribute} A reference to this instance.
  14913. */
  14914. setX( index, x ) {
  14915. if ( this.normalized ) x = normalize( x, this.array );
  14916. this.data.array[ index * this.data.stride + this.offset ] = x;
  14917. return this;
  14918. }
  14919. /**
  14920. * Sets the y component of the vector at the given index.
  14921. *
  14922. * @param {number} index - The index into the buffer attribute.
  14923. * @param {number} y - The value to set.
  14924. * @return {InterleavedBufferAttribute} A reference to this instance.
  14925. */
  14926. setY( index, y ) {
  14927. if ( this.normalized ) y = normalize( y, this.array );
  14928. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  14929. return this;
  14930. }
  14931. /**
  14932. * Sets the z component of the vector at the given index.
  14933. *
  14934. * @param {number} index - The index into the buffer attribute.
  14935. * @param {number} z - The value to set.
  14936. * @return {InterleavedBufferAttribute} A reference to this instance.
  14937. */
  14938. setZ( index, z ) {
  14939. if ( this.normalized ) z = normalize( z, this.array );
  14940. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  14941. return this;
  14942. }
  14943. /**
  14944. * Sets the w component of the vector at the given index.
  14945. *
  14946. * @param {number} index - The index into the buffer attribute.
  14947. * @param {number} w - The value to set.
  14948. * @return {InterleavedBufferAttribute} A reference to this instance.
  14949. */
  14950. setW( index, w ) {
  14951. if ( this.normalized ) w = normalize( w, this.array );
  14952. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  14953. return this;
  14954. }
  14955. /**
  14956. * Returns the x component of the vector at the given index.
  14957. *
  14958. * @param {number} index - The index into the buffer attribute.
  14959. * @return {number} The x component.
  14960. */
  14961. getX( index ) {
  14962. let x = this.data.array[ index * this.data.stride + this.offset ];
  14963. if ( this.normalized ) x = denormalize( x, this.array );
  14964. return x;
  14965. }
  14966. /**
  14967. * Returns the y component of the vector at the given index.
  14968. *
  14969. * @param {number} index - The index into the buffer attribute.
  14970. * @return {number} The y component.
  14971. */
  14972. getY( index ) {
  14973. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  14974. if ( this.normalized ) y = denormalize( y, this.array );
  14975. return y;
  14976. }
  14977. /**
  14978. * Returns the z component of the vector at the given index.
  14979. *
  14980. * @param {number} index - The index into the buffer attribute.
  14981. * @return {number} The z component.
  14982. */
  14983. getZ( index ) {
  14984. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  14985. if ( this.normalized ) z = denormalize( z, this.array );
  14986. return z;
  14987. }
  14988. /**
  14989. * Returns the w component of the vector at the given index.
  14990. *
  14991. * @param {number} index - The index into the buffer attribute.
  14992. * @return {number} The w component.
  14993. */
  14994. getW( index ) {
  14995. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  14996. if ( this.normalized ) w = denormalize( w, this.array );
  14997. return w;
  14998. }
  14999. /**
  15000. * Sets the x and y component of the vector at the given index.
  15001. *
  15002. * @param {number} index - The index into the buffer attribute.
  15003. * @param {number} x - The value for the x component to set.
  15004. * @param {number} y - The value for the y component to set.
  15005. * @return {InterleavedBufferAttribute} A reference to this instance.
  15006. */
  15007. setXY( index, x, y ) {
  15008. index = index * this.data.stride + this.offset;
  15009. if ( this.normalized ) {
  15010. x = normalize( x, this.array );
  15011. y = normalize( y, this.array );
  15012. }
  15013. this.data.array[ index + 0 ] = x;
  15014. this.data.array[ index + 1 ] = y;
  15015. return this;
  15016. }
  15017. /**
  15018. * Sets the x, y and z component of the vector at the given index.
  15019. *
  15020. * @param {number} index - The index into the buffer attribute.
  15021. * @param {number} x - The value for the x component to set.
  15022. * @param {number} y - The value for the y component to set.
  15023. * @param {number} z - The value for the z component to set.
  15024. * @return {InterleavedBufferAttribute} A reference to this instance.
  15025. */
  15026. setXYZ( index, x, y, z ) {
  15027. index = index * this.data.stride + this.offset;
  15028. if ( this.normalized ) {
  15029. x = normalize( x, this.array );
  15030. y = normalize( y, this.array );
  15031. z = normalize( z, this.array );
  15032. }
  15033. this.data.array[ index + 0 ] = x;
  15034. this.data.array[ index + 1 ] = y;
  15035. this.data.array[ index + 2 ] = z;
  15036. return this;
  15037. }
  15038. /**
  15039. * Sets the x, y, z and w component of the vector at the given index.
  15040. *
  15041. * @param {number} index - The index into the buffer attribute.
  15042. * @param {number} x - The value for the x component to set.
  15043. * @param {number} y - The value for the y component to set.
  15044. * @param {number} z - The value for the z component to set.
  15045. * @param {number} w - The value for the w component to set.
  15046. * @return {InterleavedBufferAttribute} A reference to this instance.
  15047. */
  15048. setXYZW( index, x, y, z, w ) {
  15049. index = index * this.data.stride + this.offset;
  15050. if ( this.normalized ) {
  15051. x = normalize( x, this.array );
  15052. y = normalize( y, this.array );
  15053. z = normalize( z, this.array );
  15054. w = normalize( w, this.array );
  15055. }
  15056. this.data.array[ index + 0 ] = x;
  15057. this.data.array[ index + 1 ] = y;
  15058. this.data.array[ index + 2 ] = z;
  15059. this.data.array[ index + 3 ] = w;
  15060. return this;
  15061. }
  15062. /**
  15063. * Returns a new buffer attribute with copied values from this instance.
  15064. *
  15065. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15066. *
  15067. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  15068. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  15069. */
  15070. clone( data ) {
  15071. if ( data === undefined ) {
  15072. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  15073. const array = [];
  15074. for ( let i = 0; i < this.count; i ++ ) {
  15075. const index = i * this.data.stride + this.offset;
  15076. for ( let j = 0; j < this.itemSize; j ++ ) {
  15077. array.push( this.data.array[ index + j ] );
  15078. }
  15079. }
  15080. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15081. } else {
  15082. if ( data.interleavedBuffers === undefined ) {
  15083. data.interleavedBuffers = {};
  15084. }
  15085. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15086. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15087. }
  15088. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15089. }
  15090. }
  15091. /**
  15092. * Serializes the buffer attribute into JSON.
  15093. *
  15094. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15095. *
  15096. * @param {Object} [data] - An optional value holding meta information about the serialization.
  15097. * @return {Object} A JSON object representing the serialized buffer attribute.
  15098. */
  15099. toJSON( data ) {
  15100. if ( data === undefined ) {
  15101. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  15102. const array = [];
  15103. for ( let i = 0; i < this.count; i ++ ) {
  15104. const index = i * this.data.stride + this.offset;
  15105. for ( let j = 0; j < this.itemSize; j ++ ) {
  15106. array.push( this.data.array[ index + j ] );
  15107. }
  15108. }
  15109. // de-interleave data and save it as an ordinary buffer attribute for now
  15110. return {
  15111. itemSize: this.itemSize,
  15112. type: this.array.constructor.name,
  15113. array: array,
  15114. normalized: this.normalized
  15115. };
  15116. } else {
  15117. // save as true interleaved attribute
  15118. if ( data.interleavedBuffers === undefined ) {
  15119. data.interleavedBuffers = {};
  15120. }
  15121. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15122. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15123. }
  15124. return {
  15125. isInterleavedBufferAttribute: true,
  15126. itemSize: this.itemSize,
  15127. data: this.data.uuid,
  15128. offset: this.offset,
  15129. normalized: this.normalized
  15130. };
  15131. }
  15132. }
  15133. }
  15134. let _materialId = 0;
  15135. /**
  15136. * Abstract base class for materials.
  15137. *
  15138. * Materials define the appearance of renderable 3D objects.
  15139. *
  15140. * @abstract
  15141. * @augments EventDispatcher
  15142. */
  15143. class Material extends EventDispatcher {
  15144. /**
  15145. * Constructs a new material.
  15146. */
  15147. constructor() {
  15148. super();
  15149. /**
  15150. * This flag can be used for type testing.
  15151. *
  15152. * @type {boolean}
  15153. * @readonly
  15154. * @default true
  15155. */
  15156. this.isMaterial = true;
  15157. /**
  15158. * The ID of the material.
  15159. *
  15160. * @name Material#id
  15161. * @type {number}
  15162. * @readonly
  15163. */
  15164. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  15165. /**
  15166. * The UUID of the material.
  15167. *
  15168. * @type {string}
  15169. * @readonly
  15170. */
  15171. this.uuid = generateUUID();
  15172. /**
  15173. * The name of the material.
  15174. *
  15175. * @type {string}
  15176. */
  15177. this.name = '';
  15178. /**
  15179. * The type property is used for detecting the object type
  15180. * in context of serialization/deserialization.
  15181. *
  15182. * @type {string}
  15183. * @readonly
  15184. */
  15185. this.type = 'Material';
  15186. /**
  15187. * Defines the blending type of the material.
  15188. *
  15189. * It must be set to `CustomBlending` if custom blending properties like
  15190. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  15191. * should have any effect.
  15192. *
  15193. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  15194. * @default NormalBlending
  15195. */
  15196. this.blending = NormalBlending;
  15197. /**
  15198. * Defines which side of faces will be rendered - front, back or both.
  15199. *
  15200. * @type {(FrontSide|BackSide|DoubleSide)}
  15201. * @default FrontSide
  15202. */
  15203. this.side = FrontSide;
  15204. /**
  15205. * If set to `true`, vertex colors should be used.
  15206. *
  15207. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  15208. * four (RGBA) component color buffer attribute is used.
  15209. *
  15210. * @type {boolean}
  15211. * @default false
  15212. */
  15213. this.vertexColors = false;
  15214. /**
  15215. * Defines how transparent the material is.
  15216. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  15217. *
  15218. * If the {@link Material#transparent} is not set to `true`,
  15219. * the material will remain fully opaque and this value will only affect its color.
  15220. *
  15221. * @type {number}
  15222. * @default 1
  15223. */
  15224. this.opacity = 1;
  15225. /**
  15226. * Defines whether this material is transparent. This has an effect on
  15227. * rendering as transparent objects need special treatment and are rendered
  15228. * after non-transparent objects.
  15229. *
  15230. * When set to true, the extent to which the material is transparent is
  15231. * controlled by {@link Material#opacity}.
  15232. *
  15233. * @type {boolean}
  15234. * @default false
  15235. */
  15236. this.transparent = false;
  15237. /**
  15238. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  15239. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  15240. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  15241. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  15242. *
  15243. * @type {boolean}
  15244. * @default false
  15245. */
  15246. this.alphaHash = false;
  15247. /**
  15248. * Defines the blending source factor.
  15249. *
  15250. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15251. * @default SrcAlphaFactor
  15252. */
  15253. this.blendSrc = SrcAlphaFactor;
  15254. /**
  15255. * Defines the blending destination factor.
  15256. *
  15257. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15258. * @default OneMinusSrcAlphaFactor
  15259. */
  15260. this.blendDst = OneMinusSrcAlphaFactor;
  15261. /**
  15262. * Defines the blending equation.
  15263. *
  15264. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15265. * @default AddEquation
  15266. */
  15267. this.blendEquation = AddEquation;
  15268. /**
  15269. * Defines the blending source alpha factor.
  15270. *
  15271. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15272. * @default null
  15273. */
  15274. this.blendSrcAlpha = null;
  15275. /**
  15276. * Defines the blending destination alpha factor.
  15277. *
  15278. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15279. * @default null
  15280. */
  15281. this.blendDstAlpha = null;
  15282. /**
  15283. * Defines the blending equation of the alpha channel.
  15284. *
  15285. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15286. * @default null
  15287. */
  15288. this.blendEquationAlpha = null;
  15289. /**
  15290. * Represents the RGB values of the constant blend color.
  15291. *
  15292. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  15293. *
  15294. * @type {Color}
  15295. * @default (0,0,0)
  15296. */
  15297. this.blendColor = new Color( 0, 0, 0 );
  15298. /**
  15299. * Represents the alpha value of the constant blend color.
  15300. *
  15301. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  15302. *
  15303. * @type {number}
  15304. * @default 0
  15305. */
  15306. this.blendAlpha = 0;
  15307. /**
  15308. * Defines the depth function.
  15309. *
  15310. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  15311. * @default LessEqualDepth
  15312. */
  15313. this.depthFunc = LessEqualDepth;
  15314. /**
  15315. * Whether to have depth test enabled when rendering this material.
  15316. * When the depth test is disabled, the depth write will also be implicitly disabled.
  15317. *
  15318. * @type {boolean}
  15319. * @default true
  15320. */
  15321. this.depthTest = true;
  15322. /**
  15323. * Whether rendering this material has any effect on the depth buffer.
  15324. *
  15325. * When drawing 2D overlays it can be useful to disable the depth writing in
  15326. * order to layer several things together without creating z-index artifacts.
  15327. *
  15328. * @type {boolean}
  15329. * @default true
  15330. */
  15331. this.depthWrite = true;
  15332. /**
  15333. * The bit mask to use when writing to the stencil buffer.
  15334. *
  15335. * @type {number}
  15336. * @default 0xff
  15337. */
  15338. this.stencilWriteMask = 0xff;
  15339. /**
  15340. * The stencil comparison function to use.
  15341. *
  15342. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  15343. * @default AlwaysStencilFunc
  15344. */
  15345. this.stencilFunc = AlwaysStencilFunc;
  15346. /**
  15347. * The value to use when performing stencil comparisons or stencil operations.
  15348. *
  15349. * @type {number}
  15350. * @default 0
  15351. */
  15352. this.stencilRef = 0;
  15353. /**
  15354. * The bit mask to use when comparing against the stencil buffer.
  15355. *
  15356. * @type {number}
  15357. * @default 0xff
  15358. */
  15359. this.stencilFuncMask = 0xff;
  15360. /**
  15361. * Which stencil operation to perform when the comparison function returns `false`.
  15362. *
  15363. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15364. * @default KeepStencilOp
  15365. */
  15366. this.stencilFail = KeepStencilOp;
  15367. /**
  15368. * Which stencil operation to perform when the comparison function returns
  15369. * `true` but the depth test fails.
  15370. *
  15371. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15372. * @default KeepStencilOp
  15373. */
  15374. this.stencilZFail = KeepStencilOp;
  15375. /**
  15376. * Which stencil operation to perform when the comparison function returns
  15377. * `true` and the depth test passes.
  15378. *
  15379. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15380. * @default KeepStencilOp
  15381. */
  15382. this.stencilZPass = KeepStencilOp;
  15383. /**
  15384. * Whether stencil operations are performed against the stencil buffer. In
  15385. * order to perform writes or comparisons against the stencil buffer this
  15386. * value must be `true`.
  15387. *
  15388. * @type {boolean}
  15389. * @default false
  15390. */
  15391. this.stencilWrite = false;
  15392. /**
  15393. * User-defined clipping planes specified as THREE.Plane objects in world
  15394. * space. These planes apply to the objects this material is attached to.
  15395. * Points in space whose signed distance to the plane is negative are clipped
  15396. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  15397. * be `true`.
  15398. *
  15399. * @type {?Array<Plane>}
  15400. * @default null
  15401. */
  15402. this.clippingPlanes = null;
  15403. /**
  15404. * Changes the behavior of clipping planes so that only their intersection is
  15405. * clipped, rather than their union.
  15406. *
  15407. * @type {boolean}
  15408. * @default false
  15409. */
  15410. this.clipIntersection = false;
  15411. /**
  15412. * Defines whether to clip shadows according to the clipping planes specified
  15413. * on this material.
  15414. *
  15415. * @type {boolean}
  15416. * @default false
  15417. */
  15418. this.clipShadows = false;
  15419. /**
  15420. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  15421. * is determined as follows:
  15422. *
  15423. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  15424. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  15425. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  15426. *
  15427. * @type {?(FrontSide|BackSide|DoubleSide)}
  15428. * @default null
  15429. */
  15430. this.shadowSide = null;
  15431. /**
  15432. * Whether to render the material's color.
  15433. *
  15434. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  15435. * objects that occlude other objects.
  15436. *
  15437. * @type {boolean}
  15438. * @default true
  15439. */
  15440. this.colorWrite = true;
  15441. /**
  15442. * Override the renderer's default precision for this material.
  15443. *
  15444. * @type {?('highp'|'mediump'|'lowp')}
  15445. * @default null
  15446. */
  15447. this.precision = null;
  15448. /**
  15449. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  15450. * be offset after it is interpolated from the depth values of the appropriate vertices.
  15451. * The offset is added before the depth test is performed and before the value is written
  15452. * into the depth buffer.
  15453. *
  15454. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  15455. * rendering solids with highlighted edges.
  15456. *
  15457. * @type {boolean}
  15458. * @default false
  15459. */
  15460. this.polygonOffset = false;
  15461. /**
  15462. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  15463. *
  15464. * @type {number}
  15465. * @default 0
  15466. */
  15467. this.polygonOffsetFactor = 0;
  15468. /**
  15469. * Is multiplied by an implementation-specific value to create a constant depth offset.
  15470. *
  15471. * @type {number}
  15472. * @default 0
  15473. */
  15474. this.polygonOffsetUnits = 0;
  15475. /**
  15476. * Whether to apply dithering to the color to remove the appearance of banding.
  15477. *
  15478. * @type {boolean}
  15479. * @default false
  15480. */
  15481. this.dithering = false;
  15482. /**
  15483. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  15484. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  15485. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  15486. *
  15487. * @type {boolean}
  15488. * @default false
  15489. */
  15490. this.alphaToCoverage = false;
  15491. /**
  15492. * Whether to premultiply the alpha (transparency) value.
  15493. *
  15494. * @type {boolean}
  15495. * @default false
  15496. */
  15497. this.premultipliedAlpha = false;
  15498. /**
  15499. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  15500. *
  15501. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  15502. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  15503. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  15504. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  15505. * disable the two pass rendering to avoid performance issues.
  15506. *
  15507. * @type {boolean}
  15508. * @default false
  15509. */
  15510. this.forceSinglePass = false;
  15511. /**
  15512. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  15513. *
  15514. * @type {boolean}
  15515. * @default true
  15516. */
  15517. this.allowOverride = true;
  15518. /**
  15519. * Defines whether 3D objects using this material are visible.
  15520. *
  15521. * @type {boolean}
  15522. * @default true
  15523. */
  15524. this.visible = true;
  15525. /**
  15526. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  15527. *
  15528. * It is ignored when rendering to a render target or using post processing or when using
  15529. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  15530. *
  15531. * @type {boolean}
  15532. * @default true
  15533. */
  15534. this.toneMapped = true;
  15535. /**
  15536. * An object that can be used to store custom data about the Material. It
  15537. * should not hold references to functions as these will not be cloned.
  15538. *
  15539. * @type {Object}
  15540. */
  15541. this.userData = {};
  15542. /**
  15543. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  15544. *
  15545. * @type {number}
  15546. * @readonly
  15547. * @default 0
  15548. */
  15549. this.version = 0;
  15550. this._alphaTest = 0;
  15551. }
  15552. /**
  15553. * Sets the alpha value to be used when running an alpha test. The material
  15554. * will not be rendered if the opacity is lower than this value.
  15555. *
  15556. * @type {number}
  15557. * @readonly
  15558. * @default 0
  15559. */
  15560. get alphaTest() {
  15561. return this._alphaTest;
  15562. }
  15563. set alphaTest( value ) {
  15564. if ( this._alphaTest > 0 !== value > 0 ) {
  15565. this.version ++;
  15566. }
  15567. this._alphaTest = value;
  15568. }
  15569. /**
  15570. * An optional callback that is executed immediately before the material is used to render a 3D object.
  15571. *
  15572. * This method can only be used when rendering with {@link WebGLRenderer}.
  15573. *
  15574. * @param {WebGLRenderer} renderer - The renderer.
  15575. * @param {Scene} scene - The scene.
  15576. * @param {Camera} camera - The camera that is used to render the scene.
  15577. * @param {BufferGeometry} geometry - The 3D object's geometry.
  15578. * @param {Object3D} object - The 3D object.
  15579. * @param {Object} group - The geometry group data.
  15580. */
  15581. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  15582. /**
  15583. * An optional callback that is executed immediately before the shader
  15584. * program is compiled. This function is called with the shader source code
  15585. * as a parameter. Useful for the modification of built-in materials.
  15586. *
  15587. * This method can only be used when rendering with {@link WebGLRenderer}. The
  15588. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  15589. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  15590. *
  15591. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  15592. * @param {WebGLRenderer} renderer - A reference to the renderer.
  15593. */
  15594. onBeforeCompile( /* shaderobject, renderer */ ) {}
  15595. /**
  15596. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  15597. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  15598. * shader or recompile the shader for this material as needed.
  15599. *
  15600. * This method can only be used when rendering with {@link WebGLRenderer}.
  15601. *
  15602. * @return {string} The custom program cache key.
  15603. */
  15604. customProgramCacheKey() {
  15605. return this.onBeforeCompile.toString();
  15606. }
  15607. /**
  15608. * This method can be used to set default values from parameter objects.
  15609. * It is a generic implementation so it can be used with different types
  15610. * of materials.
  15611. *
  15612. * @param {Object} [values] - The material values to set.
  15613. */
  15614. setValues( values ) {
  15615. if ( values === undefined ) return;
  15616. for ( const key in values ) {
  15617. const newValue = values[ key ];
  15618. if ( newValue === undefined ) {
  15619. warn( `Material: parameter '${ key }' has value of undefined.` );
  15620. continue;
  15621. }
  15622. const currentValue = this[ key ];
  15623. if ( currentValue === undefined ) {
  15624. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  15625. continue;
  15626. }
  15627. if ( currentValue && currentValue.isColor ) {
  15628. currentValue.set( newValue );
  15629. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  15630. currentValue.copy( newValue );
  15631. } else {
  15632. this[ key ] = newValue;
  15633. }
  15634. }
  15635. }
  15636. /**
  15637. * Serializes the material into JSON.
  15638. *
  15639. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  15640. * @return {Object} A JSON object representing the serialized material.
  15641. * @see {@link ObjectLoader#parse}
  15642. */
  15643. toJSON( meta ) {
  15644. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  15645. if ( isRootObject ) {
  15646. meta = {
  15647. textures: {},
  15648. images: {}
  15649. };
  15650. }
  15651. const data = {
  15652. metadata: {
  15653. version: 4.7,
  15654. type: 'Material',
  15655. generator: 'Material.toJSON'
  15656. }
  15657. };
  15658. // standard Material serialization
  15659. data.uuid = this.uuid;
  15660. data.type = this.type;
  15661. if ( this.name !== '' ) data.name = this.name;
  15662. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  15663. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  15664. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  15665. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  15666. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  15667. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  15668. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  15669. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  15670. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  15671. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  15672. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  15673. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  15674. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  15675. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  15676. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  15677. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  15678. }
  15679. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  15680. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  15681. }
  15682. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  15683. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  15684. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  15685. }
  15686. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  15687. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  15688. }
  15689. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  15690. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  15691. }
  15692. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  15693. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  15694. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  15695. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  15696. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  15697. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  15698. }
  15699. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  15700. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  15701. }
  15702. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  15703. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  15704. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  15705. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  15706. }
  15707. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  15708. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  15709. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  15710. if ( this.lightMap && this.lightMap.isTexture ) {
  15711. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  15712. data.lightMapIntensity = this.lightMapIntensity;
  15713. }
  15714. if ( this.aoMap && this.aoMap.isTexture ) {
  15715. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  15716. data.aoMapIntensity = this.aoMapIntensity;
  15717. }
  15718. if ( this.bumpMap && this.bumpMap.isTexture ) {
  15719. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  15720. data.bumpScale = this.bumpScale;
  15721. }
  15722. if ( this.normalMap && this.normalMap.isTexture ) {
  15723. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  15724. data.normalMapType = this.normalMapType;
  15725. data.normalScale = this.normalScale.toArray();
  15726. }
  15727. if ( this.displacementMap && this.displacementMap.isTexture ) {
  15728. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  15729. data.displacementScale = this.displacementScale;
  15730. data.displacementBias = this.displacementBias;
  15731. }
  15732. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  15733. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  15734. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  15735. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  15736. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  15737. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  15738. if ( this.envMap && this.envMap.isTexture ) {
  15739. data.envMap = this.envMap.toJSON( meta ).uuid;
  15740. if ( this.combine !== undefined ) data.combine = this.combine;
  15741. }
  15742. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  15743. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  15744. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  15745. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  15746. if ( this.gradientMap && this.gradientMap.isTexture ) {
  15747. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  15748. }
  15749. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  15750. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  15751. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  15752. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  15753. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  15754. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  15755. if ( this.size !== undefined ) data.size = this.size;
  15756. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  15757. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  15758. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  15759. if ( this.side !== FrontSide ) data.side = this.side;
  15760. if ( this.vertexColors === true ) data.vertexColors = true;
  15761. if ( this.opacity < 1 ) data.opacity = this.opacity;
  15762. if ( this.transparent === true ) data.transparent = true;
  15763. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  15764. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  15765. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  15766. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  15767. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  15768. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  15769. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  15770. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  15771. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  15772. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  15773. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  15774. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  15775. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  15776. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  15777. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  15778. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  15779. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  15780. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  15781. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  15782. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  15783. // rotation (SpriteMaterial)
  15784. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  15785. if ( this.polygonOffset === true ) data.polygonOffset = true;
  15786. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  15787. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  15788. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  15789. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  15790. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  15791. if ( this.scale !== undefined ) data.scale = this.scale;
  15792. if ( this.dithering === true ) data.dithering = true;
  15793. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  15794. if ( this.alphaHash === true ) data.alphaHash = true;
  15795. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  15796. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  15797. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  15798. if ( this.allowOverride === false ) data.allowOverride = false;
  15799. if ( this.wireframe === true ) data.wireframe = true;
  15800. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  15801. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  15802. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  15803. if ( this.flatShading === true ) data.flatShading = true;
  15804. if ( this.visible === false ) data.visible = false;
  15805. if ( this.toneMapped === false ) data.toneMapped = false;
  15806. if ( this.fog === false ) data.fog = false;
  15807. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15808. // TODO: Copied from Object3D.toJSON
  15809. function extractFromCache( cache ) {
  15810. const values = [];
  15811. for ( const key in cache ) {
  15812. const data = cache[ key ];
  15813. delete data.metadata;
  15814. values.push( data );
  15815. }
  15816. return values;
  15817. }
  15818. if ( isRootObject ) {
  15819. const textures = extractFromCache( meta.textures );
  15820. const images = extractFromCache( meta.images );
  15821. if ( textures.length > 0 ) data.textures = textures;
  15822. if ( images.length > 0 ) data.images = images;
  15823. }
  15824. return data;
  15825. }
  15826. /**
  15827. * Returns a new material with copied values from this instance.
  15828. *
  15829. * @return {Material} A clone of this instance.
  15830. */
  15831. clone() {
  15832. return new this.constructor().copy( this );
  15833. }
  15834. /**
  15835. * Copies the values of the given material to this instance.
  15836. *
  15837. * @param {Material} source - The material to copy.
  15838. * @return {Material} A reference to this instance.
  15839. */
  15840. copy( source ) {
  15841. this.name = source.name;
  15842. this.blending = source.blending;
  15843. this.side = source.side;
  15844. this.vertexColors = source.vertexColors;
  15845. this.opacity = source.opacity;
  15846. this.transparent = source.transparent;
  15847. this.blendSrc = source.blendSrc;
  15848. this.blendDst = source.blendDst;
  15849. this.blendEquation = source.blendEquation;
  15850. this.blendSrcAlpha = source.blendSrcAlpha;
  15851. this.blendDstAlpha = source.blendDstAlpha;
  15852. this.blendEquationAlpha = source.blendEquationAlpha;
  15853. this.blendColor.copy( source.blendColor );
  15854. this.blendAlpha = source.blendAlpha;
  15855. this.depthFunc = source.depthFunc;
  15856. this.depthTest = source.depthTest;
  15857. this.depthWrite = source.depthWrite;
  15858. this.stencilWriteMask = source.stencilWriteMask;
  15859. this.stencilFunc = source.stencilFunc;
  15860. this.stencilRef = source.stencilRef;
  15861. this.stencilFuncMask = source.stencilFuncMask;
  15862. this.stencilFail = source.stencilFail;
  15863. this.stencilZFail = source.stencilZFail;
  15864. this.stencilZPass = source.stencilZPass;
  15865. this.stencilWrite = source.stencilWrite;
  15866. const srcPlanes = source.clippingPlanes;
  15867. let dstPlanes = null;
  15868. if ( srcPlanes !== null ) {
  15869. const n = srcPlanes.length;
  15870. dstPlanes = new Array( n );
  15871. for ( let i = 0; i !== n; ++ i ) {
  15872. dstPlanes[ i ] = srcPlanes[ i ].clone();
  15873. }
  15874. }
  15875. this.clippingPlanes = dstPlanes;
  15876. this.clipIntersection = source.clipIntersection;
  15877. this.clipShadows = source.clipShadows;
  15878. this.shadowSide = source.shadowSide;
  15879. this.colorWrite = source.colorWrite;
  15880. this.precision = source.precision;
  15881. this.polygonOffset = source.polygonOffset;
  15882. this.polygonOffsetFactor = source.polygonOffsetFactor;
  15883. this.polygonOffsetUnits = source.polygonOffsetUnits;
  15884. this.dithering = source.dithering;
  15885. this.alphaTest = source.alphaTest;
  15886. this.alphaHash = source.alphaHash;
  15887. this.alphaToCoverage = source.alphaToCoverage;
  15888. this.premultipliedAlpha = source.premultipliedAlpha;
  15889. this.forceSinglePass = source.forceSinglePass;
  15890. this.allowOverride = source.allowOverride;
  15891. this.visible = source.visible;
  15892. this.toneMapped = source.toneMapped;
  15893. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  15894. return this;
  15895. }
  15896. /**
  15897. * Frees the GPU-related resources allocated by this instance. Call this
  15898. * method whenever this instance is no longer used in your app.
  15899. *
  15900. * @fires Material#dispose
  15901. */
  15902. dispose() {
  15903. /**
  15904. * Fires when the material has been disposed of.
  15905. *
  15906. * @event Material#dispose
  15907. * @type {Object}
  15908. */
  15909. this.dispatchEvent( { type: 'dispose' } );
  15910. }
  15911. /**
  15912. * Setting this property to `true` indicates the engine the material
  15913. * needs to be recompiled.
  15914. *
  15915. * @type {boolean}
  15916. * @default false
  15917. * @param {boolean} value
  15918. */
  15919. set needsUpdate( value ) {
  15920. if ( value === true ) this.version ++;
  15921. }
  15922. }
  15923. /**
  15924. * A material for rendering instances of {@link Sprite}.
  15925. *
  15926. * ```js
  15927. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  15928. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  15929. *
  15930. * const sprite = new THREE.Sprite( material );
  15931. * sprite.scale.set(200, 200, 1)
  15932. * scene.add( sprite );
  15933. * ```
  15934. *
  15935. * @augments Material
  15936. */
  15937. class SpriteMaterial extends Material {
  15938. /**
  15939. * Constructs a new sprite material.
  15940. *
  15941. * @param {Object} [parameters] - An object with one or more properties
  15942. * defining the material's appearance. Any property of the material
  15943. * (including any property from inherited materials) can be passed
  15944. * in here. Color values can be passed any type of value accepted
  15945. * by {@link Color#set}.
  15946. */
  15947. constructor( parameters ) {
  15948. super();
  15949. /**
  15950. * This flag can be used for type testing.
  15951. *
  15952. * @type {boolean}
  15953. * @readonly
  15954. * @default true
  15955. */
  15956. this.isSpriteMaterial = true;
  15957. this.type = 'SpriteMaterial';
  15958. /**
  15959. * Color of the material.
  15960. *
  15961. * @type {Color}
  15962. * @default (1,1,1)
  15963. */
  15964. this.color = new Color( 0xffffff );
  15965. /**
  15966. * The color map. May optionally include an alpha channel, typically combined
  15967. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  15968. * color is modulated by the diffuse `color`.
  15969. *
  15970. * @type {?Texture}
  15971. * @default null
  15972. */
  15973. this.map = null;
  15974. /**
  15975. * The alpha map is a grayscale texture that controls the opacity across the
  15976. * surface (black: fully transparent; white: fully opaque).
  15977. *
  15978. * Only the color of the texture is used, ignoring the alpha channel if one
  15979. * exists. For RGB and RGBA textures, the renderer will use the green channel
  15980. * when sampling this texture due to the extra bit of precision provided for
  15981. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  15982. * luminance/alpha textures will also still work as expected.
  15983. *
  15984. * @type {?Texture}
  15985. * @default null
  15986. */
  15987. this.alphaMap = null;
  15988. /**
  15989. * The rotation of the sprite in radians.
  15990. *
  15991. * @type {number}
  15992. * @default 0
  15993. */
  15994. this.rotation = 0;
  15995. /**
  15996. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  15997. *
  15998. * @type {boolean}
  15999. * @default true
  16000. */
  16001. this.sizeAttenuation = true;
  16002. /**
  16003. * Overwritten since sprite materials are transparent
  16004. * by default.
  16005. *
  16006. * @type {boolean}
  16007. * @default true
  16008. */
  16009. this.transparent = true;
  16010. /**
  16011. * Whether the material is affected by fog or not.
  16012. *
  16013. * @type {boolean}
  16014. * @default true
  16015. */
  16016. this.fog = true;
  16017. this.setValues( parameters );
  16018. }
  16019. copy( source ) {
  16020. super.copy( source );
  16021. this.color.copy( source.color );
  16022. this.map = source.map;
  16023. this.alphaMap = source.alphaMap;
  16024. this.rotation = source.rotation;
  16025. this.sizeAttenuation = source.sizeAttenuation;
  16026. this.fog = source.fog;
  16027. return this;
  16028. }
  16029. }
  16030. let _geometry;
  16031. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16032. const _worldScale = /*@__PURE__*/ new Vector3();
  16033. const _mvPosition = /*@__PURE__*/ new Vector3();
  16034. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16035. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16036. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16037. const _vA$1 = /*@__PURE__*/ new Vector3();
  16038. const _vB$1 = /*@__PURE__*/ new Vector3();
  16039. const _vC$1 = /*@__PURE__*/ new Vector3();
  16040. const _uvA = /*@__PURE__*/ new Vector2();
  16041. const _uvB = /*@__PURE__*/ new Vector2();
  16042. const _uvC = /*@__PURE__*/ new Vector2();
  16043. /**
  16044. * A sprite is a plane that always faces towards the camera, generally with a
  16045. * partially transparent texture applied.
  16046. *
  16047. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  16048. * have no effect.
  16049. *
  16050. * ```js
  16051. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  16052. * const material = new THREE.SpriteMaterial( { map: map } );
  16053. *
  16054. * const sprite = new THREE.Sprite( material );
  16055. * scene.add( sprite );
  16056. * ```
  16057. *
  16058. * @augments Object3D
  16059. */
  16060. class Sprite extends Object3D {
  16061. /**
  16062. * Constructs a new sprite.
  16063. *
  16064. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  16065. */
  16066. constructor( material = new SpriteMaterial() ) {
  16067. super();
  16068. /**
  16069. * This flag can be used for type testing.
  16070. *
  16071. * @type {boolean}
  16072. * @readonly
  16073. * @default true
  16074. */
  16075. this.isSprite = true;
  16076. this.type = 'Sprite';
  16077. if ( _geometry === undefined ) {
  16078. _geometry = new BufferGeometry();
  16079. const float32Array = new Float32Array( [
  16080. -0.5, -0.5, 0, 0, 0,
  16081. 0.5, -0.5, 0, 1, 0,
  16082. 0.5, 0.5, 0, 1, 1,
  16083. -0.5, 0.5, 0, 0, 1
  16084. ] );
  16085. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16086. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16087. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16088. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16089. }
  16090. /**
  16091. * The sprite geometry.
  16092. *
  16093. * @type {BufferGeometry}
  16094. */
  16095. this.geometry = _geometry;
  16096. /**
  16097. * The sprite material.
  16098. *
  16099. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  16100. */
  16101. this.material = material;
  16102. /**
  16103. * The sprite's anchor point, and the point around which the sprite rotates.
  16104. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  16105. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  16106. *
  16107. * @type {Vector2}
  16108. * @default (0.5,0.5)
  16109. */
  16110. this.center = new Vector2( 0.5, 0.5 );
  16111. /**
  16112. * The number of instances of this sprite.
  16113. * Can only be used with {@link WebGPURenderer}.
  16114. *
  16115. * @type {number}
  16116. * @default 1
  16117. */
  16118. this.count = 1;
  16119. }
  16120. /**
  16121. * Computes intersection points between a casted ray and this sprite.
  16122. *
  16123. * @param {Raycaster} raycaster - The raycaster.
  16124. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16125. */
  16126. raycast( raycaster, intersects ) {
  16127. if ( raycaster.camera === null ) {
  16128. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16129. }
  16130. _worldScale.setFromMatrixScale( this.matrixWorld );
  16131. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16132. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16133. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16134. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16135. _worldScale.multiplyScalar( - _mvPosition.z );
  16136. }
  16137. const rotation = this.material.rotation;
  16138. let sin, cos;
  16139. if ( rotation !== 0 ) {
  16140. cos = Math.cos( rotation );
  16141. sin = Math.sin( rotation );
  16142. }
  16143. const center = this.center;
  16144. transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16145. transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16146. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16147. _uvA.set( 0, 0 );
  16148. _uvB.set( 1, 0 );
  16149. _uvC.set( 1, 1 );
  16150. // check first triangle
  16151. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16152. if ( intersect === null ) {
  16153. // check second triangle
  16154. transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16155. _uvB.set( 0, 1 );
  16156. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16157. if ( intersect === null ) {
  16158. return;
  16159. }
  16160. }
  16161. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16162. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16163. intersects.push( {
  16164. distance: distance,
  16165. point: _intersectPoint.clone(),
  16166. uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ),
  16167. face: null,
  16168. object: this
  16169. } );
  16170. }
  16171. copy( source, recursive ) {
  16172. super.copy( source, recursive );
  16173. if ( source.center !== undefined ) this.center.copy( source.center );
  16174. this.material = source.material;
  16175. return this;
  16176. }
  16177. }
  16178. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16179. // compute position in camera space
  16180. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16181. // to check if rotation is not zero
  16182. if ( sin !== undefined ) {
  16183. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16184. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16185. } else {
  16186. _rotatedPosition.copy( _alignedPosition );
  16187. }
  16188. vertexPosition.copy( mvPosition );
  16189. vertexPosition.x += _rotatedPosition.x;
  16190. vertexPosition.y += _rotatedPosition.y;
  16191. // transform to world space
  16192. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16193. }
  16194. const _v1$2 = /*@__PURE__*/ new Vector3();
  16195. const _v2$1 = /*@__PURE__*/ new Vector3();
  16196. /**
  16197. * A component for providing a basic Level of Detail (LOD) mechanism.
  16198. *
  16199. * Every LOD level is associated with an object, and rendering can be switched
  16200. * between them at the distances specified. Typically you would create, say,
  16201. * three meshes, one for far away (low detail), one for mid range (medium
  16202. * detail) and one for close up (high detail).
  16203. *
  16204. * ```js
  16205. * const lod = new THREE.LOD();
  16206. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  16207. *
  16208. * //Create spheres with 3 levels of detail and create new LOD levels for them
  16209. * for( let i = 0; i < 3; i++ ) {
  16210. *
  16211. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  16212. * const mesh = new THREE.Mesh( geometry, material );
  16213. * lod.addLevel( mesh, i * 75 );
  16214. *
  16215. * }
  16216. *
  16217. * scene.add( lod );
  16218. * ```
  16219. *
  16220. * @augments Object3D
  16221. */
  16222. class LOD extends Object3D {
  16223. /**
  16224. * Constructs a new LOD.
  16225. */
  16226. constructor() {
  16227. super();
  16228. /**
  16229. * This flag can be used for type testing.
  16230. *
  16231. * @type {boolean}
  16232. * @readonly
  16233. * @default true
  16234. */
  16235. this.isLOD = true;
  16236. /**
  16237. * The current LOD index.
  16238. *
  16239. * @private
  16240. * @type {number}
  16241. * @default 0
  16242. */
  16243. this._currentLevel = 0;
  16244. this.type = 'LOD';
  16245. Object.defineProperties( this, {
  16246. /**
  16247. * This array holds the LOD levels.
  16248. *
  16249. * @name LOD#levels
  16250. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  16251. */
  16252. levels: {
  16253. enumerable: true,
  16254. value: []
  16255. }
  16256. } );
  16257. /**
  16258. * Whether the LOD object is updated automatically by the renderer per frame
  16259. * or not. If set to `false`, you have to call {@link LOD#update} in the
  16260. * render loop by yourself.
  16261. *
  16262. * @type {boolean}
  16263. * @default true
  16264. */
  16265. this.autoUpdate = true;
  16266. }
  16267. copy( source ) {
  16268. super.copy( source, false );
  16269. const levels = source.levels;
  16270. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16271. const level = levels[ i ];
  16272. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  16273. }
  16274. this.autoUpdate = source.autoUpdate;
  16275. return this;
  16276. }
  16277. /**
  16278. * Adds a mesh that will display at a certain distance and greater. Typically
  16279. * the further away the distance, the lower the detail on the mesh.
  16280. *
  16281. * @param {Object3D} object - The 3D object to display at this level.
  16282. * @param {number} [distance=0] - The distance at which to display this level of detail.
  16283. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  16284. * @return {LOD} A reference to this instance.
  16285. */
  16286. addLevel( object, distance = 0, hysteresis = 0 ) {
  16287. distance = Math.abs( distance );
  16288. const levels = this.levels;
  16289. let l;
  16290. for ( l = 0; l < levels.length; l ++ ) {
  16291. if ( distance < levels[ l ].distance ) {
  16292. break;
  16293. }
  16294. }
  16295. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  16296. this.add( object );
  16297. return this;
  16298. }
  16299. /**
  16300. * Removes an existing level, based on the distance from the camera.
  16301. * Returns `true` when the level has been removed. Otherwise `false`.
  16302. *
  16303. * @param {number} distance - Distance of the level to remove.
  16304. * @return {boolean} Whether the level has been removed or not.
  16305. */
  16306. removeLevel( distance ) {
  16307. const levels = this.levels;
  16308. for ( let i = 0; i < levels.length; i ++ ) {
  16309. if ( levels[ i ].distance === distance ) {
  16310. const removedElements = levels.splice( i, 1 );
  16311. this.remove( removedElements[ 0 ].object );
  16312. return true;
  16313. }
  16314. }
  16315. return false;
  16316. }
  16317. /**
  16318. * Returns the currently active LOD level index.
  16319. *
  16320. * @return {number} The current active LOD level index.
  16321. */
  16322. getCurrentLevel() {
  16323. return this._currentLevel;
  16324. }
  16325. /**
  16326. * Returns a reference to the first 3D object that is greater than
  16327. * the given distance.
  16328. *
  16329. * @param {number} distance - The LOD distance.
  16330. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  16331. */
  16332. getObjectForDistance( distance ) {
  16333. const levels = this.levels;
  16334. if ( levels.length > 0 ) {
  16335. let i, l;
  16336. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16337. let levelDistance = levels[ i ].distance;
  16338. if ( levels[ i ].object.visible ) {
  16339. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16340. }
  16341. if ( distance < levelDistance ) {
  16342. break;
  16343. }
  16344. }
  16345. return levels[ i - 1 ].object;
  16346. }
  16347. return null;
  16348. }
  16349. /**
  16350. * Computes intersection points between a casted ray and this LOD.
  16351. *
  16352. * @param {Raycaster} raycaster - The raycaster.
  16353. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16354. */
  16355. raycast( raycaster, intersects ) {
  16356. const levels = this.levels;
  16357. if ( levels.length > 0 ) {
  16358. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16359. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16360. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16361. }
  16362. }
  16363. /**
  16364. * Updates the LOD by computing which LOD level should be visible according
  16365. * to the current distance of the given camera.
  16366. *
  16367. * @param {Camera} camera - The camera the scene is rendered with.
  16368. */
  16369. update( camera ) {
  16370. const levels = this.levels;
  16371. if ( levels.length > 1 ) {
  16372. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16373. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16374. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16375. levels[ 0 ].object.visible = true;
  16376. let i, l;
  16377. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16378. let levelDistance = levels[ i ].distance;
  16379. if ( levels[ i ].object.visible ) {
  16380. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16381. }
  16382. if ( distance >= levelDistance ) {
  16383. levels[ i - 1 ].object.visible = false;
  16384. levels[ i ].object.visible = true;
  16385. } else {
  16386. break;
  16387. }
  16388. }
  16389. this._currentLevel = i - 1;
  16390. for ( ; i < l; i ++ ) {
  16391. levels[ i ].object.visible = false;
  16392. }
  16393. }
  16394. }
  16395. toJSON( meta ) {
  16396. const data = super.toJSON( meta );
  16397. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16398. data.object.levels = [];
  16399. const levels = this.levels;
  16400. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16401. const level = levels[ i ];
  16402. data.object.levels.push( {
  16403. object: level.object.uuid,
  16404. distance: level.distance,
  16405. hysteresis: level.hysteresis
  16406. } );
  16407. }
  16408. return data;
  16409. }
  16410. }
  16411. const _vector$7 = /*@__PURE__*/ new Vector3();
  16412. const _segCenter = /*@__PURE__*/ new Vector3();
  16413. const _segDir = /*@__PURE__*/ new Vector3();
  16414. const _diff = /*@__PURE__*/ new Vector3();
  16415. const _edge1 = /*@__PURE__*/ new Vector3();
  16416. const _edge2 = /*@__PURE__*/ new Vector3();
  16417. const _normal$1 = /*@__PURE__*/ new Vector3();
  16418. /**
  16419. * A ray that emits from an origin in a certain direction. The class is used by
  16420. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16421. * mouse picking (working out what objects in the 3D space the mouse is over)
  16422. * amongst other things.
  16423. */
  16424. class Ray {
  16425. /**
  16426. * Constructs a new ray.
  16427. *
  16428. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16429. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16430. */
  16431. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16432. /**
  16433. * The origin of the ray.
  16434. *
  16435. * @type {Vector3}
  16436. */
  16437. this.origin = origin;
  16438. /**
  16439. * The (normalized) direction of the ray.
  16440. *
  16441. * @type {Vector3}
  16442. */
  16443. this.direction = direction;
  16444. }
  16445. /**
  16446. * Sets the ray's components by copying the given values.
  16447. *
  16448. * @param {Vector3} origin - The origin.
  16449. * @param {Vector3} direction - The direction.
  16450. * @return {Ray} A reference to this ray.
  16451. */
  16452. set( origin, direction ) {
  16453. this.origin.copy( origin );
  16454. this.direction.copy( direction );
  16455. return this;
  16456. }
  16457. /**
  16458. * Copies the values of the given ray to this instance.
  16459. *
  16460. * @param {Ray} ray - The ray to copy.
  16461. * @return {Ray} A reference to this ray.
  16462. */
  16463. copy( ray ) {
  16464. this.origin.copy( ray.origin );
  16465. this.direction.copy( ray.direction );
  16466. return this;
  16467. }
  16468. /**
  16469. * Returns a vector that is located at a given distance along this ray.
  16470. *
  16471. * @param {number} t - The distance along the ray to retrieve a position for.
  16472. * @param {Vector3} target - The target vector that is used to store the method's result.
  16473. * @return {Vector3} A position on the ray.
  16474. */
  16475. at( t, target ) {
  16476. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16477. }
  16478. /**
  16479. * Adjusts the direction of the ray to point at the given vector in world space.
  16480. *
  16481. * @param {Vector3} v - The target position.
  16482. * @return {Ray} A reference to this ray.
  16483. */
  16484. lookAt( v ) {
  16485. this.direction.copy( v ).sub( this.origin ).normalize();
  16486. return this;
  16487. }
  16488. /**
  16489. * Shift the origin of this ray along its direction by the given distance.
  16490. *
  16491. * @param {number} t - The distance along the ray to interpolate.
  16492. * @return {Ray} A reference to this ray.
  16493. */
  16494. recast( t ) {
  16495. this.origin.copy( this.at( t, _vector$7 ) );
  16496. return this;
  16497. }
  16498. /**
  16499. * Returns the point along this ray that is closest to the given point.
  16500. *
  16501. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16502. * @param {Vector3} target - The target vector that is used to store the method's result.
  16503. * @return {Vector3} The closest point on this ray.
  16504. */
  16505. closestPointToPoint( point, target ) {
  16506. target.subVectors( point, this.origin );
  16507. const directionDistance = target.dot( this.direction );
  16508. if ( directionDistance < 0 ) {
  16509. return target.copy( this.origin );
  16510. }
  16511. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16512. }
  16513. /**
  16514. * Returns the distance of the closest approach between this ray and the given point.
  16515. *
  16516. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16517. * @return {number} The distance.
  16518. */
  16519. distanceToPoint( point ) {
  16520. return Math.sqrt( this.distanceSqToPoint( point ) );
  16521. }
  16522. /**
  16523. * Returns the squared distance of the closest approach between this ray and the given point.
  16524. *
  16525. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16526. * @return {number} The squared distance.
  16527. */
  16528. distanceSqToPoint( point ) {
  16529. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16530. // point behind the ray
  16531. if ( directionDistance < 0 ) {
  16532. return this.origin.distanceToSquared( point );
  16533. }
  16534. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16535. return _vector$7.distanceToSquared( point );
  16536. }
  16537. /**
  16538. * Returns the squared distance between this ray and the given line segment.
  16539. *
  16540. * @param {Vector3} v0 - The start point of the line segment.
  16541. * @param {Vector3} v1 - The end point of the line segment.
  16542. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16543. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16544. * @return {number} The squared distance.
  16545. */
  16546. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16547. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16548. // It returns the min distance between the ray and the segment
  16549. // defined by v0 and v1
  16550. // It can also set two optional targets :
  16551. // - The closest point on the ray
  16552. // - The closest point on the segment
  16553. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16554. _segDir.copy( v1 ).sub( v0 ).normalize();
  16555. _diff.copy( this.origin ).sub( _segCenter );
  16556. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16557. const a01 = - this.direction.dot( _segDir );
  16558. const b0 = _diff.dot( this.direction );
  16559. const b1 = - _diff.dot( _segDir );
  16560. const c = _diff.lengthSq();
  16561. const det = Math.abs( 1 - a01 * a01 );
  16562. let s0, s1, sqrDist, extDet;
  16563. if ( det > 0 ) {
  16564. // The ray and segment are not parallel.
  16565. s0 = a01 * b1 - b0;
  16566. s1 = a01 * b0 - b1;
  16567. extDet = segExtent * det;
  16568. if ( s0 >= 0 ) {
  16569. if ( s1 >= - extDet ) {
  16570. if ( s1 <= extDet ) {
  16571. // region 0
  16572. // Minimum at interior points of ray and segment.
  16573. const invDet = 1 / det;
  16574. s0 *= invDet;
  16575. s1 *= invDet;
  16576. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16577. } else {
  16578. // region 1
  16579. s1 = segExtent;
  16580. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16581. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16582. }
  16583. } else {
  16584. // region 5
  16585. s1 = - segExtent;
  16586. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16587. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16588. }
  16589. } else {
  16590. if ( s1 <= - extDet ) {
  16591. // region 4
  16592. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16593. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16594. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16595. } else if ( s1 <= extDet ) {
  16596. // region 3
  16597. s0 = 0;
  16598. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16599. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16600. } else {
  16601. // region 2
  16602. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16603. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16604. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16605. }
  16606. }
  16607. } else {
  16608. // Ray and segment are parallel.
  16609. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16610. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16611. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16612. }
  16613. if ( optionalPointOnRay ) {
  16614. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16615. }
  16616. if ( optionalPointOnSegment ) {
  16617. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16618. }
  16619. return sqrDist;
  16620. }
  16621. /**
  16622. * Intersects this ray with the given sphere, returning the intersection
  16623. * point or `null` if there is no intersection.
  16624. *
  16625. * @param {Sphere} sphere - The sphere to intersect.
  16626. * @param {Vector3} target - The target vector that is used to store the method's result.
  16627. * @return {?Vector3} The intersection point.
  16628. */
  16629. intersectSphere( sphere, target ) {
  16630. _vector$7.subVectors( sphere.center, this.origin );
  16631. const tca = _vector$7.dot( this.direction );
  16632. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16633. const radius2 = sphere.radius * sphere.radius;
  16634. if ( d2 > radius2 ) return null;
  16635. const thc = Math.sqrt( radius2 - d2 );
  16636. // t0 = first intersect point - entrance on front of sphere
  16637. const t0 = tca - thc;
  16638. // t1 = second intersect point - exit point on back of sphere
  16639. const t1 = tca + thc;
  16640. // test to see if t1 is behind the ray - if so, return null
  16641. if ( t1 < 0 ) return null;
  16642. // test to see if t0 is behind the ray:
  16643. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16644. // in order to always return an intersect point that is in front of the ray.
  16645. if ( t0 < 0 ) return this.at( t1, target );
  16646. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16647. return this.at( t0, target );
  16648. }
  16649. /**
  16650. * Returns `true` if this ray intersects with the given sphere.
  16651. *
  16652. * @param {Sphere} sphere - The sphere to intersect.
  16653. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16654. */
  16655. intersectsSphere( sphere ) {
  16656. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16657. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16658. }
  16659. /**
  16660. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16661. * does not intersect with the plane.
  16662. *
  16663. * @param {Plane} plane - The plane to compute the distance to.
  16664. * @return {?number} Whether this ray intersects with the given sphere or not.
  16665. */
  16666. distanceToPlane( plane ) {
  16667. const denominator = plane.normal.dot( this.direction );
  16668. if ( denominator === 0 ) {
  16669. // line is coplanar, return origin
  16670. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16671. return 0;
  16672. }
  16673. // Null is preferable to undefined since undefined means.... it is undefined
  16674. return null;
  16675. }
  16676. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16677. // Return if the ray never intersects the plane
  16678. return t >= 0 ? t : null;
  16679. }
  16680. /**
  16681. * Intersects this ray with the given plane, returning the intersection
  16682. * point or `null` if there is no intersection.
  16683. *
  16684. * @param {Plane} plane - The plane to intersect.
  16685. * @param {Vector3} target - The target vector that is used to store the method's result.
  16686. * @return {?Vector3} The intersection point.
  16687. */
  16688. intersectPlane( plane, target ) {
  16689. const t = this.distanceToPlane( plane );
  16690. if ( t === null ) {
  16691. return null;
  16692. }
  16693. return this.at( t, target );
  16694. }
  16695. /**
  16696. * Returns `true` if this ray intersects with the given plane.
  16697. *
  16698. * @param {Plane} plane - The plane to intersect.
  16699. * @return {boolean} Whether this ray intersects with the given plane or not.
  16700. */
  16701. intersectsPlane( plane ) {
  16702. // check if the ray lies on the plane first
  16703. const distToPoint = plane.distanceToPoint( this.origin );
  16704. if ( distToPoint === 0 ) {
  16705. return true;
  16706. }
  16707. const denominator = plane.normal.dot( this.direction );
  16708. if ( denominator * distToPoint < 0 ) {
  16709. return true;
  16710. }
  16711. // ray origin is behind the plane (and is pointing behind it)
  16712. return false;
  16713. }
  16714. /**
  16715. * Intersects this ray with the given bounding box, returning the intersection
  16716. * point or `null` if there is no intersection.
  16717. *
  16718. * @param {Box3} box - The box to intersect.
  16719. * @param {Vector3} target - The target vector that is used to store the method's result.
  16720. * @return {?Vector3} The intersection point.
  16721. */
  16722. intersectBox( box, target ) {
  16723. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16724. const invdirx = 1 / this.direction.x,
  16725. invdiry = 1 / this.direction.y,
  16726. invdirz = 1 / this.direction.z;
  16727. const origin = this.origin;
  16728. if ( invdirx >= 0 ) {
  16729. tmin = ( box.min.x - origin.x ) * invdirx;
  16730. tmax = ( box.max.x - origin.x ) * invdirx;
  16731. } else {
  16732. tmin = ( box.max.x - origin.x ) * invdirx;
  16733. tmax = ( box.min.x - origin.x ) * invdirx;
  16734. }
  16735. if ( invdiry >= 0 ) {
  16736. tymin = ( box.min.y - origin.y ) * invdiry;
  16737. tymax = ( box.max.y - origin.y ) * invdiry;
  16738. } else {
  16739. tymin = ( box.max.y - origin.y ) * invdiry;
  16740. tymax = ( box.min.y - origin.y ) * invdiry;
  16741. }
  16742. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  16743. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  16744. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  16745. if ( invdirz >= 0 ) {
  16746. tzmin = ( box.min.z - origin.z ) * invdirz;
  16747. tzmax = ( box.max.z - origin.z ) * invdirz;
  16748. } else {
  16749. tzmin = ( box.max.z - origin.z ) * invdirz;
  16750. tzmax = ( box.min.z - origin.z ) * invdirz;
  16751. }
  16752. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  16753. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  16754. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  16755. //return point closest to the ray (positive side)
  16756. if ( tmax < 0 ) return null;
  16757. return this.at( tmin >= 0 ? tmin : tmax, target );
  16758. }
  16759. /**
  16760. * Returns `true` if this ray intersects with the given box.
  16761. *
  16762. * @param {Box3} box - The box to intersect.
  16763. * @return {boolean} Whether this ray intersects with the given box or not.
  16764. */
  16765. intersectsBox( box ) {
  16766. return this.intersectBox( box, _vector$7 ) !== null;
  16767. }
  16768. /**
  16769. * Intersects this ray with the given triangle, returning the intersection
  16770. * point or `null` if there is no intersection.
  16771. *
  16772. * @param {Vector3} a - The first vertex of the triangle.
  16773. * @param {Vector3} b - The second vertex of the triangle.
  16774. * @param {Vector3} c - The third vertex of the triangle.
  16775. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  16776. * @param {Vector3} target - The target vector that is used to store the method's result.
  16777. * @return {?Vector3} The intersection point.
  16778. */
  16779. intersectTriangle( a, b, c, backfaceCulling, target ) {
  16780. // Compute the offset origin, edges, and normal.
  16781. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  16782. _edge1.subVectors( b, a );
  16783. _edge2.subVectors( c, a );
  16784. _normal$1.crossVectors( _edge1, _edge2 );
  16785. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  16786. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  16787. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  16788. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  16789. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  16790. let DdN = this.direction.dot( _normal$1 );
  16791. let sign;
  16792. if ( DdN > 0 ) {
  16793. if ( backfaceCulling ) return null;
  16794. sign = 1;
  16795. } else if ( DdN < 0 ) {
  16796. sign = -1;
  16797. DdN = - DdN;
  16798. } else {
  16799. return null;
  16800. }
  16801. _diff.subVectors( this.origin, a );
  16802. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  16803. // b1 < 0, no intersection
  16804. if ( DdQxE2 < 0 ) {
  16805. return null;
  16806. }
  16807. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  16808. // b2 < 0, no intersection
  16809. if ( DdE1xQ < 0 ) {
  16810. return null;
  16811. }
  16812. // b1+b2 > 1, no intersection
  16813. if ( DdQxE2 + DdE1xQ > DdN ) {
  16814. return null;
  16815. }
  16816. // Line intersects triangle, check if ray does.
  16817. const QdN = - sign * _diff.dot( _normal$1 );
  16818. // t < 0, no intersection
  16819. if ( QdN < 0 ) {
  16820. return null;
  16821. }
  16822. // Ray intersects triangle.
  16823. return this.at( QdN / DdN, target );
  16824. }
  16825. /**
  16826. * Transforms this ray with the given 4x4 transformation matrix.
  16827. *
  16828. * @param {Matrix4} matrix4 - The transformation matrix.
  16829. * @return {Ray} A reference to this ray.
  16830. */
  16831. applyMatrix4( matrix4 ) {
  16832. this.origin.applyMatrix4( matrix4 );
  16833. this.direction.transformDirection( matrix4 );
  16834. return this;
  16835. }
  16836. /**
  16837. * Returns `true` if this ray is equal with the given one.
  16838. *
  16839. * @param {Ray} ray - The ray to test for equality.
  16840. * @return {boolean} Whether this ray is equal with the given one.
  16841. */
  16842. equals( ray ) {
  16843. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  16844. }
  16845. /**
  16846. * Returns a new ray with copied values from this instance.
  16847. *
  16848. * @return {Ray} A clone of this instance.
  16849. */
  16850. clone() {
  16851. return new this.constructor().copy( this );
  16852. }
  16853. }
  16854. /**
  16855. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  16856. *
  16857. * This material is not affected by lights.
  16858. *
  16859. * @augments Material
  16860. * @demo scenes/material-browser.html#MeshBasicMaterial
  16861. */
  16862. class MeshBasicMaterial extends Material {
  16863. /**
  16864. * Constructs a new mesh basic material.
  16865. *
  16866. * @param {Object} [parameters] - An object with one or more properties
  16867. * defining the material's appearance. Any property of the material
  16868. * (including any property from inherited materials) can be passed
  16869. * in here. Color values can be passed any type of value accepted
  16870. * by {@link Color#set}.
  16871. */
  16872. constructor( parameters ) {
  16873. super();
  16874. /**
  16875. * This flag can be used for type testing.
  16876. *
  16877. * @type {boolean}
  16878. * @readonly
  16879. * @default true
  16880. */
  16881. this.isMeshBasicMaterial = true;
  16882. this.type = 'MeshBasicMaterial';
  16883. /**
  16884. * Color of the material.
  16885. *
  16886. * @type {Color}
  16887. * @default (1,1,1)
  16888. */
  16889. this.color = new Color( 0xffffff ); // diffuse
  16890. /**
  16891. * The color map. May optionally include an alpha channel, typically combined
  16892. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16893. * color is modulated by the diffuse `color`.
  16894. *
  16895. * @type {?Texture}
  16896. * @default null
  16897. */
  16898. this.map = null;
  16899. /**
  16900. * The light map. Requires a second set of UVs.
  16901. *
  16902. * @type {?Texture}
  16903. * @default null
  16904. */
  16905. this.lightMap = null;
  16906. /**
  16907. * Intensity of the baked light.
  16908. *
  16909. * @type {number}
  16910. * @default 1
  16911. */
  16912. this.lightMapIntensity = 1.0;
  16913. /**
  16914. * The red channel of this texture is used as the ambient occlusion map.
  16915. * Requires a second set of UVs.
  16916. *
  16917. * @type {?Texture}
  16918. * @default null
  16919. */
  16920. this.aoMap = null;
  16921. /**
  16922. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  16923. * disables ambient occlusion. Where intensity is `1` and the AO map's
  16924. * red channel is also `1`, ambient light is fully occluded on a surface.
  16925. *
  16926. * @type {number}
  16927. * @default 1
  16928. */
  16929. this.aoMapIntensity = 1.0;
  16930. /**
  16931. * Specular map used by the material.
  16932. *
  16933. * @type {?Texture}
  16934. * @default null
  16935. */
  16936. this.specularMap = null;
  16937. /**
  16938. * The alpha map is a grayscale texture that controls the opacity across the
  16939. * surface (black: fully transparent; white: fully opaque).
  16940. *
  16941. * Only the color of the texture is used, ignoring the alpha channel if one
  16942. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16943. * when sampling this texture due to the extra bit of precision provided for
  16944. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16945. * luminance/alpha textures will also still work as expected.
  16946. *
  16947. * @type {?Texture}
  16948. * @default null
  16949. */
  16950. this.alphaMap = null;
  16951. /**
  16952. * The environment map.
  16953. *
  16954. * @type {?Texture}
  16955. * @default null
  16956. */
  16957. this.envMap = null;
  16958. /**
  16959. * The rotation of the environment map in radians.
  16960. *
  16961. * @type {Euler}
  16962. * @default (0,0,0)
  16963. */
  16964. this.envMapRotation = new Euler();
  16965. /**
  16966. * How to combine the result of the surface's color with the environment map, if any.
  16967. *
  16968. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  16969. * blend between the two colors.
  16970. *
  16971. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  16972. * @default MultiplyOperation
  16973. */
  16974. this.combine = MultiplyOperation;
  16975. /**
  16976. * How much the environment map affects the surface.
  16977. * The valid range is between `0` (no reflections) and `1` (full reflections).
  16978. *
  16979. * @type {number}
  16980. * @default 1
  16981. */
  16982. this.reflectivity = 1;
  16983. /**
  16984. * The index of refraction (IOR) of air (approximately 1) divided by the
  16985. * index of refraction of the material. It is used with environment mapping
  16986. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  16987. * The refraction ratio should not exceed `1`.
  16988. *
  16989. * @type {number}
  16990. * @default 0.98
  16991. */
  16992. this.refractionRatio = 0.98;
  16993. /**
  16994. * Renders the geometry as a wireframe.
  16995. *
  16996. * @type {boolean}
  16997. * @default false
  16998. */
  16999. this.wireframe = false;
  17000. /**
  17001. * Controls the thickness of the wireframe.
  17002. *
  17003. * Can only be used with {@link SVGRenderer}.
  17004. *
  17005. * @type {number}
  17006. * @default 1
  17007. */
  17008. this.wireframeLinewidth = 1;
  17009. /**
  17010. * Defines appearance of wireframe ends.
  17011. *
  17012. * Can only be used with {@link SVGRenderer}.
  17013. *
  17014. * @type {('round'|'bevel'|'miter')}
  17015. * @default 'round'
  17016. */
  17017. this.wireframeLinecap = 'round';
  17018. /**
  17019. * Defines appearance of wireframe joints.
  17020. *
  17021. * Can only be used with {@link SVGRenderer}.
  17022. *
  17023. * @type {('round'|'bevel'|'miter')}
  17024. * @default 'round'
  17025. */
  17026. this.wireframeLinejoin = 'round';
  17027. /**
  17028. * Whether the material is affected by fog or not.
  17029. *
  17030. * @type {boolean}
  17031. * @default true
  17032. */
  17033. this.fog = true;
  17034. this.setValues( parameters );
  17035. }
  17036. copy( source ) {
  17037. super.copy( source );
  17038. this.color.copy( source.color );
  17039. this.map = source.map;
  17040. this.lightMap = source.lightMap;
  17041. this.lightMapIntensity = source.lightMapIntensity;
  17042. this.aoMap = source.aoMap;
  17043. this.aoMapIntensity = source.aoMapIntensity;
  17044. this.specularMap = source.specularMap;
  17045. this.alphaMap = source.alphaMap;
  17046. this.envMap = source.envMap;
  17047. this.envMapRotation.copy( source.envMapRotation );
  17048. this.combine = source.combine;
  17049. this.reflectivity = source.reflectivity;
  17050. this.refractionRatio = source.refractionRatio;
  17051. this.wireframe = source.wireframe;
  17052. this.wireframeLinewidth = source.wireframeLinewidth;
  17053. this.wireframeLinecap = source.wireframeLinecap;
  17054. this.wireframeLinejoin = source.wireframeLinejoin;
  17055. this.fog = source.fog;
  17056. return this;
  17057. }
  17058. }
  17059. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17060. const _ray$3 = /*@__PURE__*/ new Ray();
  17061. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17062. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17063. const _vA = /*@__PURE__*/ new Vector3();
  17064. const _vB = /*@__PURE__*/ new Vector3();
  17065. const _vC = /*@__PURE__*/ new Vector3();
  17066. const _tempA = /*@__PURE__*/ new Vector3();
  17067. const _morphA = /*@__PURE__*/ new Vector3();
  17068. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17069. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17070. /**
  17071. * Class representing triangular polygon mesh based objects.
  17072. *
  17073. * ```js
  17074. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17075. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17076. * const mesh = new THREE.Mesh( geometry, material );
  17077. * scene.add( mesh );
  17078. * ```
  17079. *
  17080. * @augments Object3D
  17081. */
  17082. class Mesh extends Object3D {
  17083. /**
  17084. * Constructs a new mesh.
  17085. *
  17086. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17087. * @param {Material|Array<Material>} [material] - The mesh material.
  17088. */
  17089. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17090. super();
  17091. /**
  17092. * This flag can be used for type testing.
  17093. *
  17094. * @type {boolean}
  17095. * @readonly
  17096. * @default true
  17097. */
  17098. this.isMesh = true;
  17099. this.type = 'Mesh';
  17100. /**
  17101. * The mesh geometry.
  17102. *
  17103. * @type {BufferGeometry}
  17104. */
  17105. this.geometry = geometry;
  17106. /**
  17107. * The mesh material.
  17108. *
  17109. * @type {Material|Array<Material>}
  17110. * @default MeshBasicMaterial
  17111. */
  17112. this.material = material;
  17113. /**
  17114. * A dictionary representing the morph targets in the geometry. The key is the
  17115. * morph targets name, the value its attribute index. This member is `undefined`
  17116. * by default and only set when morph targets are detected in the geometry.
  17117. *
  17118. * @type {Object<string,number>|undefined}
  17119. * @default undefined
  17120. */
  17121. this.morphTargetDictionary = undefined;
  17122. /**
  17123. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17124. * is applied. This member is `undefined` by default and only set when morph targets are
  17125. * detected in the geometry.
  17126. *
  17127. * @type {Array<number>|undefined}
  17128. * @default undefined
  17129. */
  17130. this.morphTargetInfluences = undefined;
  17131. /**
  17132. * The number of instances of this mesh.
  17133. * Can only be used with {@link WebGPURenderer}.
  17134. *
  17135. * @type {number}
  17136. * @default 1
  17137. */
  17138. this.count = 1;
  17139. this.updateMorphTargets();
  17140. }
  17141. copy( source, recursive ) {
  17142. super.copy( source, recursive );
  17143. if ( source.morphTargetInfluences !== undefined ) {
  17144. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17145. }
  17146. if ( source.morphTargetDictionary !== undefined ) {
  17147. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17148. }
  17149. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17150. this.geometry = source.geometry;
  17151. return this;
  17152. }
  17153. /**
  17154. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17155. * to make sure existing morph targets can influence this 3D object.
  17156. */
  17157. updateMorphTargets() {
  17158. const geometry = this.geometry;
  17159. const morphAttributes = geometry.morphAttributes;
  17160. const keys = Object.keys( morphAttributes );
  17161. if ( keys.length > 0 ) {
  17162. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17163. if ( morphAttribute !== undefined ) {
  17164. this.morphTargetInfluences = [];
  17165. this.morphTargetDictionary = {};
  17166. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17167. const name = morphAttribute[ m ].name || String( m );
  17168. this.morphTargetInfluences.push( 0 );
  17169. this.morphTargetDictionary[ name ] = m;
  17170. }
  17171. }
  17172. }
  17173. }
  17174. /**
  17175. * Returns the local-space position of the vertex at the given index, taking into
  17176. * account the current animation state of both morph targets and skinning.
  17177. *
  17178. * @param {number} index - The vertex index.
  17179. * @param {Vector3} target - The target object that is used to store the method's result.
  17180. * @return {Vector3} The vertex position in local space.
  17181. */
  17182. getVertexPosition( index, target ) {
  17183. const geometry = this.geometry;
  17184. const position = geometry.attributes.position;
  17185. const morphPosition = geometry.morphAttributes.position;
  17186. const morphTargetsRelative = geometry.morphTargetsRelative;
  17187. target.fromBufferAttribute( position, index );
  17188. const morphInfluences = this.morphTargetInfluences;
  17189. if ( morphPosition && morphInfluences ) {
  17190. _morphA.set( 0, 0, 0 );
  17191. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17192. const influence = morphInfluences[ i ];
  17193. const morphAttribute = morphPosition[ i ];
  17194. if ( influence === 0 ) continue;
  17195. _tempA.fromBufferAttribute( morphAttribute, index );
  17196. if ( morphTargetsRelative ) {
  17197. _morphA.addScaledVector( _tempA, influence );
  17198. } else {
  17199. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17200. }
  17201. }
  17202. target.add( _morphA );
  17203. }
  17204. return target;
  17205. }
  17206. /**
  17207. * Computes intersection points between a casted ray and this line.
  17208. *
  17209. * @param {Raycaster} raycaster - The raycaster.
  17210. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17211. */
  17212. raycast( raycaster, intersects ) {
  17213. const geometry = this.geometry;
  17214. const material = this.material;
  17215. const matrixWorld = this.matrixWorld;
  17216. if ( material === undefined ) return;
  17217. // test with bounding sphere in world space
  17218. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17219. _sphere$6.copy( geometry.boundingSphere );
  17220. _sphere$6.applyMatrix4( matrixWorld );
  17221. // check distance from ray origin to bounding sphere
  17222. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17223. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17224. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17225. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17226. }
  17227. // convert ray to local space of mesh
  17228. _inverseMatrix$3.copy( matrixWorld ).invert();
  17229. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17230. // test with bounding box in local space
  17231. if ( geometry.boundingBox !== null ) {
  17232. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17233. }
  17234. // test for intersections with geometry
  17235. this._computeIntersections( raycaster, intersects, _ray$3 );
  17236. }
  17237. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17238. let intersection;
  17239. const geometry = this.geometry;
  17240. const material = this.material;
  17241. const index = geometry.index;
  17242. const position = geometry.attributes.position;
  17243. const uv = geometry.attributes.uv;
  17244. const uv1 = geometry.attributes.uv1;
  17245. const normal = geometry.attributes.normal;
  17246. const groups = geometry.groups;
  17247. const drawRange = geometry.drawRange;
  17248. if ( index !== null ) {
  17249. // indexed buffer geometry
  17250. if ( Array.isArray( material ) ) {
  17251. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17252. const group = groups[ i ];
  17253. const groupMaterial = material[ group.materialIndex ];
  17254. const start = Math.max( group.start, drawRange.start );
  17255. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17256. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17257. const a = index.getX( j );
  17258. const b = index.getX( j + 1 );
  17259. const c = index.getX( j + 2 );
  17260. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17261. if ( intersection ) {
  17262. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17263. intersection.face.materialIndex = group.materialIndex;
  17264. intersects.push( intersection );
  17265. }
  17266. }
  17267. }
  17268. } else {
  17269. const start = Math.max( 0, drawRange.start );
  17270. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17271. for ( let i = start, il = end; i < il; i += 3 ) {
  17272. const a = index.getX( i );
  17273. const b = index.getX( i + 1 );
  17274. const c = index.getX( i + 2 );
  17275. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17276. if ( intersection ) {
  17277. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17278. intersects.push( intersection );
  17279. }
  17280. }
  17281. }
  17282. } else if ( position !== undefined ) {
  17283. // non-indexed buffer geometry
  17284. if ( Array.isArray( material ) ) {
  17285. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17286. const group = groups[ i ];
  17287. const groupMaterial = material[ group.materialIndex ];
  17288. const start = Math.max( group.start, drawRange.start );
  17289. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17290. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17291. const a = j;
  17292. const b = j + 1;
  17293. const c = j + 2;
  17294. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17295. if ( intersection ) {
  17296. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17297. intersection.face.materialIndex = group.materialIndex;
  17298. intersects.push( intersection );
  17299. }
  17300. }
  17301. }
  17302. } else {
  17303. const start = Math.max( 0, drawRange.start );
  17304. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17305. for ( let i = start, il = end; i < il; i += 3 ) {
  17306. const a = i;
  17307. const b = i + 1;
  17308. const c = i + 2;
  17309. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17310. if ( intersection ) {
  17311. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17312. intersects.push( intersection );
  17313. }
  17314. }
  17315. }
  17316. }
  17317. }
  17318. }
  17319. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17320. let intersect;
  17321. if ( material.side === BackSide ) {
  17322. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17323. } else {
  17324. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17325. }
  17326. if ( intersect === null ) return null;
  17327. _intersectionPointWorld.copy( point );
  17328. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17329. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17330. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17331. return {
  17332. distance: distance,
  17333. point: _intersectionPointWorld.clone(),
  17334. object: object
  17335. };
  17336. }
  17337. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17338. object.getVertexPosition( a, _vA );
  17339. object.getVertexPosition( b, _vB );
  17340. object.getVertexPosition( c, _vC );
  17341. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17342. if ( intersection ) {
  17343. const barycoord = new Vector3();
  17344. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17345. if ( uv ) {
  17346. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17347. }
  17348. if ( uv1 ) {
  17349. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17350. }
  17351. if ( normal ) {
  17352. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17353. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17354. intersection.normal.multiplyScalar( -1 );
  17355. }
  17356. }
  17357. const face = {
  17358. a: a,
  17359. b: b,
  17360. c: c,
  17361. normal: new Vector3(),
  17362. materialIndex: 0
  17363. };
  17364. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17365. intersection.face = face;
  17366. intersection.barycoord = barycoord;
  17367. }
  17368. return intersection;
  17369. }
  17370. const _basePosition = /*@__PURE__*/ new Vector3();
  17371. const _skinIndex = /*@__PURE__*/ new Vector4();
  17372. const _skinWeight = /*@__PURE__*/ new Vector4();
  17373. const _vector3 = /*@__PURE__*/ new Vector3();
  17374. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17375. const _vertex = /*@__PURE__*/ new Vector3();
  17376. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17377. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17378. const _ray$2 = /*@__PURE__*/ new Ray();
  17379. /**
  17380. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17381. * vertices of the geometry with skinning/skeleton animation.
  17382. *
  17383. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17384. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17385. * vertex to a certain extend.
  17386. *
  17387. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17388. * or {@link FBXLoader } import respective models.
  17389. *
  17390. * @augments Mesh
  17391. * @demo scenes/bones-browser.html
  17392. */
  17393. class SkinnedMesh extends Mesh {
  17394. /**
  17395. * Constructs a new skinned mesh.
  17396. *
  17397. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17398. * @param {Material|Array<Material>} [material] - The mesh material.
  17399. */
  17400. constructor( geometry, material ) {
  17401. super( geometry, material );
  17402. /**
  17403. * This flag can be used for type testing.
  17404. *
  17405. * @type {boolean}
  17406. * @readonly
  17407. * @default true
  17408. */
  17409. this.isSkinnedMesh = true;
  17410. this.type = 'SkinnedMesh';
  17411. /**
  17412. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17413. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17414. * across multiple skinned meshes.
  17415. *
  17416. * @type {(AttachedBindMode|DetachedBindMode)}
  17417. * @default AttachedBindMode
  17418. */
  17419. this.bindMode = AttachedBindMode;
  17420. /**
  17421. * The base matrix that is used for the bound bone transforms.
  17422. *
  17423. * @type {Matrix4}
  17424. */
  17425. this.bindMatrix = new Matrix4();
  17426. /**
  17427. * The base matrix that is used for resetting the bound bone transforms.
  17428. *
  17429. * @type {Matrix4}
  17430. */
  17431. this.bindMatrixInverse = new Matrix4();
  17432. /**
  17433. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17434. *
  17435. * @type {?Box3}
  17436. * @default null
  17437. */
  17438. this.boundingBox = null;
  17439. /**
  17440. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17441. *
  17442. * @type {?Sphere}
  17443. * @default null
  17444. */
  17445. this.boundingSphere = null;
  17446. }
  17447. /**
  17448. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17449. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17450. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17451. * the current animation state.
  17452. */
  17453. computeBoundingBox() {
  17454. const geometry = this.geometry;
  17455. if ( this.boundingBox === null ) {
  17456. this.boundingBox = new Box3();
  17457. }
  17458. this.boundingBox.makeEmpty();
  17459. const positionAttribute = geometry.getAttribute( 'position' );
  17460. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17461. this.getVertexPosition( i, _vertex );
  17462. this.boundingBox.expandByPoint( _vertex );
  17463. }
  17464. }
  17465. /**
  17466. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17467. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17468. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17469. * per frame in order to reflect the current animation state.
  17470. */
  17471. computeBoundingSphere() {
  17472. const geometry = this.geometry;
  17473. if ( this.boundingSphere === null ) {
  17474. this.boundingSphere = new Sphere();
  17475. }
  17476. this.boundingSphere.makeEmpty();
  17477. const positionAttribute = geometry.getAttribute( 'position' );
  17478. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17479. this.getVertexPosition( i, _vertex );
  17480. this.boundingSphere.expandByPoint( _vertex );
  17481. }
  17482. }
  17483. copy( source, recursive ) {
  17484. super.copy( source, recursive );
  17485. this.bindMode = source.bindMode;
  17486. this.bindMatrix.copy( source.bindMatrix );
  17487. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17488. this.skeleton = source.skeleton;
  17489. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17490. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17491. return this;
  17492. }
  17493. raycast( raycaster, intersects ) {
  17494. const material = this.material;
  17495. const matrixWorld = this.matrixWorld;
  17496. if ( material === undefined ) return;
  17497. // test with bounding sphere in world space
  17498. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17499. _sphere$5.copy( this.boundingSphere );
  17500. _sphere$5.applyMatrix4( matrixWorld );
  17501. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17502. // convert ray to local space of skinned mesh
  17503. _inverseMatrix$2.copy( matrixWorld ).invert();
  17504. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17505. // test with bounding box in local space
  17506. if ( this.boundingBox !== null ) {
  17507. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17508. }
  17509. // test for intersections with geometry
  17510. this._computeIntersections( raycaster, intersects, _ray$2 );
  17511. }
  17512. getVertexPosition( index, target ) {
  17513. super.getVertexPosition( index, target );
  17514. this.applyBoneTransform( index, target );
  17515. return target;
  17516. }
  17517. /**
  17518. * Binds the given skeleton to the skinned mesh.
  17519. *
  17520. * @param {Skeleton} skeleton - The skeleton to bind.
  17521. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17522. * the skinned mesh's world matrix will be used instead.
  17523. */
  17524. bind( skeleton, bindMatrix ) {
  17525. this.skeleton = skeleton;
  17526. if ( bindMatrix === undefined ) {
  17527. this.updateMatrixWorld( true );
  17528. this.skeleton.calculateInverses();
  17529. bindMatrix = this.matrixWorld;
  17530. }
  17531. this.bindMatrix.copy( bindMatrix );
  17532. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17533. }
  17534. /**
  17535. * This method sets the skinned mesh in the rest pose).
  17536. */
  17537. pose() {
  17538. this.skeleton.pose();
  17539. }
  17540. /**
  17541. * Normalizes the skin weights which are defined as a buffer attribute
  17542. * in the skinned mesh's geometry.
  17543. */
  17544. normalizeSkinWeights() {
  17545. const vector = new Vector4();
  17546. const skinWeight = this.geometry.attributes.skinWeight;
  17547. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17548. vector.fromBufferAttribute( skinWeight, i );
  17549. const scale = 1.0 / vector.manhattanLength();
  17550. if ( scale !== Infinity ) {
  17551. vector.multiplyScalar( scale );
  17552. } else {
  17553. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17554. }
  17555. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17556. }
  17557. }
  17558. updateMatrixWorld( force ) {
  17559. super.updateMatrixWorld( force );
  17560. if ( this.bindMode === AttachedBindMode ) {
  17561. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17562. } else if ( this.bindMode === DetachedBindMode ) {
  17563. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17564. } else {
  17565. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17566. }
  17567. }
  17568. /**
  17569. * Applies the bone transform associated with the given index to the given
  17570. * vertex position. Returns the updated vector.
  17571. *
  17572. * @param {number} index - The vertex index.
  17573. * @param {Vector3} target - The target object that is used to store the method's result.
  17574. * the skinned mesh's world matrix will be used instead.
  17575. * @return {Vector3} The updated vertex position.
  17576. */
  17577. applyBoneTransform( index, target ) {
  17578. const skeleton = this.skeleton;
  17579. const geometry = this.geometry;
  17580. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17581. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17582. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17583. target.set( 0, 0, 0 );
  17584. for ( let i = 0; i < 4; i ++ ) {
  17585. const weight = _skinWeight.getComponent( i );
  17586. if ( weight !== 0 ) {
  17587. const boneIndex = _skinIndex.getComponent( i );
  17588. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17589. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  17590. }
  17591. }
  17592. return target.applyMatrix4( this.bindMatrixInverse );
  17593. }
  17594. }
  17595. /**
  17596. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17597. * the {@link SkinnedMesh}.
  17598. *
  17599. * ```js
  17600. * const root = new THREE.Bone();
  17601. * const child = new THREE.Bone();
  17602. *
  17603. * root.add( child );
  17604. * child.position.y = 5;
  17605. * ```
  17606. *
  17607. * @augments Object3D
  17608. */
  17609. class Bone extends Object3D {
  17610. /**
  17611. * Constructs a new bone.
  17612. */
  17613. constructor() {
  17614. super();
  17615. /**
  17616. * This flag can be used for type testing.
  17617. *
  17618. * @type {boolean}
  17619. * @readonly
  17620. * @default true
  17621. */
  17622. this.isBone = true;
  17623. this.type = 'Bone';
  17624. }
  17625. }
  17626. /**
  17627. * Creates a texture directly from raw buffer data.
  17628. *
  17629. * The interpretation of the data depends on type and format: If the type is
  17630. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17631. * texel data. If the format is `RGBAFormat`, data needs four values for
  17632. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17633. *
  17634. * @augments Texture
  17635. */
  17636. class DataTexture extends Texture {
  17637. /**
  17638. * Constructs a new data texture.
  17639. *
  17640. * @param {?TypedArray} [data=null] - The buffer data.
  17641. * @param {number} [width=1] - The width of the texture.
  17642. * @param {number} [height=1] - The height of the texture.
  17643. * @param {number} [format=RGBAFormat] - The texture format.
  17644. * @param {number} [type=UnsignedByteType] - The texture type.
  17645. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17646. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17647. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17648. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17649. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17650. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17651. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17652. */
  17653. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17654. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17655. /**
  17656. * This flag can be used for type testing.
  17657. *
  17658. * @type {boolean}
  17659. * @readonly
  17660. * @default true
  17661. */
  17662. this.isDataTexture = true;
  17663. /**
  17664. * The image definition of a data texture.
  17665. *
  17666. * @type {{data:TypedArray,width:number,height:number}}
  17667. */
  17668. this.image = { data: data, width: width, height: height };
  17669. /**
  17670. * Whether to generate mipmaps (if possible) for a texture.
  17671. *
  17672. * Overwritten and set to `false` by default.
  17673. *
  17674. * @type {boolean}
  17675. * @default false
  17676. */
  17677. this.generateMipmaps = false;
  17678. /**
  17679. * If set to `true`, the texture is flipped along the vertical axis when
  17680. * uploaded to the GPU.
  17681. *
  17682. * Overwritten and set to `false` by default.
  17683. *
  17684. * @type {boolean}
  17685. * @default false
  17686. */
  17687. this.flipY = false;
  17688. /**
  17689. * Specifies the alignment requirements for the start of each pixel row in memory.
  17690. *
  17691. * Overwritten and set to `1` by default.
  17692. *
  17693. * @type {boolean}
  17694. * @default 1
  17695. */
  17696. this.unpackAlignment = 1;
  17697. }
  17698. }
  17699. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17700. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17701. /**
  17702. * Class for representing the armatures in `three.js`. The skeleton
  17703. * is defined by a hierarchy of bones.
  17704. *
  17705. * ```js
  17706. * const bones = [];
  17707. *
  17708. * const shoulder = new THREE.Bone();
  17709. * const elbow = new THREE.Bone();
  17710. * const hand = new THREE.Bone();
  17711. *
  17712. * shoulder.add( elbow );
  17713. * elbow.add( hand );
  17714. *
  17715. * bones.push( shoulder , elbow, hand);
  17716. *
  17717. * shoulder.position.y = -5;
  17718. * elbow.position.y = 0;
  17719. * hand.position.y = 5;
  17720. *
  17721. * const armSkeleton = new THREE.Skeleton( bones );
  17722. * ```
  17723. */
  17724. class Skeleton {
  17725. /**
  17726. * Constructs a new skeleton.
  17727. *
  17728. * @param {Array<Bone>} [bones] - An array of bones.
  17729. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  17730. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  17731. */
  17732. constructor( bones = [], boneInverses = [] ) {
  17733. this.uuid = generateUUID();
  17734. /**
  17735. * An array of bones defining the skeleton.
  17736. *
  17737. * @type {Array<Bone>}
  17738. */
  17739. this.bones = bones.slice( 0 );
  17740. /**
  17741. * An array of bone inverse matrices.
  17742. *
  17743. * @type {Array<Matrix4>}
  17744. */
  17745. this.boneInverses = boneInverses;
  17746. /**
  17747. * An array buffer holding the bone data.
  17748. * Input data for {@link Skeleton#boneTexture}.
  17749. *
  17750. * @type {?Float32Array}
  17751. * @default null
  17752. */
  17753. this.boneMatrices = null;
  17754. /**
  17755. * An array buffer holding the bone data of the previous frame.
  17756. * Required for computing velocity. Maintained in {@link SkinningNode}.
  17757. *
  17758. * @type {?Float32Array}
  17759. * @default null
  17760. */
  17761. this.previousBoneMatrices = null;
  17762. /**
  17763. * A texture holding the bone data for use
  17764. * in the vertex shader.
  17765. *
  17766. * @type {?DataTexture}
  17767. * @default null
  17768. */
  17769. this.boneTexture = null;
  17770. this.init();
  17771. }
  17772. /**
  17773. * Initializes the skeleton. This method gets automatically called by the constructor
  17774. * but depending on how the skeleton is created it might be necessary to call this method
  17775. * manually.
  17776. */
  17777. init() {
  17778. const bones = this.bones;
  17779. const boneInverses = this.boneInverses;
  17780. this.boneMatrices = new Float32Array( bones.length * 16 );
  17781. // calculate inverse bone matrices if necessary
  17782. if ( boneInverses.length === 0 ) {
  17783. this.calculateInverses();
  17784. } else {
  17785. // handle special case
  17786. if ( bones.length !== boneInverses.length ) {
  17787. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17788. this.boneInverses = [];
  17789. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17790. this.boneInverses.push( new Matrix4() );
  17791. }
  17792. }
  17793. }
  17794. }
  17795. /**
  17796. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  17797. * and fills it with new matrices.
  17798. */
  17799. calculateInverses() {
  17800. this.boneInverses.length = 0;
  17801. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17802. const inverse = new Matrix4();
  17803. if ( this.bones[ i ] ) {
  17804. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17805. }
  17806. this.boneInverses.push( inverse );
  17807. }
  17808. }
  17809. /**
  17810. * Resets the skeleton to the base pose.
  17811. */
  17812. pose() {
  17813. // recover the bind-time world matrices
  17814. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17815. const bone = this.bones[ i ];
  17816. if ( bone ) {
  17817. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17818. }
  17819. }
  17820. // compute the local matrices, positions, rotations and scales
  17821. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17822. const bone = this.bones[ i ];
  17823. if ( bone ) {
  17824. if ( bone.parent && bone.parent.isBone ) {
  17825. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17826. bone.matrix.multiply( bone.matrixWorld );
  17827. } else {
  17828. bone.matrix.copy( bone.matrixWorld );
  17829. }
  17830. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17831. }
  17832. }
  17833. }
  17834. /**
  17835. * Resets the skeleton to the base pose.
  17836. */
  17837. update() {
  17838. const bones = this.bones;
  17839. const boneInverses = this.boneInverses;
  17840. const boneMatrices = this.boneMatrices;
  17841. const boneTexture = this.boneTexture;
  17842. // flatten bone matrices to array
  17843. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17844. // compute the offset between the current and the original transform
  17845. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17846. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17847. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17848. }
  17849. if ( boneTexture !== null ) {
  17850. boneTexture.needsUpdate = true;
  17851. }
  17852. }
  17853. /**
  17854. * Returns a new skeleton with copied values from this instance.
  17855. *
  17856. * @return {Skeleton} A clone of this instance.
  17857. */
  17858. clone() {
  17859. return new Skeleton( this.bones, this.boneInverses );
  17860. }
  17861. /**
  17862. * Computes a data texture for passing bone data to the vertex shader.
  17863. *
  17864. * @return {Skeleton} A reference of this instance.
  17865. */
  17866. computeBoneTexture() {
  17867. // layout (1 matrix = 4 pixels)
  17868. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17869. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17870. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17871. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17872. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17873. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17874. size = Math.ceil( size / 4 ) * 4;
  17875. size = Math.max( size, 4 );
  17876. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17877. boneMatrices.set( this.boneMatrices ); // copy current values
  17878. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17879. boneTexture.needsUpdate = true;
  17880. this.boneMatrices = boneMatrices;
  17881. this.boneTexture = boneTexture;
  17882. return this;
  17883. }
  17884. /**
  17885. * Searches through the skeleton's bone array and returns the first with a
  17886. * matching name.
  17887. *
  17888. * @param {string} name - The name of the bone.
  17889. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  17890. */
  17891. getBoneByName( name ) {
  17892. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17893. const bone = this.bones[ i ];
  17894. if ( bone.name === name ) {
  17895. return bone;
  17896. }
  17897. }
  17898. return undefined;
  17899. }
  17900. /**
  17901. * Frees the GPU-related resources allocated by this instance. Call this
  17902. * method whenever this instance is no longer used in your app.
  17903. */
  17904. dispose( ) {
  17905. if ( this.boneTexture !== null ) {
  17906. this.boneTexture.dispose();
  17907. this.boneTexture = null;
  17908. }
  17909. }
  17910. /**
  17911. * Setups the skeleton by the given JSON and bones.
  17912. *
  17913. * @param {Object} json - The skeleton as serialized JSON.
  17914. * @param {Object<string, Bone>} bones - An array of bones.
  17915. * @return {Skeleton} A reference of this instance.
  17916. */
  17917. fromJSON( json, bones ) {
  17918. this.uuid = json.uuid;
  17919. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17920. const uuid = json.bones[ i ];
  17921. let bone = bones[ uuid ];
  17922. if ( bone === undefined ) {
  17923. warn( 'Skeleton: No bone found with UUID:', uuid );
  17924. bone = new Bone();
  17925. }
  17926. this.bones.push( bone );
  17927. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17928. }
  17929. this.init();
  17930. return this;
  17931. }
  17932. /**
  17933. * Serializes the skeleton into JSON.
  17934. *
  17935. * @return {Object} A JSON object representing the serialized skeleton.
  17936. * @see {@link ObjectLoader#parse}
  17937. */
  17938. toJSON() {
  17939. const data = {
  17940. metadata: {
  17941. version: 4.7,
  17942. type: 'Skeleton',
  17943. generator: 'Skeleton.toJSON'
  17944. },
  17945. bones: [],
  17946. boneInverses: []
  17947. };
  17948. data.uuid = this.uuid;
  17949. const bones = this.bones;
  17950. const boneInverses = this.boneInverses;
  17951. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17952. const bone = bones[ i ];
  17953. data.bones.push( bone.uuid );
  17954. const boneInverse = boneInverses[ i ];
  17955. data.boneInverses.push( boneInverse.toArray() );
  17956. }
  17957. return data;
  17958. }
  17959. }
  17960. /**
  17961. * An instanced version of a buffer attribute.
  17962. *
  17963. * @augments BufferAttribute
  17964. */
  17965. class InstancedBufferAttribute extends BufferAttribute {
  17966. /**
  17967. * Constructs a new instanced buffer attribute.
  17968. *
  17969. * @param {TypedArray} array - The array holding the attribute data.
  17970. * @param {number} itemSize - The item size.
  17971. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17972. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  17973. */
  17974. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17975. super( array, itemSize, normalized );
  17976. /**
  17977. * This flag can be used for type testing.
  17978. *
  17979. * @type {boolean}
  17980. * @readonly
  17981. * @default true
  17982. */
  17983. this.isInstancedBufferAttribute = true;
  17984. /**
  17985. * Defines how often a value of this buffer attribute should be repeated. A
  17986. * value of one means that each value of the instanced attribute is used for
  17987. * a single instance. A value of two means that each value is used for two
  17988. * consecutive instances (and so on).
  17989. *
  17990. * @type {number}
  17991. * @default 1
  17992. */
  17993. this.meshPerAttribute = meshPerAttribute;
  17994. }
  17995. copy( source ) {
  17996. super.copy( source );
  17997. this.meshPerAttribute = source.meshPerAttribute;
  17998. return this;
  17999. }
  18000. toJSON() {
  18001. const data = super.toJSON();
  18002. data.meshPerAttribute = this.meshPerAttribute;
  18003. data.isInstancedBufferAttribute = true;
  18004. return data;
  18005. }
  18006. }
  18007. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18008. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18009. const _instanceIntersects = [];
  18010. const _box3 = /*@__PURE__*/ new Box3();
  18011. const _identity = /*@__PURE__*/ new Matrix4();
  18012. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18013. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18014. /**
  18015. * A special version of a mesh with instanced rendering support. Use
  18016. * this class if you have to render a large number of objects with the same
  18017. * geometry and material(s) but with different world transformations. The usage
  18018. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18019. * improve the overall rendering performance in your application.
  18020. *
  18021. * @augments Mesh
  18022. */
  18023. class InstancedMesh extends Mesh {
  18024. /**
  18025. * Constructs a new instanced mesh.
  18026. *
  18027. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18028. * @param {Material|Array<Material>} [material] - The mesh material.
  18029. * @param {number} count - The number of instances.
  18030. */
  18031. constructor( geometry, material, count ) {
  18032. super( geometry, material );
  18033. /**
  18034. * This flag can be used for type testing.
  18035. *
  18036. * @type {boolean}
  18037. * @readonly
  18038. * @default true
  18039. */
  18040. this.isInstancedMesh = true;
  18041. /**
  18042. * Represents the local transformation of all instances. You have to set its
  18043. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18044. * via {@link InstancedMesh#setMatrixAt}.
  18045. *
  18046. * @type {InstancedBufferAttribute}
  18047. */
  18048. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18049. /**
  18050. * Represents the local transformation of all instances of the previous frame.
  18051. * Required for computing velocity. Maintained in {@link InstanceNode}.
  18052. *
  18053. * @type {?InstancedBufferAttribute}
  18054. * @default null
  18055. */
  18056. this.previousInstanceMatrix = null;
  18057. /**
  18058. * Represents the color of all instances. You have to set its
  18059. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18060. * via {@link InstancedMesh#setColorAt}.
  18061. *
  18062. * @type {?InstancedBufferAttribute}
  18063. * @default null
  18064. */
  18065. this.instanceColor = null;
  18066. /**
  18067. * Represents the morph target weights of all instances. You have to set its
  18068. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18069. * via {@link InstancedMesh#setMorphAt}.
  18070. *
  18071. * @type {?DataTexture}
  18072. * @default null
  18073. */
  18074. this.morphTexture = null;
  18075. /**
  18076. * The number of instances.
  18077. *
  18078. * @type {number}
  18079. */
  18080. this.count = count;
  18081. /**
  18082. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18083. *
  18084. * @type {?Box3}
  18085. * @default null
  18086. */
  18087. this.boundingBox = null;
  18088. /**
  18089. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18090. *
  18091. * @type {?Sphere}
  18092. * @default null
  18093. */
  18094. this.boundingSphere = null;
  18095. for ( let i = 0; i < count; i ++ ) {
  18096. this.setMatrixAt( i, _identity );
  18097. }
  18098. }
  18099. /**
  18100. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18101. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18102. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18103. */
  18104. computeBoundingBox() {
  18105. const geometry = this.geometry;
  18106. const count = this.count;
  18107. if ( this.boundingBox === null ) {
  18108. this.boundingBox = new Box3();
  18109. }
  18110. if ( geometry.boundingBox === null ) {
  18111. geometry.computeBoundingBox();
  18112. }
  18113. this.boundingBox.makeEmpty();
  18114. for ( let i = 0; i < count; i ++ ) {
  18115. this.getMatrixAt( i, _instanceLocalMatrix );
  18116. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18117. this.boundingBox.union( _box3 );
  18118. }
  18119. }
  18120. /**
  18121. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18122. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18123. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18124. */
  18125. computeBoundingSphere() {
  18126. const geometry = this.geometry;
  18127. const count = this.count;
  18128. if ( this.boundingSphere === null ) {
  18129. this.boundingSphere = new Sphere();
  18130. }
  18131. if ( geometry.boundingSphere === null ) {
  18132. geometry.computeBoundingSphere();
  18133. }
  18134. this.boundingSphere.makeEmpty();
  18135. for ( let i = 0; i < count; i ++ ) {
  18136. this.getMatrixAt( i, _instanceLocalMatrix );
  18137. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18138. this.boundingSphere.union( _sphere$4 );
  18139. }
  18140. }
  18141. copy( source, recursive ) {
  18142. super.copy( source, recursive );
  18143. this.instanceMatrix.copy( source.instanceMatrix );
  18144. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  18145. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18146. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18147. this.count = source.count;
  18148. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18149. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18150. return this;
  18151. }
  18152. /**
  18153. * Gets the color of the defined instance.
  18154. *
  18155. * @param {number} index - The instance index.
  18156. * @param {Color} color - The target object that is used to store the method's result.
  18157. */
  18158. getColorAt( index, color ) {
  18159. color.fromArray( this.instanceColor.array, index * 3 );
  18160. }
  18161. /**
  18162. * Gets the local transformation matrix of the defined instance.
  18163. *
  18164. * @param {number} index - The instance index.
  18165. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18166. */
  18167. getMatrixAt( index, matrix ) {
  18168. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18169. }
  18170. /**
  18171. * Gets the morph target weights of the defined instance.
  18172. *
  18173. * @param {number} index - The instance index.
  18174. * @param {Mesh} object - The target object that is used to store the method's result.
  18175. */
  18176. getMorphAt( index, object ) {
  18177. const objectInfluences = object.morphTargetInfluences;
  18178. const array = this.morphTexture.source.data.data;
  18179. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18180. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18181. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18182. objectInfluences[ i ] = array[ dataIndex + i ];
  18183. }
  18184. }
  18185. raycast( raycaster, intersects ) {
  18186. const matrixWorld = this.matrixWorld;
  18187. const raycastTimes = this.count;
  18188. _mesh$1.geometry = this.geometry;
  18189. _mesh$1.material = this.material;
  18190. if ( _mesh$1.material === undefined ) return;
  18191. // test with bounding sphere first
  18192. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18193. _sphere$4.copy( this.boundingSphere );
  18194. _sphere$4.applyMatrix4( matrixWorld );
  18195. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18196. // now test each instance
  18197. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18198. // calculate the world matrix for each instance
  18199. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18200. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18201. // the mesh represents this single instance
  18202. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18203. _mesh$1.raycast( raycaster, _instanceIntersects );
  18204. // process the result of raycast
  18205. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18206. const intersect = _instanceIntersects[ i ];
  18207. intersect.instanceId = instanceId;
  18208. intersect.object = this;
  18209. intersects.push( intersect );
  18210. }
  18211. _instanceIntersects.length = 0;
  18212. }
  18213. }
  18214. /**
  18215. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18216. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18217. *
  18218. * @param {number} index - The instance index.
  18219. * @param {Color} color - The instance color.
  18220. */
  18221. setColorAt( index, color ) {
  18222. if ( this.instanceColor === null ) {
  18223. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18224. }
  18225. color.toArray( this.instanceColor.array, index * 3 );
  18226. }
  18227. /**
  18228. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18229. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  18230. *
  18231. * @param {number} index - The instance index.
  18232. * @param {Matrix4} matrix - The local transformation.
  18233. */
  18234. setMatrixAt( index, matrix ) {
  18235. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18236. }
  18237. /**
  18238. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18239. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18240. *
  18241. * @param {number} index - The instance index.
  18242. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18243. * of a single instance.
  18244. */
  18245. setMorphAt( index, object ) {
  18246. const objectInfluences = object.morphTargetInfluences;
  18247. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18248. if ( this.morphTexture === null ) {
  18249. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18250. }
  18251. const array = this.morphTexture.source.data.data;
  18252. let morphInfluencesSum = 0;
  18253. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18254. morphInfluencesSum += objectInfluences[ i ];
  18255. }
  18256. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18257. const dataIndex = len * index;
  18258. array[ dataIndex ] = morphBaseInfluence;
  18259. array.set( objectInfluences, dataIndex + 1 );
  18260. }
  18261. updateMorphTargets() {
  18262. }
  18263. /**
  18264. * Frees the GPU-related resources allocated by this instance. Call this
  18265. * method whenever this instance is no longer used in your app.
  18266. */
  18267. dispose() {
  18268. this.dispatchEvent( { type: 'dispose' } );
  18269. if ( this.morphTexture !== null ) {
  18270. this.morphTexture.dispose();
  18271. this.morphTexture = null;
  18272. }
  18273. }
  18274. }
  18275. const _vector1 = /*@__PURE__*/ new Vector3();
  18276. const _vector2 = /*@__PURE__*/ new Vector3();
  18277. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18278. /**
  18279. * A two dimensional surface that extends infinitely in 3D space, represented
  18280. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18281. * by a unit length normal vector and a constant.
  18282. */
  18283. class Plane {
  18284. /**
  18285. * Constructs a new plane.
  18286. *
  18287. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18288. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18289. */
  18290. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18291. /**
  18292. * This flag can be used for type testing.
  18293. *
  18294. * @type {boolean}
  18295. * @readonly
  18296. * @default true
  18297. */
  18298. this.isPlane = true;
  18299. /**
  18300. * A unit length vector defining the normal of the plane.
  18301. *
  18302. * @type {Vector3}
  18303. */
  18304. this.normal = normal;
  18305. /**
  18306. * The signed distance from the origin to the plane.
  18307. *
  18308. * @type {number}
  18309. * @default 0
  18310. */
  18311. this.constant = constant;
  18312. }
  18313. /**
  18314. * Sets the plane components by copying the given values.
  18315. *
  18316. * @param {Vector3} normal - The normal.
  18317. * @param {number} constant - The constant.
  18318. * @return {Plane} A reference to this plane.
  18319. */
  18320. set( normal, constant ) {
  18321. this.normal.copy( normal );
  18322. this.constant = constant;
  18323. return this;
  18324. }
  18325. /**
  18326. * Sets the plane components by defining `x`, `y`, `z` as the
  18327. * plane normal and `w` as the constant.
  18328. *
  18329. * @param {number} x - The value for the normal's x component.
  18330. * @param {number} y - The value for the normal's y component.
  18331. * @param {number} z - The value for the normal's z component.
  18332. * @param {number} w - The constant value.
  18333. * @return {Plane} A reference to this plane.
  18334. */
  18335. setComponents( x, y, z, w ) {
  18336. this.normal.set( x, y, z );
  18337. this.constant = w;
  18338. return this;
  18339. }
  18340. /**
  18341. * Sets the plane from the given normal and coplanar point (that is a point
  18342. * that lies onto the plane).
  18343. *
  18344. * @param {Vector3} normal - The normal.
  18345. * @param {Vector3} point - A coplanar point.
  18346. * @return {Plane} A reference to this plane.
  18347. */
  18348. setFromNormalAndCoplanarPoint( normal, point ) {
  18349. this.normal.copy( normal );
  18350. this.constant = - point.dot( this.normal );
  18351. return this;
  18352. }
  18353. /**
  18354. * Sets the plane from three coplanar points. The winding order is
  18355. * assumed to be counter-clockwise, and determines the direction of
  18356. * the plane normal.
  18357. *
  18358. * @param {Vector3} a - The first coplanar point.
  18359. * @param {Vector3} b - The second coplanar point.
  18360. * @param {Vector3} c - The third coplanar point.
  18361. * @return {Plane} A reference to this plane.
  18362. */
  18363. setFromCoplanarPoints( a, b, c ) {
  18364. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18365. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18366. this.setFromNormalAndCoplanarPoint( normal, a );
  18367. return this;
  18368. }
  18369. /**
  18370. * Copies the values of the given plane to this instance.
  18371. *
  18372. * @param {Plane} plane - The plane to copy.
  18373. * @return {Plane} A reference to this plane.
  18374. */
  18375. copy( plane ) {
  18376. this.normal.copy( plane.normal );
  18377. this.constant = plane.constant;
  18378. return this;
  18379. }
  18380. /**
  18381. * Normalizes the plane normal and adjusts the constant accordingly.
  18382. *
  18383. * @return {Plane} A reference to this plane.
  18384. */
  18385. normalize() {
  18386. // Note: will lead to a divide by zero if the plane is invalid.
  18387. const inverseNormalLength = 1.0 / this.normal.length();
  18388. this.normal.multiplyScalar( inverseNormalLength );
  18389. this.constant *= inverseNormalLength;
  18390. return this;
  18391. }
  18392. /**
  18393. * Negates both the plane normal and the constant.
  18394. *
  18395. * @return {Plane} A reference to this plane.
  18396. */
  18397. negate() {
  18398. this.constant *= -1;
  18399. this.normal.negate();
  18400. return this;
  18401. }
  18402. /**
  18403. * Returns the signed distance from the given point to this plane.
  18404. *
  18405. * @param {Vector3} point - The point to compute the distance for.
  18406. * @return {number} The signed distance.
  18407. */
  18408. distanceToPoint( point ) {
  18409. return this.normal.dot( point ) + this.constant;
  18410. }
  18411. /**
  18412. * Returns the signed distance from the given sphere to this plane.
  18413. *
  18414. * @param {Sphere} sphere - The sphere to compute the distance for.
  18415. * @return {number} The signed distance.
  18416. */
  18417. distanceToSphere( sphere ) {
  18418. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18419. }
  18420. /**
  18421. * Projects a the given point onto the plane.
  18422. *
  18423. * @param {Vector3} point - The point to project.
  18424. * @param {Vector3} target - The target vector that is used to store the method's result.
  18425. * @return {Vector3} The projected point on the plane.
  18426. */
  18427. projectPoint( point, target ) {
  18428. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18429. }
  18430. /**
  18431. * Returns the intersection point of the passed line and the plane. Returns
  18432. * `null` if the line does not intersect. Returns the line's starting point if
  18433. * the line is coplanar with the plane.
  18434. *
  18435. * @param {Line3} line - The line to compute the intersection for.
  18436. * @param {Vector3} target - The target vector that is used to store the method's result.
  18437. * @return {?Vector3} The intersection point.
  18438. */
  18439. intersectLine( line, target ) {
  18440. const direction = line.delta( _vector1 );
  18441. const denominator = this.normal.dot( direction );
  18442. if ( denominator === 0 ) {
  18443. // line is coplanar, return origin
  18444. if ( this.distanceToPoint( line.start ) === 0 ) {
  18445. return target.copy( line.start );
  18446. }
  18447. // Unsure if this is the correct method to handle this case.
  18448. return null;
  18449. }
  18450. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18451. if ( t < 0 || t > 1 ) {
  18452. return null;
  18453. }
  18454. return target.copy( line.start ).addScaledVector( direction, t );
  18455. }
  18456. /**
  18457. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18458. *
  18459. * @param {Line3} line - The line to test.
  18460. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18461. */
  18462. intersectsLine( line ) {
  18463. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18464. const startSign = this.distanceToPoint( line.start );
  18465. const endSign = this.distanceToPoint( line.end );
  18466. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18467. }
  18468. /**
  18469. * Returns `true` if the given bounding box intersects with the plane.
  18470. *
  18471. * @param {Box3} box - The bounding box to test.
  18472. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18473. */
  18474. intersectsBox( box ) {
  18475. return box.intersectsPlane( this );
  18476. }
  18477. /**
  18478. * Returns `true` if the given bounding sphere intersects with the plane.
  18479. *
  18480. * @param {Sphere} sphere - The bounding sphere to test.
  18481. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18482. */
  18483. intersectsSphere( sphere ) {
  18484. return sphere.intersectsPlane( this );
  18485. }
  18486. /**
  18487. * Returns a coplanar vector to the plane, by calculating the
  18488. * projection of the normal at the origin onto the plane.
  18489. *
  18490. * @param {Vector3} target - The target vector that is used to store the method's result.
  18491. * @return {Vector3} The coplanar point.
  18492. */
  18493. coplanarPoint( target ) {
  18494. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18495. }
  18496. /**
  18497. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18498. *
  18499. * The optional normal matrix can be pre-computed like so:
  18500. * ```js
  18501. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18502. * ```
  18503. *
  18504. * @param {Matrix4} matrix - The transformation matrix.
  18505. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18506. * @return {Plane} A reference to this plane.
  18507. */
  18508. applyMatrix4( matrix, optionalNormalMatrix ) {
  18509. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18510. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18511. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18512. this.constant = - referencePoint.dot( normal );
  18513. return this;
  18514. }
  18515. /**
  18516. * Translates the plane by the distance defined by the given offset vector.
  18517. * Note that this only affects the plane constant and will not affect the normal vector.
  18518. *
  18519. * @param {Vector3} offset - The offset vector.
  18520. * @return {Plane} A reference to this plane.
  18521. */
  18522. translate( offset ) {
  18523. this.constant -= offset.dot( this.normal );
  18524. return this;
  18525. }
  18526. /**
  18527. * Returns `true` if this plane is equal with the given one.
  18528. *
  18529. * @param {Plane} plane - The plane to test for equality.
  18530. * @return {boolean} Whether this plane is equal with the given one.
  18531. */
  18532. equals( plane ) {
  18533. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18534. }
  18535. /**
  18536. * Returns a new plane with copied values from this instance.
  18537. *
  18538. * @return {Plane} A clone of this instance.
  18539. */
  18540. clone() {
  18541. return new this.constructor().copy( this );
  18542. }
  18543. }
  18544. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18545. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18546. const _vector$6 = /*@__PURE__*/ new Vector3();
  18547. /**
  18548. * Frustums are used to determine what is inside the camera's field of view.
  18549. * They help speed up the rendering process - objects which lie outside a camera's
  18550. * frustum can safely be excluded from rendering.
  18551. *
  18552. * This class is mainly intended for use internally by a renderer.
  18553. */
  18554. class Frustum {
  18555. /**
  18556. * Constructs a new frustum.
  18557. *
  18558. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18559. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18560. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18561. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18562. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18563. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18564. */
  18565. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18566. /**
  18567. * This array holds the planes that enclose the frustum.
  18568. *
  18569. * @type {Array<Plane>}
  18570. */
  18571. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18572. }
  18573. /**
  18574. * Sets the frustum planes by copying the given planes.
  18575. *
  18576. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18577. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18578. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18579. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18580. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18581. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18582. * @return {Frustum} A reference to this frustum.
  18583. */
  18584. set( p0, p1, p2, p3, p4, p5 ) {
  18585. const planes = this.planes;
  18586. planes[ 0 ].copy( p0 );
  18587. planes[ 1 ].copy( p1 );
  18588. planes[ 2 ].copy( p2 );
  18589. planes[ 3 ].copy( p3 );
  18590. planes[ 4 ].copy( p4 );
  18591. planes[ 5 ].copy( p5 );
  18592. return this;
  18593. }
  18594. /**
  18595. * Copies the values of the given frustum to this instance.
  18596. *
  18597. * @param {Frustum} frustum - The frustum to copy.
  18598. * @return {Frustum} A reference to this frustum.
  18599. */
  18600. copy( frustum ) {
  18601. const planes = this.planes;
  18602. for ( let i = 0; i < 6; i ++ ) {
  18603. planes[ i ].copy( frustum.planes[ i ] );
  18604. }
  18605. return this;
  18606. }
  18607. /**
  18608. * Sets the frustum planes from the given projection matrix.
  18609. *
  18610. * @param {Matrix4} m - The projection matrix.
  18611. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18612. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18613. * @return {Frustum} A reference to this frustum.
  18614. */
  18615. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18616. const planes = this.planes;
  18617. const me = m.elements;
  18618. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18619. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18620. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18621. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18622. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18623. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18624. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18625. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18626. if ( reversedDepth ) {
  18627. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18628. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18629. } else {
  18630. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18631. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18632. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18633. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18634. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18635. } else {
  18636. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18637. }
  18638. }
  18639. return this;
  18640. }
  18641. /**
  18642. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18643. *
  18644. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18645. *
  18646. * @param {Object3D} object - The 3D object to test.
  18647. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18648. */
  18649. intersectsObject( object ) {
  18650. if ( object.boundingSphere !== undefined ) {
  18651. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18652. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18653. } else {
  18654. const geometry = object.geometry;
  18655. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18656. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18657. }
  18658. return this.intersectsSphere( _sphere$3 );
  18659. }
  18660. /**
  18661. * Returns `true` if the given sprite is intersecting this frustum.
  18662. *
  18663. * @param {Sprite} sprite - The sprite to test.
  18664. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18665. */
  18666. intersectsSprite( sprite ) {
  18667. _sphere$3.center.set( 0, 0, 0 );
  18668. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18669. _sphere$3.radius = 0.7071067811865476 + offset;
  18670. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18671. return this.intersectsSphere( _sphere$3 );
  18672. }
  18673. /**
  18674. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18675. *
  18676. * @param {Sphere} sphere - The bounding sphere to test.
  18677. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  18678. */
  18679. intersectsSphere( sphere ) {
  18680. const planes = this.planes;
  18681. const center = sphere.center;
  18682. const negRadius = - sphere.radius;
  18683. for ( let i = 0; i < 6; i ++ ) {
  18684. const distance = planes[ i ].distanceToPoint( center );
  18685. if ( distance < negRadius ) {
  18686. return false;
  18687. }
  18688. }
  18689. return true;
  18690. }
  18691. /**
  18692. * Returns `true` if the given bounding box is intersecting this frustum.
  18693. *
  18694. * @param {Box3} box - The bounding box to test.
  18695. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  18696. */
  18697. intersectsBox( box ) {
  18698. const planes = this.planes;
  18699. for ( let i = 0; i < 6; i ++ ) {
  18700. const plane = planes[ i ];
  18701. // corner at max distance
  18702. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  18703. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  18704. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  18705. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  18706. return false;
  18707. }
  18708. }
  18709. return true;
  18710. }
  18711. /**
  18712. * Returns `true` if the given point lies within the frustum.
  18713. *
  18714. * @param {Vector3} point - The point to test.
  18715. * @return {boolean} Whether the point lies within this frustum or not.
  18716. */
  18717. containsPoint( point ) {
  18718. const planes = this.planes;
  18719. for ( let i = 0; i < 6; i ++ ) {
  18720. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  18721. return false;
  18722. }
  18723. }
  18724. return true;
  18725. }
  18726. /**
  18727. * Returns a new frustum with copied values from this instance.
  18728. *
  18729. * @return {Frustum} A clone of this instance.
  18730. */
  18731. clone() {
  18732. return new this.constructor().copy( this );
  18733. }
  18734. }
  18735. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  18736. const _frustum$1 = /*@__PURE__*/ new Frustum();
  18737. /**
  18738. * FrustumArray is used to determine if an object is visible in at least one camera
  18739. * from an array of cameras. This is particularly useful for multi-view renderers.
  18740. */
  18741. class FrustumArray {
  18742. /**
  18743. * Constructs a new frustum array.
  18744. *
  18745. */
  18746. constructor() {
  18747. /**
  18748. * The coordinate system to use.
  18749. *
  18750. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  18751. * @default WebGLCoordinateSystem
  18752. */
  18753. this.coordinateSystem = WebGLCoordinateSystem;
  18754. }
  18755. /**
  18756. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  18757. * from the camera array.
  18758. *
  18759. * @param {Object3D} object - The 3D object to test.
  18760. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18761. * @return {boolean} Whether the 3D object is visible in any camera.
  18762. */
  18763. intersectsObject( object, cameraArray ) {
  18764. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  18765. return false;
  18766. }
  18767. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18768. const camera = cameraArray.cameras[ i ];
  18769. _projScreenMatrix$2.multiplyMatrices(
  18770. camera.projectionMatrix,
  18771. camera.matrixWorldInverse
  18772. );
  18773. _frustum$1.setFromProjectionMatrix(
  18774. _projScreenMatrix$2,
  18775. camera.coordinateSystem,
  18776. camera.reversedDepth
  18777. );
  18778. if ( _frustum$1.intersectsObject( object ) ) {
  18779. return true; // Object is visible in at least one camera
  18780. }
  18781. }
  18782. return false; // Not visible in any camera
  18783. }
  18784. /**
  18785. * Returns `true` if the given sprite is intersecting any frustum
  18786. * from the camera array.
  18787. *
  18788. * @param {Sprite} sprite - The sprite to test.
  18789. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18790. * @return {boolean} Whether the sprite is visible in any camera.
  18791. */
  18792. intersectsSprite( sprite, cameraArray ) {
  18793. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18794. return false;
  18795. }
  18796. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18797. const camera = cameraArray.cameras[ i ];
  18798. _projScreenMatrix$2.multiplyMatrices(
  18799. camera.projectionMatrix,
  18800. camera.matrixWorldInverse
  18801. );
  18802. _frustum$1.setFromProjectionMatrix(
  18803. _projScreenMatrix$2,
  18804. camera.coordinateSystem,
  18805. camera.reversedDepth
  18806. );
  18807. if ( _frustum$1.intersectsSprite( sprite ) ) {
  18808. return true; // Sprite is visible in at least one camera
  18809. }
  18810. }
  18811. return false; // Not visible in any camera
  18812. }
  18813. /**
  18814. * Returns `true` if the given bounding sphere is intersecting any frustum
  18815. * from the camera array.
  18816. *
  18817. * @param {Sphere} sphere - The bounding sphere to test.
  18818. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18819. * @return {boolean} Whether the sphere is visible in any camera.
  18820. */
  18821. intersectsSphere( sphere, cameraArray ) {
  18822. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18823. return false;
  18824. }
  18825. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18826. const camera = cameraArray.cameras[ i ];
  18827. _projScreenMatrix$2.multiplyMatrices(
  18828. camera.projectionMatrix,
  18829. camera.matrixWorldInverse
  18830. );
  18831. _frustum$1.setFromProjectionMatrix(
  18832. _projScreenMatrix$2,
  18833. camera.coordinateSystem,
  18834. camera.reversedDepth
  18835. );
  18836. if ( _frustum$1.intersectsSphere( sphere ) ) {
  18837. return true; // Sphere is visible in at least one camera
  18838. }
  18839. }
  18840. return false; // Not visible in any camera
  18841. }
  18842. /**
  18843. * Returns `true` if the given bounding box is intersecting any frustum
  18844. * from the camera array.
  18845. *
  18846. * @param {Box3} box - The bounding box to test.
  18847. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18848. * @return {boolean} Whether the box is visible in any camera.
  18849. */
  18850. intersectsBox( box, cameraArray ) {
  18851. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18852. return false;
  18853. }
  18854. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18855. const camera = cameraArray.cameras[ i ];
  18856. _projScreenMatrix$2.multiplyMatrices(
  18857. camera.projectionMatrix,
  18858. camera.matrixWorldInverse
  18859. );
  18860. _frustum$1.setFromProjectionMatrix(
  18861. _projScreenMatrix$2,
  18862. camera.coordinateSystem,
  18863. camera.reversedDepth
  18864. );
  18865. if ( _frustum$1.intersectsBox( box ) ) {
  18866. return true; // Box is visible in at least one camera
  18867. }
  18868. }
  18869. return false; // Not visible in any camera
  18870. }
  18871. /**
  18872. * Returns `true` if the given point lies within any frustum
  18873. * from the camera array.
  18874. *
  18875. * @param {Vector3} point - The point to test.
  18876. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  18877. * @return {boolean} Whether the point is visible in any camera.
  18878. */
  18879. containsPoint( point, cameraArray ) {
  18880. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  18881. return false;
  18882. }
  18883. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  18884. const camera = cameraArray.cameras[ i ];
  18885. _projScreenMatrix$2.multiplyMatrices(
  18886. camera.projectionMatrix,
  18887. camera.matrixWorldInverse
  18888. );
  18889. _frustum$1.setFromProjectionMatrix(
  18890. _projScreenMatrix$2,
  18891. camera.coordinateSystem,
  18892. camera.reversedDepth
  18893. );
  18894. if ( _frustum$1.containsPoint( point ) ) {
  18895. return true; // Point is visible in at least one camera
  18896. }
  18897. }
  18898. return false; // Not visible in any camera
  18899. }
  18900. /**
  18901. * Returns a new frustum array with copied values from this instance.
  18902. *
  18903. * @return {FrustumArray} A clone of this instance.
  18904. */
  18905. clone() {
  18906. return new FrustumArray();
  18907. }
  18908. }
  18909. function ascIdSort( a, b ) {
  18910. return a - b;
  18911. }
  18912. function sortOpaque( a, b ) {
  18913. return a.z - b.z;
  18914. }
  18915. function sortTransparent( a, b ) {
  18916. return b.z - a.z;
  18917. }
  18918. class MultiDrawRenderList {
  18919. constructor() {
  18920. this.index = 0;
  18921. this.pool = [];
  18922. this.list = [];
  18923. }
  18924. push( start, count, z, index ) {
  18925. const pool = this.pool;
  18926. const list = this.list;
  18927. if ( this.index >= pool.length ) {
  18928. pool.push( {
  18929. start: -1,
  18930. count: -1,
  18931. z: -1,
  18932. index: -1,
  18933. } );
  18934. }
  18935. const item = pool[ this.index ];
  18936. list.push( item );
  18937. this.index ++;
  18938. item.start = start;
  18939. item.count = count;
  18940. item.z = z;
  18941. item.index = index;
  18942. }
  18943. reset() {
  18944. this.list.length = 0;
  18945. this.index = 0;
  18946. }
  18947. }
  18948. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  18949. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  18950. const _frustum = /*@__PURE__*/ new Frustum();
  18951. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  18952. const _box$1 = /*@__PURE__*/ new Box3();
  18953. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18954. const _vector$5 = /*@__PURE__*/ new Vector3();
  18955. const _forward$1 = /*@__PURE__*/ new Vector3();
  18956. const _temp = /*@__PURE__*/ new Vector3();
  18957. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  18958. const _mesh = /*@__PURE__*/ new Mesh();
  18959. const _batchIntersects = [];
  18960. // copies data from attribute "src" into "target" starting at "targetOffset"
  18961. function copyAttributeData( src, target, targetOffset = 0 ) {
  18962. const itemSize = target.itemSize;
  18963. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  18964. // use the component getters and setters if the array data cannot
  18965. // be copied directly
  18966. const vertexCount = src.count;
  18967. for ( let i = 0; i < vertexCount; i ++ ) {
  18968. for ( let c = 0; c < itemSize; c ++ ) {
  18969. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  18970. }
  18971. }
  18972. } else {
  18973. // faster copy approach using typed array set function
  18974. target.array.set( src.array, targetOffset * itemSize );
  18975. }
  18976. target.needsUpdate = true;
  18977. }
  18978. // safely copies array contents to a potentially smaller array
  18979. function copyArrayContents( src, target ) {
  18980. if ( src.constructor !== target.constructor ) {
  18981. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  18982. const len = Math.min( src.length, target.length );
  18983. for ( let i = 0; i < len; i ++ ) {
  18984. target[ i ] = src[ i ];
  18985. }
  18986. } else {
  18987. // if the arrays use the same data layout we can use a fast block copy
  18988. const len = Math.min( src.length, target.length );
  18989. target.set( new src.constructor( src.buffer, 0, len ) );
  18990. }
  18991. }
  18992. /**
  18993. * A special version of a mesh with multi draw batch rendering support. Use
  18994. * this class if you have to render a large number of objects with the same
  18995. * material but with different geometries or world transformations. The usage of
  18996. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  18997. * rendering performance in your application.
  18998. *
  18999. * ```js
  19000. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19001. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19002. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19003. *
  19004. * // initialize and add geometries into the batched mesh
  19005. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19006. * const boxGeometryId = batchedMesh.addGeometry( box );
  19007. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19008. *
  19009. * // create instances of those geometries
  19010. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19011. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19012. *
  19013. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19014. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19015. *
  19016. * // position the geometries
  19017. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19018. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19019. *
  19020. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19021. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19022. *
  19023. * scene.add( batchedMesh );
  19024. * ```
  19025. *
  19026. * @augments Mesh
  19027. */
  19028. class BatchedMesh extends Mesh {
  19029. /**
  19030. * Constructs a new batched mesh.
  19031. *
  19032. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19033. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19034. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19035. * @param {Material|Array<Material>} [material] - The mesh material.
  19036. */
  19037. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19038. super( new BufferGeometry(), material );
  19039. /**
  19040. * This flag can be used for type testing.
  19041. *
  19042. * @type {boolean}
  19043. * @readonly
  19044. * @default true
  19045. */
  19046. this.isBatchedMesh = true;
  19047. /**
  19048. * When set ot `true`, the individual objects of a batch are frustum culled.
  19049. *
  19050. * @type {boolean}
  19051. * @default true
  19052. */
  19053. this.perObjectFrustumCulled = true;
  19054. /**
  19055. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19056. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19057. * rendered front to back.
  19058. *
  19059. * @type {boolean}
  19060. * @default true
  19061. */
  19062. this.sortObjects = true;
  19063. /**
  19064. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19065. *
  19066. * @type {?Box3}
  19067. * @default null
  19068. */
  19069. this.boundingBox = null;
  19070. /**
  19071. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19072. *
  19073. * @type {?Sphere}
  19074. * @default null
  19075. */
  19076. this.boundingSphere = null;
  19077. /**
  19078. * Takes a sort a function that is run before render. The function takes a list of instances to
  19079. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19080. * sort with.
  19081. *
  19082. * @type {?Function}
  19083. * @default null
  19084. */
  19085. this.customSort = null;
  19086. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19087. this._instanceInfo = [];
  19088. this._geometryInfo = [];
  19089. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19090. this._availableInstanceIds = [];
  19091. this._availableGeometryIds = [];
  19092. // used to track where the next point is that geometry should be inserted
  19093. this._nextIndexStart = 0;
  19094. this._nextVertexStart = 0;
  19095. this._geometryCount = 0;
  19096. // flags
  19097. this._visibilityChanged = true;
  19098. this._geometryInitialized = false;
  19099. // cached user options
  19100. this._maxInstanceCount = maxInstanceCount;
  19101. this._maxVertexCount = maxVertexCount;
  19102. this._maxIndexCount = maxIndexCount;
  19103. // buffers for multi draw
  19104. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19105. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19106. this._multiDrawCount = 0;
  19107. this._multiDrawInstances = null;
  19108. // Local matrix per geometry by using data texture
  19109. this._matricesTexture = null;
  19110. this._indirectTexture = null;
  19111. this._colorsTexture = null;
  19112. this._initMatricesTexture();
  19113. this._initIndirectTexture();
  19114. }
  19115. /**
  19116. * The maximum number of individual instances that can be stored in the batch.
  19117. *
  19118. * @type {number}
  19119. * @readonly
  19120. */
  19121. get maxInstanceCount() {
  19122. return this._maxInstanceCount;
  19123. }
  19124. /**
  19125. * The instance count.
  19126. *
  19127. * @type {number}
  19128. * @readonly
  19129. */
  19130. get instanceCount() {
  19131. return this._instanceInfo.length - this._availableInstanceIds.length;
  19132. }
  19133. /**
  19134. * The number of unused vertices.
  19135. *
  19136. * @type {number}
  19137. * @readonly
  19138. */
  19139. get unusedVertexCount() {
  19140. return this._maxVertexCount - this._nextVertexStart;
  19141. }
  19142. /**
  19143. * The number of unused indices.
  19144. *
  19145. * @type {number}
  19146. * @readonly
  19147. */
  19148. get unusedIndexCount() {
  19149. return this._maxIndexCount - this._nextIndexStart;
  19150. }
  19151. _initMatricesTexture() {
  19152. // layout (1 matrix = 4 pixels)
  19153. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19154. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19155. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19156. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19157. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19158. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19159. size = Math.ceil( size / 4 ) * 4;
  19160. size = Math.max( size, 4 );
  19161. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19162. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19163. this._matricesTexture = matricesTexture;
  19164. }
  19165. _initIndirectTexture() {
  19166. let size = Math.sqrt( this._maxInstanceCount );
  19167. size = Math.ceil( size );
  19168. const indirectArray = new Uint32Array( size * size );
  19169. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19170. this._indirectTexture = indirectTexture;
  19171. }
  19172. _initColorsTexture() {
  19173. let size = Math.sqrt( this._maxInstanceCount );
  19174. size = Math.ceil( size );
  19175. // 4 floats per RGBA pixel initialized to white
  19176. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19177. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19178. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19179. this._colorsTexture = colorsTexture;
  19180. }
  19181. _initializeGeometry( reference ) {
  19182. const geometry = this.geometry;
  19183. const maxVertexCount = this._maxVertexCount;
  19184. const maxIndexCount = this._maxIndexCount;
  19185. if ( this._geometryInitialized === false ) {
  19186. for ( const attributeName in reference.attributes ) {
  19187. const srcAttribute = reference.getAttribute( attributeName );
  19188. const { array, itemSize, normalized } = srcAttribute;
  19189. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19190. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19191. geometry.setAttribute( attributeName, dstAttribute );
  19192. }
  19193. if ( reference.getIndex() !== null ) {
  19194. // Reserve last u16 index for primitive restart.
  19195. const indexArray = maxVertexCount > 65535
  19196. ? new Uint32Array( maxIndexCount )
  19197. : new Uint16Array( maxIndexCount );
  19198. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19199. }
  19200. this._geometryInitialized = true;
  19201. }
  19202. }
  19203. // Make sure the geometry is compatible with the existing combined geometry attributes
  19204. _validateGeometry( geometry ) {
  19205. // check to ensure the geometries are using consistent attributes and indices
  19206. const batchGeometry = this.geometry;
  19207. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19208. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19209. }
  19210. for ( const attributeName in batchGeometry.attributes ) {
  19211. if ( ! geometry.hasAttribute( attributeName ) ) {
  19212. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19213. }
  19214. const srcAttribute = geometry.getAttribute( attributeName );
  19215. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19216. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19217. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19218. }
  19219. }
  19220. }
  19221. /**
  19222. * Validates the instance defined by the given ID.
  19223. *
  19224. * @param {number} instanceId - The instance to validate.
  19225. */
  19226. validateInstanceId( instanceId ) {
  19227. const instanceInfo = this._instanceInfo;
  19228. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19229. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19230. }
  19231. }
  19232. /**
  19233. * Validates the geometry defined by the given ID.
  19234. *
  19235. * @param {number} geometryId - The geometry to validate.
  19236. */
  19237. validateGeometryId( geometryId ) {
  19238. const geometryInfoList = this._geometryInfo;
  19239. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19240. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19241. }
  19242. }
  19243. /**
  19244. * Takes a sort a function that is run before render. The function takes a list of instances to
  19245. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19246. *
  19247. * @param {Function} func - The custom sort function.
  19248. * @return {BatchedMesh} A reference to this batched mesh.
  19249. */
  19250. setCustomSort( func ) {
  19251. this.customSort = func;
  19252. return this;
  19253. }
  19254. /**
  19255. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19256. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19257. * otherwise they are `null`.
  19258. */
  19259. computeBoundingBox() {
  19260. if ( this.boundingBox === null ) {
  19261. this.boundingBox = new Box3();
  19262. }
  19263. const boundingBox = this.boundingBox;
  19264. const instanceInfo = this._instanceInfo;
  19265. boundingBox.makeEmpty();
  19266. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19267. if ( instanceInfo[ i ].active === false ) continue;
  19268. const geometryId = instanceInfo[ i ].geometryIndex;
  19269. this.getMatrixAt( i, _matrix$1 );
  19270. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19271. boundingBox.union( _box$1 );
  19272. }
  19273. }
  19274. /**
  19275. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19276. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19277. * otherwise they are `null`.
  19278. */
  19279. computeBoundingSphere() {
  19280. if ( this.boundingSphere === null ) {
  19281. this.boundingSphere = new Sphere();
  19282. }
  19283. const boundingSphere = this.boundingSphere;
  19284. const instanceInfo = this._instanceInfo;
  19285. boundingSphere.makeEmpty();
  19286. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19287. if ( instanceInfo[ i ].active === false ) continue;
  19288. const geometryId = instanceInfo[ i ].geometryIndex;
  19289. this.getMatrixAt( i, _matrix$1 );
  19290. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19291. boundingSphere.union( _sphere$2 );
  19292. }
  19293. }
  19294. /**
  19295. * Adds a new instance to the batch using the geometry of the given ID and returns
  19296. * a new id referring to the new instance to be used by other functions.
  19297. *
  19298. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19299. * @return {number} The instance ID.
  19300. */
  19301. addInstance( geometryId ) {
  19302. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19303. // ensure we're not over geometry
  19304. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19305. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19306. }
  19307. const instanceInfo = {
  19308. visible: true,
  19309. active: true,
  19310. geometryIndex: geometryId,
  19311. };
  19312. let drawId = null;
  19313. // Prioritize using previously freed instance ids
  19314. if ( this._availableInstanceIds.length > 0 ) {
  19315. this._availableInstanceIds.sort( ascIdSort );
  19316. drawId = this._availableInstanceIds.shift();
  19317. this._instanceInfo[ drawId ] = instanceInfo;
  19318. } else {
  19319. drawId = this._instanceInfo.length;
  19320. this._instanceInfo.push( instanceInfo );
  19321. }
  19322. const matricesTexture = this._matricesTexture;
  19323. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19324. matricesTexture.needsUpdate = true;
  19325. const colorsTexture = this._colorsTexture;
  19326. if ( colorsTexture ) {
  19327. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19328. colorsTexture.needsUpdate = true;
  19329. }
  19330. this._visibilityChanged = true;
  19331. return drawId;
  19332. }
  19333. /**
  19334. * Adds the given geometry to the batch and returns the associated
  19335. * geometry id referring to it to be used in other functions.
  19336. *
  19337. * @param {BufferGeometry} geometry - The geometry to add.
  19338. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19339. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19340. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19341. * Defaults to the length of the given geometry vertex buffer.
  19342. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19343. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19344. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19345. * the length of the given geometry index buffer.
  19346. * @return {number} The geometry ID.
  19347. */
  19348. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19349. this._initializeGeometry( geometry );
  19350. this._validateGeometry( geometry );
  19351. const geometryInfo = {
  19352. // geometry information
  19353. vertexStart: -1,
  19354. vertexCount: -1,
  19355. reservedVertexCount: -1,
  19356. indexStart: -1,
  19357. indexCount: -1,
  19358. reservedIndexCount: -1,
  19359. // draw range information
  19360. start: -1,
  19361. count: -1,
  19362. // state
  19363. boundingBox: null,
  19364. boundingSphere: null,
  19365. active: true,
  19366. };
  19367. const geometryInfoList = this._geometryInfo;
  19368. geometryInfo.vertexStart = this._nextVertexStart;
  19369. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19370. const index = geometry.getIndex();
  19371. const hasIndex = index !== null;
  19372. if ( hasIndex ) {
  19373. geometryInfo.indexStart = this._nextIndexStart;
  19374. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19375. }
  19376. if (
  19377. geometryInfo.indexStart !== -1 &&
  19378. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19379. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19380. ) {
  19381. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19382. }
  19383. // update id
  19384. let geometryId;
  19385. if ( this._availableGeometryIds.length > 0 ) {
  19386. this._availableGeometryIds.sort( ascIdSort );
  19387. geometryId = this._availableGeometryIds.shift();
  19388. geometryInfoList[ geometryId ] = geometryInfo;
  19389. } else {
  19390. geometryId = this._geometryCount;
  19391. this._geometryCount ++;
  19392. geometryInfoList.push( geometryInfo );
  19393. }
  19394. // update the geometry
  19395. this.setGeometryAt( geometryId, geometry );
  19396. // increment the next geometry position
  19397. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19398. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19399. return geometryId;
  19400. }
  19401. /**
  19402. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19403. * is not enough space reserved for geometry. Calling this will change all instances that are
  19404. * rendering that geometry.
  19405. *
  19406. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19407. * @param {BufferGeometry} geometry - The new geometry.
  19408. * @return {number} The geometry ID.
  19409. */
  19410. setGeometryAt( geometryId, geometry ) {
  19411. if ( geometryId >= this._geometryCount ) {
  19412. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19413. }
  19414. this._validateGeometry( geometry );
  19415. const batchGeometry = this.geometry;
  19416. const hasIndex = batchGeometry.getIndex() !== null;
  19417. const dstIndex = batchGeometry.getIndex();
  19418. const srcIndex = geometry.getIndex();
  19419. const geometryInfo = this._geometryInfo[ geometryId ];
  19420. if (
  19421. hasIndex &&
  19422. srcIndex.count > geometryInfo.reservedIndexCount ||
  19423. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19424. ) {
  19425. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19426. }
  19427. // copy geometry buffer data over
  19428. const vertexStart = geometryInfo.vertexStart;
  19429. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19430. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19431. for ( const attributeName in batchGeometry.attributes ) {
  19432. // copy attribute data
  19433. const srcAttribute = geometry.getAttribute( attributeName );
  19434. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19435. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19436. // fill the rest in with zeroes
  19437. const itemSize = srcAttribute.itemSize;
  19438. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19439. const index = vertexStart + i;
  19440. for ( let c = 0; c < itemSize; c ++ ) {
  19441. dstAttribute.setComponent( index, c, 0 );
  19442. }
  19443. }
  19444. dstAttribute.needsUpdate = true;
  19445. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19446. }
  19447. // copy index
  19448. if ( hasIndex ) {
  19449. const indexStart = geometryInfo.indexStart;
  19450. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19451. geometryInfo.indexCount = geometry.getIndex().count;
  19452. // copy index data over
  19453. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19454. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19455. }
  19456. // fill the rest in with zeroes
  19457. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19458. dstIndex.setX( indexStart + i, vertexStart );
  19459. }
  19460. dstIndex.needsUpdate = true;
  19461. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19462. }
  19463. // update the draw range
  19464. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19465. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19466. // store the bounding boxes
  19467. geometryInfo.boundingBox = null;
  19468. if ( geometry.boundingBox !== null ) {
  19469. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19470. }
  19471. geometryInfo.boundingSphere = null;
  19472. if ( geometry.boundingSphere !== null ) {
  19473. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19474. }
  19475. this._visibilityChanged = true;
  19476. return geometryId;
  19477. }
  19478. /**
  19479. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19480. * this geometry will also be removed as a side effect.
  19481. *
  19482. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19483. * @return {BatchedMesh} A reference to this batched mesh.
  19484. */
  19485. deleteGeometry( geometryId ) {
  19486. const geometryInfoList = this._geometryInfo;
  19487. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19488. return this;
  19489. }
  19490. // delete any instances associated with this geometry
  19491. const instanceInfo = this._instanceInfo;
  19492. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19493. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19494. this.deleteInstance( i );
  19495. }
  19496. }
  19497. geometryInfoList[ geometryId ].active = false;
  19498. this._availableGeometryIds.push( geometryId );
  19499. this._visibilityChanged = true;
  19500. return this;
  19501. }
  19502. /**
  19503. * Deletes an existing instance from the batch using the given ID.
  19504. *
  19505. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19506. * @return {BatchedMesh} A reference to this batched mesh.
  19507. */
  19508. deleteInstance( instanceId ) {
  19509. this.validateInstanceId( instanceId );
  19510. this._instanceInfo[ instanceId ].active = false;
  19511. this._availableInstanceIds.push( instanceId );
  19512. this._visibilityChanged = true;
  19513. return this;
  19514. }
  19515. /**
  19516. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19517. * previously deleted geometry, freeing up space to add new geometry.
  19518. *
  19519. * @return {BatchedMesh} A reference to this batched mesh.
  19520. */
  19521. optimize() {
  19522. // track the next indices to copy data to
  19523. let nextVertexStart = 0;
  19524. let nextIndexStart = 0;
  19525. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19526. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19527. const geometryInfoList = this._geometryInfo;
  19528. const indices = geometryInfoList
  19529. .map( ( e, i ) => i )
  19530. .sort( ( a, b ) => {
  19531. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19532. } );
  19533. const geometry = this.geometry;
  19534. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19535. // if a geometry range is inactive then don't copy anything
  19536. const index = indices[ i ];
  19537. const geometryInfo = geometryInfoList[ index ];
  19538. if ( geometryInfo.active === false ) {
  19539. continue;
  19540. }
  19541. // if a geometry contains an index buffer then shift it, as well
  19542. if ( geometry.index !== null ) {
  19543. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19544. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19545. const index = geometry.index;
  19546. const array = index.array;
  19547. // shift the index pointers based on how the vertex data will shift
  19548. // adjusting the index must happen first so the original vertex start value is available
  19549. const elementDelta = nextVertexStart - vertexStart;
  19550. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19551. array[ j ] = array[ j ] + elementDelta;
  19552. }
  19553. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19554. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19555. index.needsUpdate = true;
  19556. geometryInfo.indexStart = nextIndexStart;
  19557. }
  19558. nextIndexStart += geometryInfo.reservedIndexCount;
  19559. }
  19560. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19561. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19562. const { vertexStart, reservedVertexCount } = geometryInfo;
  19563. const attributes = geometry.attributes;
  19564. for ( const key in attributes ) {
  19565. const attribute = attributes[ key ];
  19566. const { array, itemSize } = attribute;
  19567. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19568. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19569. attribute.needsUpdate = true;
  19570. }
  19571. geometryInfo.vertexStart = nextVertexStart;
  19572. }
  19573. nextVertexStart += geometryInfo.reservedVertexCount;
  19574. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19575. }
  19576. this._nextIndexStart = nextIndexStart;
  19577. this._nextVertexStart = nextVertexStart;
  19578. this._visibilityChanged = true;
  19579. return this;
  19580. }
  19581. /**
  19582. * Returns the bounding box for the given geometry.
  19583. *
  19584. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19585. * @param {Box3} target - The target object that is used to store the method's result.
  19586. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19587. */
  19588. getBoundingBoxAt( geometryId, target ) {
  19589. if ( geometryId >= this._geometryCount ) {
  19590. return null;
  19591. }
  19592. // compute bounding box
  19593. const geometry = this.geometry;
  19594. const geometryInfo = this._geometryInfo[ geometryId ];
  19595. if ( geometryInfo.boundingBox === null ) {
  19596. const box = new Box3();
  19597. const index = geometry.index;
  19598. const position = geometry.attributes.position;
  19599. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19600. let iv = i;
  19601. if ( index ) {
  19602. iv = index.getX( iv );
  19603. }
  19604. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19605. }
  19606. geometryInfo.boundingBox = box;
  19607. }
  19608. target.copy( geometryInfo.boundingBox );
  19609. return target;
  19610. }
  19611. /**
  19612. * Returns the bounding sphere for the given geometry.
  19613. *
  19614. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19615. * @param {Sphere} target - The target object that is used to store the method's result.
  19616. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19617. */
  19618. getBoundingSphereAt( geometryId, target ) {
  19619. if ( geometryId >= this._geometryCount ) {
  19620. return null;
  19621. }
  19622. // compute bounding sphere
  19623. const geometry = this.geometry;
  19624. const geometryInfo = this._geometryInfo[ geometryId ];
  19625. if ( geometryInfo.boundingSphere === null ) {
  19626. const sphere = new Sphere();
  19627. this.getBoundingBoxAt( geometryId, _box$1 );
  19628. _box$1.getCenter( sphere.center );
  19629. const index = geometry.index;
  19630. const position = geometry.attributes.position;
  19631. let maxRadiusSq = 0;
  19632. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19633. let iv = i;
  19634. if ( index ) {
  19635. iv = index.getX( iv );
  19636. }
  19637. _vector$5.fromBufferAttribute( position, iv );
  19638. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19639. }
  19640. sphere.radius = Math.sqrt( maxRadiusSq );
  19641. geometryInfo.boundingSphere = sphere;
  19642. }
  19643. target.copy( geometryInfo.boundingSphere );
  19644. return target;
  19645. }
  19646. /**
  19647. * Sets the given local transformation matrix to the defined instance.
  19648. * Negatively scaled matrices are not supported.
  19649. *
  19650. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19651. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19652. * @return {BatchedMesh} A reference to this batched mesh.
  19653. */
  19654. setMatrixAt( instanceId, matrix ) {
  19655. this.validateInstanceId( instanceId );
  19656. const matricesTexture = this._matricesTexture;
  19657. const matricesArray = this._matricesTexture.image.data;
  19658. matrix.toArray( matricesArray, instanceId * 16 );
  19659. matricesTexture.needsUpdate = true;
  19660. return this;
  19661. }
  19662. /**
  19663. * Returns the local transformation matrix of the defined instance.
  19664. *
  19665. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19666. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19667. * @return {Matrix4} The instance's local transformation matrix.
  19668. */
  19669. getMatrixAt( instanceId, matrix ) {
  19670. this.validateInstanceId( instanceId );
  19671. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19672. }
  19673. /**
  19674. * Sets the given color to the defined instance.
  19675. *
  19676. * @param {number} instanceId - The ID of an instance to set the color of.
  19677. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19678. * @return {BatchedMesh} A reference to this batched mesh.
  19679. */
  19680. setColorAt( instanceId, color ) {
  19681. this.validateInstanceId( instanceId );
  19682. if ( this._colorsTexture === null ) {
  19683. this._initColorsTexture();
  19684. }
  19685. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19686. this._colorsTexture.needsUpdate = true;
  19687. return this;
  19688. }
  19689. /**
  19690. * Returns the color of the defined instance.
  19691. *
  19692. * @param {number} instanceId - The ID of an instance to get the color of.
  19693. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19694. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19695. */
  19696. getColorAt( instanceId, color ) {
  19697. this.validateInstanceId( instanceId );
  19698. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  19699. }
  19700. /**
  19701. * Sets the visibility of the instance.
  19702. *
  19703. * @param {number} instanceId - The id of the instance to set the visibility of.
  19704. * @param {boolean} visible - Whether the instance is visible or not.
  19705. * @return {BatchedMesh} A reference to this batched mesh.
  19706. */
  19707. setVisibleAt( instanceId, visible ) {
  19708. this.validateInstanceId( instanceId );
  19709. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  19710. return this;
  19711. }
  19712. this._instanceInfo[ instanceId ].visible = visible;
  19713. this._visibilityChanged = true;
  19714. return this;
  19715. }
  19716. /**
  19717. * Returns the visibility state of the defined instance.
  19718. *
  19719. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  19720. * @return {boolean} Whether the instance is visible or not.
  19721. */
  19722. getVisibleAt( instanceId ) {
  19723. this.validateInstanceId( instanceId );
  19724. return this._instanceInfo[ instanceId ].visible;
  19725. }
  19726. /**
  19727. * Sets the geometry ID of the instance at the given index.
  19728. *
  19729. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  19730. * @param {number} geometryId - The geometry ID to be use by the instance.
  19731. * @return {BatchedMesh} A reference to this batched mesh.
  19732. */
  19733. setGeometryIdAt( instanceId, geometryId ) {
  19734. this.validateInstanceId( instanceId );
  19735. this.validateGeometryId( geometryId );
  19736. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  19737. return this;
  19738. }
  19739. /**
  19740. * Returns the geometry ID of the defined instance.
  19741. *
  19742. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  19743. * @return {number} The instance's geometry ID.
  19744. */
  19745. getGeometryIdAt( instanceId ) {
  19746. this.validateInstanceId( instanceId );
  19747. return this._instanceInfo[ instanceId ].geometryIndex;
  19748. }
  19749. /**
  19750. * Get the range representing the subset of triangles related to the attached geometry,
  19751. * indicating the starting offset and count, or `null` if invalid.
  19752. *
  19753. * @param {number} geometryId - The id of the geometry to get the range of.
  19754. * @param {Object} [target] - The target object that is used to store the method's result.
  19755. * @return {{
  19756. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  19757. * indexStart:number,indexCount:number,reservedIndexCount:number,
  19758. * start:number,count:number
  19759. * }} The result object with range data.
  19760. */
  19761. getGeometryRangeAt( geometryId, target = {} ) {
  19762. this.validateGeometryId( geometryId );
  19763. const geometryInfo = this._geometryInfo[ geometryId ];
  19764. target.vertexStart = geometryInfo.vertexStart;
  19765. target.vertexCount = geometryInfo.vertexCount;
  19766. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  19767. target.indexStart = geometryInfo.indexStart;
  19768. target.indexCount = geometryInfo.indexCount;
  19769. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  19770. target.start = geometryInfo.start;
  19771. target.count = geometryInfo.count;
  19772. return target;
  19773. }
  19774. /**
  19775. * Resizes the necessary buffers to support the provided number of instances.
  19776. * If the provided arguments shrink the number of instances but there are not enough
  19777. * unused Ids at the end of the list then an error is thrown.
  19778. *
  19779. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  19780. */
  19781. setInstanceCount( maxInstanceCount ) {
  19782. // shrink the available instances as much as possible
  19783. const availableInstanceIds = this._availableInstanceIds;
  19784. const instanceInfo = this._instanceInfo;
  19785. availableInstanceIds.sort( ascIdSort );
  19786. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  19787. instanceInfo.pop();
  19788. availableInstanceIds.pop();
  19789. }
  19790. // throw an error if it can't be shrunk to the desired size
  19791. if ( maxInstanceCount < instanceInfo.length ) {
  19792. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  19793. }
  19794. // copy the multi draw counts
  19795. const multiDrawCounts = new Int32Array( maxInstanceCount );
  19796. const multiDrawStarts = new Int32Array( maxInstanceCount );
  19797. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  19798. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  19799. this._multiDrawCounts = multiDrawCounts;
  19800. this._multiDrawStarts = multiDrawStarts;
  19801. this._maxInstanceCount = maxInstanceCount;
  19802. // update texture data for instance sampling
  19803. const indirectTexture = this._indirectTexture;
  19804. const matricesTexture = this._matricesTexture;
  19805. const colorsTexture = this._colorsTexture;
  19806. indirectTexture.dispose();
  19807. this._initIndirectTexture();
  19808. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  19809. matricesTexture.dispose();
  19810. this._initMatricesTexture();
  19811. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  19812. if ( colorsTexture ) {
  19813. colorsTexture.dispose();
  19814. this._initColorsTexture();
  19815. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  19816. }
  19817. }
  19818. /**
  19819. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  19820. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  19821. * end of the geometry attributes then an error is thrown.
  19822. *
  19823. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  19824. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  19825. */
  19826. setGeometrySize( maxVertexCount, maxIndexCount ) {
  19827. // Check if we can shrink to the requested vertex attribute size
  19828. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  19829. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  19830. if ( requiredVertexLength > maxVertexCount ) {
  19831. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19832. }
  19833. // Check if we can shrink to the requested index attribute size
  19834. if ( this.geometry.index ) {
  19835. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  19836. if ( requiredIndexLength > maxIndexCount ) {
  19837. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  19838. }
  19839. }
  19840. //
  19841. // dispose of the previous geometry
  19842. const oldGeometry = this.geometry;
  19843. oldGeometry.dispose();
  19844. // recreate the geometry needed based on the previous variant
  19845. this._maxVertexCount = maxVertexCount;
  19846. this._maxIndexCount = maxIndexCount;
  19847. if ( this._geometryInitialized ) {
  19848. this._geometryInitialized = false;
  19849. this.geometry = new BufferGeometry();
  19850. this._initializeGeometry( oldGeometry );
  19851. }
  19852. // copy data from the previous geometry
  19853. const geometry = this.geometry;
  19854. if ( oldGeometry.index ) {
  19855. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  19856. }
  19857. for ( const key in oldGeometry.attributes ) {
  19858. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  19859. }
  19860. }
  19861. raycast( raycaster, intersects ) {
  19862. const instanceInfo = this._instanceInfo;
  19863. const geometryInfoList = this._geometryInfo;
  19864. const matrixWorld = this.matrixWorld;
  19865. const batchGeometry = this.geometry;
  19866. // iterate over each geometry
  19867. _mesh.material = this.material;
  19868. _mesh.geometry.index = batchGeometry.index;
  19869. _mesh.geometry.attributes = batchGeometry.attributes;
  19870. if ( _mesh.geometry.boundingBox === null ) {
  19871. _mesh.geometry.boundingBox = new Box3();
  19872. }
  19873. if ( _mesh.geometry.boundingSphere === null ) {
  19874. _mesh.geometry.boundingSphere = new Sphere();
  19875. }
  19876. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19877. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  19878. continue;
  19879. }
  19880. const geometryId = instanceInfo[ i ].geometryIndex;
  19881. const geometryInfo = geometryInfoList[ geometryId ];
  19882. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  19883. // get the intersects
  19884. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19885. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  19886. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  19887. _mesh.raycast( raycaster, _batchIntersects );
  19888. // add batch id to the intersects
  19889. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19890. const intersect = _batchIntersects[ j ];
  19891. intersect.object = this;
  19892. intersect.batchId = i;
  19893. intersects.push( intersect );
  19894. }
  19895. _batchIntersects.length = 0;
  19896. }
  19897. _mesh.material = null;
  19898. _mesh.geometry.index = null;
  19899. _mesh.geometry.attributes = {};
  19900. _mesh.geometry.setDrawRange( 0, Infinity );
  19901. }
  19902. copy( source ) {
  19903. super.copy( source );
  19904. this.geometry = source.geometry.clone();
  19905. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19906. this.sortObjects = source.sortObjects;
  19907. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19908. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19909. this._geometryInfo = source._geometryInfo.map( info => ( {
  19910. ...info,
  19911. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  19912. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  19913. } ) );
  19914. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  19915. this._availableInstanceIds = source._availableInstanceIds.slice();
  19916. this._availableGeometryIds = source._availableGeometryIds.slice();
  19917. this._nextIndexStart = source._nextIndexStart;
  19918. this._nextVertexStart = source._nextVertexStart;
  19919. this._geometryCount = source._geometryCount;
  19920. this._maxInstanceCount = source._maxInstanceCount;
  19921. this._maxVertexCount = source._maxVertexCount;
  19922. this._maxIndexCount = source._maxIndexCount;
  19923. this._geometryInitialized = source._geometryInitialized;
  19924. this._multiDrawCounts = source._multiDrawCounts.slice();
  19925. this._multiDrawStarts = source._multiDrawStarts.slice();
  19926. this._indirectTexture = source._indirectTexture.clone();
  19927. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  19928. this._matricesTexture = source._matricesTexture.clone();
  19929. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  19930. if ( this._colorsTexture !== null ) {
  19931. this._colorsTexture = source._colorsTexture.clone();
  19932. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  19933. }
  19934. return this;
  19935. }
  19936. /**
  19937. * Frees the GPU-related resources allocated by this instance. Call this
  19938. * method whenever this instance is no longer used in your app.
  19939. */
  19940. dispose() {
  19941. // Assuming the geometry is not shared with other meshes
  19942. this.geometry.dispose();
  19943. this._matricesTexture.dispose();
  19944. this._matricesTexture = null;
  19945. this._indirectTexture.dispose();
  19946. this._indirectTexture = null;
  19947. if ( this._colorsTexture !== null ) {
  19948. this._colorsTexture.dispose();
  19949. this._colorsTexture = null;
  19950. }
  19951. }
  19952. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  19953. // if visibility has not changed and frustum culling and object sorting is not required
  19954. // then skip iterating over all items
  19955. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  19956. return;
  19957. }
  19958. // the indexed version of the multi draw function requires specifying the start
  19959. // offset in bytes.
  19960. const index = geometry.getIndex();
  19961. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  19962. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  19963. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  19964. // assumptions about the index buffer byte size.
  19965. let multiDrawMultiplier = 1;
  19966. if ( material.wireframe ) {
  19967. multiDrawMultiplier = 2;
  19968. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  19969. }
  19970. const instanceInfo = this._instanceInfo;
  19971. const multiDrawStarts = this._multiDrawStarts;
  19972. const multiDrawCounts = this._multiDrawCounts;
  19973. const geometryInfoList = this._geometryInfo;
  19974. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  19975. const indirectTexture = this._indirectTexture;
  19976. const indirectArray = indirectTexture.image.data;
  19977. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  19978. // prepare the frustum in the local frame
  19979. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  19980. _matrix$1
  19981. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  19982. .multiply( this.matrixWorld );
  19983. _frustum.setFromProjectionMatrix(
  19984. _matrix$1,
  19985. camera.coordinateSystem,
  19986. camera.reversedDepth
  19987. );
  19988. }
  19989. let multiDrawCount = 0;
  19990. if ( this.sortObjects ) {
  19991. // get the camera position in the local frame
  19992. _matrix$1.copy( this.matrixWorld ).invert();
  19993. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  19994. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  19995. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19996. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  19997. const geometryId = instanceInfo[ i ].geometryIndex;
  19998. // get the bounds in world space
  19999. this.getMatrixAt( i, _matrix$1 );
  20000. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20001. // determine whether the batched geometry is within the frustum
  20002. let culled = false;
  20003. if ( perObjectFrustumCulled ) {
  20004. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20005. }
  20006. if ( ! culled ) {
  20007. // get the distance from camera used for sorting
  20008. const geometryInfo = geometryInfoList[ geometryId ];
  20009. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20010. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20011. }
  20012. }
  20013. }
  20014. // Sort the draw ranges and prep for rendering
  20015. const list = _renderList.list;
  20016. const customSort = this.customSort;
  20017. if ( customSort === null ) {
  20018. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20019. } else {
  20020. customSort.call( this, list, camera );
  20021. }
  20022. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20023. const item = list[ i ];
  20024. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20025. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20026. indirectArray[ multiDrawCount ] = item.index;
  20027. multiDrawCount ++;
  20028. }
  20029. _renderList.reset();
  20030. } else {
  20031. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20032. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20033. const geometryId = instanceInfo[ i ].geometryIndex;
  20034. // determine whether the batched geometry is within the frustum
  20035. let culled = false;
  20036. if ( perObjectFrustumCulled ) {
  20037. // get the bounds in world space
  20038. this.getMatrixAt( i, _matrix$1 );
  20039. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20040. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20041. }
  20042. if ( ! culled ) {
  20043. const geometryInfo = geometryInfoList[ geometryId ];
  20044. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20045. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20046. indirectArray[ multiDrawCount ] = i;
  20047. multiDrawCount ++;
  20048. }
  20049. }
  20050. }
  20051. }
  20052. indirectTexture.needsUpdate = true;
  20053. this._multiDrawCount = multiDrawCount;
  20054. this._visibilityChanged = false;
  20055. }
  20056. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20057. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20058. }
  20059. }
  20060. /**
  20061. * A material for rendering line primitives.
  20062. *
  20063. * Materials define the appearance of renderable 3D objects.
  20064. *
  20065. * ```js
  20066. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20067. * ```
  20068. *
  20069. * @augments Material
  20070. */
  20071. class LineBasicMaterial extends Material {
  20072. /**
  20073. * Constructs a new line basic material.
  20074. *
  20075. * @param {Object} [parameters] - An object with one or more properties
  20076. * defining the material's appearance. Any property of the material
  20077. * (including any property from inherited materials) can be passed
  20078. * in here. Color values can be passed any type of value accepted
  20079. * by {@link Color#set}.
  20080. */
  20081. constructor( parameters ) {
  20082. super();
  20083. /**
  20084. * This flag can be used for type testing.
  20085. *
  20086. * @type {boolean}
  20087. * @readonly
  20088. * @default true
  20089. */
  20090. this.isLineBasicMaterial = true;
  20091. this.type = 'LineBasicMaterial';
  20092. /**
  20093. * Color of the material.
  20094. *
  20095. * @type {Color}
  20096. * @default (1,1,1)
  20097. */
  20098. this.color = new Color( 0xffffff );
  20099. /**
  20100. * Sets the color of the lines using data from a texture. The texture map
  20101. * color is modulated by the diffuse `color`.
  20102. *
  20103. * @type {?Texture}
  20104. * @default null
  20105. */
  20106. this.map = null;
  20107. /**
  20108. * Controls line thickness or lines.
  20109. *
  20110. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20111. * ignore this setting and always render line primitives with a
  20112. * width of one pixel.
  20113. *
  20114. * @type {number}
  20115. * @default 1
  20116. */
  20117. this.linewidth = 1;
  20118. /**
  20119. * Defines appearance of line ends.
  20120. *
  20121. * Can only be used with {@link SVGRenderer}.
  20122. *
  20123. * @type {('butt'|'round'|'square')}
  20124. * @default 'round'
  20125. */
  20126. this.linecap = 'round';
  20127. /**
  20128. * Defines appearance of line joints.
  20129. *
  20130. * Can only be used with {@link SVGRenderer}.
  20131. *
  20132. * @type {('round'|'bevel'|'miter')}
  20133. * @default 'round'
  20134. */
  20135. this.linejoin = 'round';
  20136. /**
  20137. * Whether the material is affected by fog or not.
  20138. *
  20139. * @type {boolean}
  20140. * @default true
  20141. */
  20142. this.fog = true;
  20143. this.setValues( parameters );
  20144. }
  20145. copy( source ) {
  20146. super.copy( source );
  20147. this.color.copy( source.color );
  20148. this.map = source.map;
  20149. this.linewidth = source.linewidth;
  20150. this.linecap = source.linecap;
  20151. this.linejoin = source.linejoin;
  20152. this.fog = source.fog;
  20153. return this;
  20154. }
  20155. }
  20156. const _vStart = /*@__PURE__*/ new Vector3();
  20157. const _vEnd = /*@__PURE__*/ new Vector3();
  20158. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20159. const _ray$1 = /*@__PURE__*/ new Ray();
  20160. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20161. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20162. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20163. /**
  20164. * A continuous line. The line are rendered by connecting consecutive
  20165. * vertices with straight lines.
  20166. *
  20167. * ```js
  20168. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20169. *
  20170. * const points = [];
  20171. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20172. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20173. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20174. *
  20175. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20176. *
  20177. * const line = new THREE.Line( geometry, material );
  20178. * scene.add( line );
  20179. * ```
  20180. *
  20181. * @augments Object3D
  20182. */
  20183. class Line extends Object3D {
  20184. /**
  20185. * Constructs a new line.
  20186. *
  20187. * @param {BufferGeometry} [geometry] - The line geometry.
  20188. * @param {Material|Array<Material>} [material] - The line material.
  20189. */
  20190. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20191. super();
  20192. /**
  20193. * This flag can be used for type testing.
  20194. *
  20195. * @type {boolean}
  20196. * @readonly
  20197. * @default true
  20198. */
  20199. this.isLine = true;
  20200. this.type = 'Line';
  20201. /**
  20202. * The line geometry.
  20203. *
  20204. * @type {BufferGeometry}
  20205. */
  20206. this.geometry = geometry;
  20207. /**
  20208. * The line material.
  20209. *
  20210. * @type {Material|Array<Material>}
  20211. * @default LineBasicMaterial
  20212. */
  20213. this.material = material;
  20214. /**
  20215. * A dictionary representing the morph targets in the geometry. The key is the
  20216. * morph targets name, the value its attribute index. This member is `undefined`
  20217. * by default and only set when morph targets are detected in the geometry.
  20218. *
  20219. * @type {Object<string,number>|undefined}
  20220. * @default undefined
  20221. */
  20222. this.morphTargetDictionary = undefined;
  20223. /**
  20224. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20225. * is applied. This member is `undefined` by default and only set when morph targets are
  20226. * detected in the geometry.
  20227. *
  20228. * @type {Array<number>|undefined}
  20229. * @default undefined
  20230. */
  20231. this.morphTargetInfluences = undefined;
  20232. this.updateMorphTargets();
  20233. }
  20234. copy( source, recursive ) {
  20235. super.copy( source, recursive );
  20236. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20237. this.geometry = source.geometry;
  20238. return this;
  20239. }
  20240. /**
  20241. * Computes an array of distance values which are necessary for rendering dashed lines.
  20242. * For each vertex in the geometry, the method calculates the cumulative length from the
  20243. * current point to the very beginning of the line.
  20244. *
  20245. * @return {Line} A reference to this line.
  20246. */
  20247. computeLineDistances() {
  20248. const geometry = this.geometry;
  20249. // we assume non-indexed geometry
  20250. if ( geometry.index === null ) {
  20251. const positionAttribute = geometry.attributes.position;
  20252. const lineDistances = [ 0 ];
  20253. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20254. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20255. _vEnd.fromBufferAttribute( positionAttribute, i );
  20256. lineDistances[ i ] = lineDistances[ i - 1 ];
  20257. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20258. }
  20259. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20260. } else {
  20261. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20262. }
  20263. return this;
  20264. }
  20265. /**
  20266. * Computes intersection points between a casted ray and this line.
  20267. *
  20268. * @param {Raycaster} raycaster - The raycaster.
  20269. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20270. */
  20271. raycast( raycaster, intersects ) {
  20272. const geometry = this.geometry;
  20273. const matrixWorld = this.matrixWorld;
  20274. const threshold = raycaster.params.Line.threshold;
  20275. const drawRange = geometry.drawRange;
  20276. // Checking boundingSphere distance to ray
  20277. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20278. _sphere$1.copy( geometry.boundingSphere );
  20279. _sphere$1.applyMatrix4( matrixWorld );
  20280. _sphere$1.radius += threshold;
  20281. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20282. //
  20283. _inverseMatrix$1.copy( matrixWorld ).invert();
  20284. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20285. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20286. const localThresholdSq = localThreshold * localThreshold;
  20287. const step = this.isLineSegments ? 2 : 1;
  20288. const index = geometry.index;
  20289. const attributes = geometry.attributes;
  20290. const positionAttribute = attributes.position;
  20291. if ( index !== null ) {
  20292. const start = Math.max( 0, drawRange.start );
  20293. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20294. for ( let i = start, l = end - 1; i < l; i += step ) {
  20295. const a = index.getX( i );
  20296. const b = index.getX( i + 1 );
  20297. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20298. if ( intersect ) {
  20299. intersects.push( intersect );
  20300. }
  20301. }
  20302. if ( this.isLineLoop ) {
  20303. const a = index.getX( end - 1 );
  20304. const b = index.getX( start );
  20305. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20306. if ( intersect ) {
  20307. intersects.push( intersect );
  20308. }
  20309. }
  20310. } else {
  20311. const start = Math.max( 0, drawRange.start );
  20312. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20313. for ( let i = start, l = end - 1; i < l; i += step ) {
  20314. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20315. if ( intersect ) {
  20316. intersects.push( intersect );
  20317. }
  20318. }
  20319. if ( this.isLineLoop ) {
  20320. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20321. if ( intersect ) {
  20322. intersects.push( intersect );
  20323. }
  20324. }
  20325. }
  20326. }
  20327. /**
  20328. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20329. * to make sure existing morph targets can influence this 3D object.
  20330. */
  20331. updateMorphTargets() {
  20332. const geometry = this.geometry;
  20333. const morphAttributes = geometry.morphAttributes;
  20334. const keys = Object.keys( morphAttributes );
  20335. if ( keys.length > 0 ) {
  20336. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20337. if ( morphAttribute !== undefined ) {
  20338. this.morphTargetInfluences = [];
  20339. this.morphTargetDictionary = {};
  20340. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20341. const name = morphAttribute[ m ].name || String( m );
  20342. this.morphTargetInfluences.push( 0 );
  20343. this.morphTargetDictionary[ name ] = m;
  20344. }
  20345. }
  20346. }
  20347. }
  20348. }
  20349. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20350. const positionAttribute = object.geometry.attributes.position;
  20351. _vStart.fromBufferAttribute( positionAttribute, a );
  20352. _vEnd.fromBufferAttribute( positionAttribute, b );
  20353. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20354. if ( distSq > thresholdSq ) return;
  20355. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20356. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20357. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20358. return {
  20359. distance: distance,
  20360. // What do we want? intersection point on the ray or on the segment??
  20361. // point: raycaster.ray.at( distance ),
  20362. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20363. index: i,
  20364. face: null,
  20365. faceIndex: null,
  20366. barycoord: null,
  20367. object: object
  20368. };
  20369. }
  20370. const _start = /*@__PURE__*/ new Vector3();
  20371. const _end = /*@__PURE__*/ new Vector3();
  20372. /**
  20373. * A series of lines drawn between pairs of vertices.
  20374. *
  20375. * @augments Line
  20376. */
  20377. class LineSegments extends Line {
  20378. /**
  20379. * Constructs a new line segments.
  20380. *
  20381. * @param {BufferGeometry} [geometry] - The line geometry.
  20382. * @param {Material|Array<Material>} [material] - The line material.
  20383. */
  20384. constructor( geometry, material ) {
  20385. super( geometry, material );
  20386. /**
  20387. * This flag can be used for type testing.
  20388. *
  20389. * @type {boolean}
  20390. * @readonly
  20391. * @default true
  20392. */
  20393. this.isLineSegments = true;
  20394. this.type = 'LineSegments';
  20395. }
  20396. computeLineDistances() {
  20397. const geometry = this.geometry;
  20398. // we assume non-indexed geometry
  20399. if ( geometry.index === null ) {
  20400. const positionAttribute = geometry.attributes.position;
  20401. const lineDistances = [];
  20402. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20403. _start.fromBufferAttribute( positionAttribute, i );
  20404. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20405. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20406. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20407. }
  20408. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20409. } else {
  20410. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20411. }
  20412. return this;
  20413. }
  20414. }
  20415. /**
  20416. * A continuous line. This is nearly the same as {@link Line} the only difference
  20417. * is that the last vertex is connected with the first vertex in order to close
  20418. * the line to form a loop.
  20419. *
  20420. * @augments Line
  20421. */
  20422. class LineLoop extends Line {
  20423. /**
  20424. * Constructs a new line loop.
  20425. *
  20426. * @param {BufferGeometry} [geometry] - The line geometry.
  20427. * @param {Material|Array<Material>} [material] - The line material.
  20428. */
  20429. constructor( geometry, material ) {
  20430. super( geometry, material );
  20431. /**
  20432. * This flag can be used for type testing.
  20433. *
  20434. * @type {boolean}
  20435. * @readonly
  20436. * @default true
  20437. */
  20438. this.isLineLoop = true;
  20439. this.type = 'LineLoop';
  20440. }
  20441. }
  20442. /**
  20443. * A material for rendering point primitives.
  20444. *
  20445. * Materials define the appearance of renderable 3D objects.
  20446. *
  20447. * ```js
  20448. * const vertices = [];
  20449. *
  20450. * for ( let i = 0; i < 10000; i ++ ) {
  20451. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20452. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20453. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20454. *
  20455. * vertices.push( x, y, z );
  20456. * }
  20457. *
  20458. * const geometry = new THREE.BufferGeometry();
  20459. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20460. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20461. * const points = new THREE.Points( geometry, material );
  20462. * scene.add( points );
  20463. * ```
  20464. *
  20465. * @augments Material
  20466. */
  20467. class PointsMaterial extends Material {
  20468. /**
  20469. * Constructs a new points material.
  20470. *
  20471. * @param {Object} [parameters] - An object with one or more properties
  20472. * defining the material's appearance. Any property of the material
  20473. * (including any property from inherited materials) can be passed
  20474. * in here. Color values can be passed any type of value accepted
  20475. * by {@link Color#set}.
  20476. */
  20477. constructor( parameters ) {
  20478. super();
  20479. /**
  20480. * This flag can be used for type testing.
  20481. *
  20482. * @type {boolean}
  20483. * @readonly
  20484. * @default true
  20485. */
  20486. this.isPointsMaterial = true;
  20487. this.type = 'PointsMaterial';
  20488. /**
  20489. * Color of the material.
  20490. *
  20491. * @type {Color}
  20492. * @default (1,1,1)
  20493. */
  20494. this.color = new Color( 0xffffff );
  20495. /**
  20496. * The color map. May optionally include an alpha channel, typically combined
  20497. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20498. * color is modulated by the diffuse `color`.
  20499. *
  20500. * @type {?Texture}
  20501. * @default null
  20502. */
  20503. this.map = null;
  20504. /**
  20505. * The alpha map is a grayscale texture that controls the opacity across the
  20506. * surface (black: fully transparent; white: fully opaque).
  20507. *
  20508. * Only the color of the texture is used, ignoring the alpha channel if one
  20509. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20510. * when sampling this texture due to the extra bit of precision provided for
  20511. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20512. * luminance/alpha textures will also still work as expected.
  20513. *
  20514. * @type {?Texture}
  20515. * @default null
  20516. */
  20517. this.alphaMap = null;
  20518. /**
  20519. * Defines the size of the points in pixels.
  20520. *
  20521. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete).
  20522. *
  20523. * @type {number}
  20524. * @default 1
  20525. */
  20526. this.size = 1;
  20527. /**
  20528. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20529. *
  20530. * @type {boolean}
  20531. * @default true
  20532. */
  20533. this.sizeAttenuation = true;
  20534. /**
  20535. * Whether the material is affected by fog or not.
  20536. *
  20537. * @type {boolean}
  20538. * @default true
  20539. */
  20540. this.fog = true;
  20541. this.setValues( parameters );
  20542. }
  20543. copy( source ) {
  20544. super.copy( source );
  20545. this.color.copy( source.color );
  20546. this.map = source.map;
  20547. this.alphaMap = source.alphaMap;
  20548. this.size = source.size;
  20549. this.sizeAttenuation = source.sizeAttenuation;
  20550. this.fog = source.fog;
  20551. return this;
  20552. }
  20553. }
  20554. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20555. const _ray = /*@__PURE__*/ new Ray();
  20556. const _sphere = /*@__PURE__*/ new Sphere();
  20557. const _position$3 = /*@__PURE__*/ new Vector3();
  20558. /**
  20559. * A class for displaying points or point clouds.
  20560. *
  20561. * @augments Object3D
  20562. */
  20563. class Points extends Object3D {
  20564. /**
  20565. * Constructs a new point cloud.
  20566. *
  20567. * @param {BufferGeometry} [geometry] - The points geometry.
  20568. * @param {Material|Array<Material>} [material] - The points material.
  20569. */
  20570. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20571. super();
  20572. /**
  20573. * This flag can be used for type testing.
  20574. *
  20575. * @type {boolean}
  20576. * @readonly
  20577. * @default true
  20578. */
  20579. this.isPoints = true;
  20580. this.type = 'Points';
  20581. /**
  20582. * The points geometry.
  20583. *
  20584. * @type {BufferGeometry}
  20585. */
  20586. this.geometry = geometry;
  20587. /**
  20588. * The line material.
  20589. *
  20590. * @type {Material|Array<Material>}
  20591. * @default PointsMaterial
  20592. */
  20593. this.material = material;
  20594. /**
  20595. * A dictionary representing the morph targets in the geometry. The key is the
  20596. * morph targets name, the value its attribute index. This member is `undefined`
  20597. * by default and only set when morph targets are detected in the geometry.
  20598. *
  20599. * @type {Object<string,number>|undefined}
  20600. * @default undefined
  20601. */
  20602. this.morphTargetDictionary = undefined;
  20603. /**
  20604. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20605. * is applied. This member is `undefined` by default and only set when morph targets are
  20606. * detected in the geometry.
  20607. *
  20608. * @type {Array<number>|undefined}
  20609. * @default undefined
  20610. */
  20611. this.morphTargetInfluences = undefined;
  20612. this.updateMorphTargets();
  20613. }
  20614. copy( source, recursive ) {
  20615. super.copy( source, recursive );
  20616. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20617. this.geometry = source.geometry;
  20618. return this;
  20619. }
  20620. /**
  20621. * Computes intersection points between a casted ray and this point cloud.
  20622. *
  20623. * @param {Raycaster} raycaster - The raycaster.
  20624. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20625. */
  20626. raycast( raycaster, intersects ) {
  20627. const geometry = this.geometry;
  20628. const matrixWorld = this.matrixWorld;
  20629. const threshold = raycaster.params.Points.threshold;
  20630. const drawRange = geometry.drawRange;
  20631. // Checking boundingSphere distance to ray
  20632. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20633. _sphere.copy( geometry.boundingSphere );
  20634. _sphere.applyMatrix4( matrixWorld );
  20635. _sphere.radius += threshold;
  20636. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20637. //
  20638. _inverseMatrix.copy( matrixWorld ).invert();
  20639. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20640. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20641. const localThresholdSq = localThreshold * localThreshold;
  20642. const index = geometry.index;
  20643. const attributes = geometry.attributes;
  20644. const positionAttribute = attributes.position;
  20645. if ( index !== null ) {
  20646. const start = Math.max( 0, drawRange.start );
  20647. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20648. for ( let i = start, il = end; i < il; i ++ ) {
  20649. const a = index.getX( i );
  20650. _position$3.fromBufferAttribute( positionAttribute, a );
  20651. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20652. }
  20653. } else {
  20654. const start = Math.max( 0, drawRange.start );
  20655. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20656. for ( let i = start, l = end; i < l; i ++ ) {
  20657. _position$3.fromBufferAttribute( positionAttribute, i );
  20658. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20659. }
  20660. }
  20661. }
  20662. /**
  20663. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20664. * to make sure existing morph targets can influence this 3D object.
  20665. */
  20666. updateMorphTargets() {
  20667. const geometry = this.geometry;
  20668. const morphAttributes = geometry.morphAttributes;
  20669. const keys = Object.keys( morphAttributes );
  20670. if ( keys.length > 0 ) {
  20671. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20672. if ( morphAttribute !== undefined ) {
  20673. this.morphTargetInfluences = [];
  20674. this.morphTargetDictionary = {};
  20675. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20676. const name = morphAttribute[ m ].name || String( m );
  20677. this.morphTargetInfluences.push( 0 );
  20678. this.morphTargetDictionary[ name ] = m;
  20679. }
  20680. }
  20681. }
  20682. }
  20683. }
  20684. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20685. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20686. if ( rayPointDistanceSq < localThresholdSq ) {
  20687. const intersectPoint = new Vector3();
  20688. _ray.closestPointToPoint( point, intersectPoint );
  20689. intersectPoint.applyMatrix4( matrixWorld );
  20690. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20691. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20692. intersects.push( {
  20693. distance: distance,
  20694. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20695. point: intersectPoint,
  20696. index: index,
  20697. face: null,
  20698. faceIndex: null,
  20699. barycoord: null,
  20700. object: object
  20701. } );
  20702. }
  20703. }
  20704. /**
  20705. * A texture for use with a video.
  20706. *
  20707. * ```js
  20708. * // assuming you have created a HTML video element with id="video"
  20709. * const video = document.getElementById( 'video' );
  20710. * const texture = new THREE.VideoTexture( video );
  20711. * ```
  20712. *
  20713. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  20714. * set to THREE.SRGBColorSpace.
  20715. *
  20716. * Note: After the initial use of a texture, its dimensions, format, and type
  20717. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  20718. *
  20719. * @augments Texture
  20720. */
  20721. class VideoTexture extends Texture {
  20722. /**
  20723. * Constructs a new video texture.
  20724. *
  20725. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  20726. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20727. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20728. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20729. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20730. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20731. * @param {number} [format=RGBAFormat] - The texture format.
  20732. * @param {number} [type=UnsignedByteType] - The texture type.
  20733. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20734. */
  20735. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  20736. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20737. /**
  20738. * This flag can be used for type testing.
  20739. *
  20740. * @type {boolean}
  20741. * @readonly
  20742. * @default true
  20743. */
  20744. this.isVideoTexture = true;
  20745. /**
  20746. * Whether to generate mipmaps (if possible) for a texture.
  20747. *
  20748. * Overwritten and set to `false` by default.
  20749. *
  20750. * @type {boolean}
  20751. * @default false
  20752. */
  20753. this.generateMipmaps = false;
  20754. /**
  20755. * The video frame request callback identifier, which is a positive integer.
  20756. *
  20757. * Value of 0 represents no scheduled rVFC.
  20758. *
  20759. * @private
  20760. * @type {number}
  20761. */
  20762. this._requestVideoFrameCallbackId = 0;
  20763. const scope = this;
  20764. function updateVideo() {
  20765. scope.needsUpdate = true;
  20766. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20767. }
  20768. if ( 'requestVideoFrameCallback' in video ) {
  20769. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  20770. }
  20771. }
  20772. clone() {
  20773. return new this.constructor( this.image ).copy( this );
  20774. }
  20775. /**
  20776. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  20777. * to `true` every time a new frame is available.
  20778. *
  20779. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  20780. */
  20781. update() {
  20782. const video = this.image;
  20783. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20784. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20785. this.needsUpdate = true;
  20786. }
  20787. }
  20788. dispose() {
  20789. if ( this._requestVideoFrameCallbackId !== 0 ) {
  20790. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  20791. this._requestVideoFrameCallbackId = 0;
  20792. }
  20793. super.dispose();
  20794. }
  20795. }
  20796. /**
  20797. * This class can be used as an alternative way to define video data. Instead of using
  20798. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  20799. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  20800. * video frames are decoded with the WebCodecs API.
  20801. *
  20802. * ```js
  20803. * const texture = new THREE.VideoFrameTexture();
  20804. * texture.setFrame( frame );
  20805. * ```
  20806. *
  20807. * @augments VideoTexture
  20808. */
  20809. class VideoFrameTexture extends VideoTexture {
  20810. /**
  20811. * Constructs a new video frame texture.
  20812. *
  20813. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20814. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20815. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20816. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20817. * @param {number} [minFilter=LinearFilter] - The min filter value.
  20818. * @param {number} [format=RGBAFormat] - The texture format.
  20819. * @param {number} [type=UnsignedByteType] - The texture type.
  20820. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20821. */
  20822. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20823. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20824. /**
  20825. * This flag can be used for type testing.
  20826. *
  20827. * @type {boolean}
  20828. * @readonly
  20829. * @default true
  20830. */
  20831. this.isVideoFrameTexture = true;
  20832. }
  20833. /**
  20834. * This method overwritten with an empty implementation since
  20835. * this type of texture is updated via `setFrame()`.
  20836. */
  20837. update() {}
  20838. clone() {
  20839. return new this.constructor().copy( this ); // restoring Texture.clone()
  20840. }
  20841. /**
  20842. * Sets the current frame of the video. This will automatically update the texture
  20843. * so the data can be used for rendering.
  20844. *
  20845. * @param {VideoFrame} frame - The video frame.
  20846. */
  20847. setFrame( frame ) {
  20848. this.image = frame;
  20849. this.needsUpdate = true;
  20850. }
  20851. }
  20852. /**
  20853. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  20854. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  20855. * as a texture for further usage.
  20856. *
  20857. * ```js
  20858. * const pixelRatio = window.devicePixelRatio;
  20859. * const textureSize = 128 * pixelRatio;
  20860. *
  20861. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  20862. *
  20863. * // calculate start position for copying part of the frame data
  20864. * const vector = new Vector2();
  20865. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  20866. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  20867. *
  20868. * renderer.render( scene, camera );
  20869. *
  20870. * // copy part of the rendered frame into the framebuffer texture
  20871. * renderer.copyFramebufferToTexture( frameTexture, vector );
  20872. * ```
  20873. *
  20874. * @augments Texture
  20875. */
  20876. class FramebufferTexture extends Texture {
  20877. /**
  20878. * Constructs a new framebuffer texture.
  20879. *
  20880. * @param {number} [width] - The width of the texture.
  20881. * @param {number} [height] - The height of the texture.
  20882. */
  20883. constructor( width, height ) {
  20884. super( { width, height } );
  20885. /**
  20886. * This flag can be used for type testing.
  20887. *
  20888. * @type {boolean}
  20889. * @readonly
  20890. * @default true
  20891. */
  20892. this.isFramebufferTexture = true;
  20893. /**
  20894. * How the texture is sampled when a texel covers more than one pixel.
  20895. *
  20896. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20897. *
  20898. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20899. * @default NearestFilter
  20900. */
  20901. this.magFilter = NearestFilter;
  20902. /**
  20903. * How the texture is sampled when a texel covers less than one pixel.
  20904. *
  20905. * Overwritten and set to `NearestFilter` by default to disable filtering.
  20906. *
  20907. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  20908. * @default NearestFilter
  20909. */
  20910. this.minFilter = NearestFilter;
  20911. /**
  20912. * Whether to generate mipmaps (if possible) for a texture.
  20913. *
  20914. * Overwritten and set to `false` by default.
  20915. *
  20916. * @type {boolean}
  20917. * @default false
  20918. */
  20919. this.generateMipmaps = false;
  20920. this.needsUpdate = true;
  20921. }
  20922. }
  20923. /**
  20924. * Creates a texture based on data in compressed form.
  20925. *
  20926. * These texture are usually loaded with {@link CompressedTextureLoader}.
  20927. *
  20928. * @augments Texture
  20929. */
  20930. class CompressedTexture extends Texture {
  20931. /**
  20932. * Constructs a new compressed texture.
  20933. *
  20934. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  20935. * the data and dimensions.
  20936. * @param {number} width - The width of the texture.
  20937. * @param {number} height - The height of the texture.
  20938. * @param {number} [format=RGBAFormat] - The texture format.
  20939. * @param {number} [type=UnsignedByteType] - The texture type.
  20940. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  20941. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  20942. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  20943. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  20944. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  20945. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  20946. * @param {string} [colorSpace=NoColorSpace] - The color space.
  20947. */
  20948. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20949. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20950. /**
  20951. * This flag can be used for type testing.
  20952. *
  20953. * @type {boolean}
  20954. * @readonly
  20955. * @default true
  20956. */
  20957. this.isCompressedTexture = true;
  20958. /**
  20959. * The image property of a compressed texture just defines its dimensions.
  20960. *
  20961. * @type {{width:number,height:number}}
  20962. */
  20963. this.image = { width: width, height: height };
  20964. /**
  20965. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  20966. *
  20967. * @type {Array<Object>}
  20968. */
  20969. this.mipmaps = mipmaps;
  20970. /**
  20971. * If set to `true`, the texture is flipped along the vertical axis when
  20972. * uploaded to the GPU.
  20973. *
  20974. * Overwritten and set to `false` by default since it is not possible to
  20975. * flip compressed textures.
  20976. *
  20977. * @type {boolean}
  20978. * @default false
  20979. * @readonly
  20980. */
  20981. this.flipY = false;
  20982. /**
  20983. * Whether to generate mipmaps (if possible) for a texture.
  20984. *
  20985. * Overwritten and set to `false` by default since it is not
  20986. * possible to generate mipmaps for compressed data. Mipmaps
  20987. * must be embedded in the compressed texture file.
  20988. *
  20989. * @type {boolean}
  20990. * @default false
  20991. * @readonly
  20992. */
  20993. this.generateMipmaps = false;
  20994. }
  20995. }
  20996. /**
  20997. * Creates a texture 2D array based on data in compressed form.
  20998. *
  20999. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21000. *
  21001. * @augments CompressedTexture
  21002. */
  21003. class CompressedArrayTexture extends CompressedTexture {
  21004. /**
  21005. * Constructs a new compressed array texture.
  21006. *
  21007. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21008. * the data and dimensions.
  21009. * @param {number} width - The width of the texture.
  21010. * @param {number} height - The height of the texture.
  21011. * @param {number} depth - The depth of the texture.
  21012. * @param {number} [format=RGBAFormat] - The min filter value.
  21013. * @param {number} [type=UnsignedByteType] - The min filter value.
  21014. */
  21015. constructor( mipmaps, width, height, depth, format, type ) {
  21016. super( mipmaps, width, height, format, type );
  21017. /**
  21018. * This flag can be used for type testing.
  21019. *
  21020. * @type {boolean}
  21021. * @readonly
  21022. * @default true
  21023. */
  21024. this.isCompressedArrayTexture = true;
  21025. /**
  21026. * The image property of a compressed texture just defines its dimensions.
  21027. *
  21028. * @name CompressedArrayTexture#image
  21029. * @type {{width:number,height:number,depth:number}}
  21030. */
  21031. this.image.depth = depth;
  21032. /**
  21033. * This defines how the texture is wrapped in the depth and corresponds to
  21034. * *W* in UVW mapping.
  21035. *
  21036. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21037. * @default ClampToEdgeWrapping
  21038. */
  21039. this.wrapR = ClampToEdgeWrapping;
  21040. /**
  21041. * A set of all layers which need to be updated in the texture.
  21042. *
  21043. * @type {Set<number>}
  21044. */
  21045. this.layerUpdates = new Set();
  21046. }
  21047. /**
  21048. * Describes that a specific layer of the texture needs to be updated.
  21049. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21050. * entire compressed texture array is sent to the GPU. Marking specific
  21051. * layers will only transmit subsets of all mipmaps associated with a
  21052. * specific depth in the array which is often much more performant.
  21053. *
  21054. * @param {number} layerIndex - The layer index that should be updated.
  21055. */
  21056. addLayerUpdate( layerIndex ) {
  21057. this.layerUpdates.add( layerIndex );
  21058. }
  21059. /**
  21060. * Resets the layer updates registry.
  21061. */
  21062. clearLayerUpdates() {
  21063. this.layerUpdates.clear();
  21064. }
  21065. }
  21066. /**
  21067. * Creates a cube texture based on data in compressed form.
  21068. *
  21069. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21070. *
  21071. * @augments CompressedTexture
  21072. */
  21073. class CompressedCubeTexture extends CompressedTexture {
  21074. /**
  21075. * Constructs a new compressed texture.
  21076. *
  21077. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21078. * @param {number} [format=RGBAFormat] - The texture format.
  21079. * @param {number} [type=UnsignedByteType] - The texture type.
  21080. */
  21081. constructor( images, format, type ) {
  21082. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21083. /**
  21084. * This flag can be used for type testing.
  21085. *
  21086. * @type {boolean}
  21087. * @readonly
  21088. * @default true
  21089. */
  21090. this.isCompressedCubeTexture = true;
  21091. /**
  21092. * This flag can be used for type testing.
  21093. *
  21094. * @type {boolean}
  21095. * @readonly
  21096. * @default true
  21097. */
  21098. this.isCubeTexture = true;
  21099. this.image = images;
  21100. }
  21101. }
  21102. /**
  21103. * Creates a cube texture made up of six images.
  21104. *
  21105. * ```js
  21106. * const loader = new THREE.CubeTextureLoader();
  21107. * loader.setPath( 'textures/cube/pisa/' );
  21108. *
  21109. * const textureCube = loader.load( [
  21110. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21111. * ] );
  21112. *
  21113. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21114. * ```
  21115. *
  21116. * @augments Texture
  21117. */
  21118. class CubeTexture extends Texture {
  21119. /**
  21120. * Constructs a new cube texture.
  21121. *
  21122. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21123. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21124. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21125. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21126. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21127. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21128. * @param {number} [format=RGBAFormat] - The texture format.
  21129. * @param {number} [type=UnsignedByteType] - The texture type.
  21130. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21131. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21132. */
  21133. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21134. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21135. /**
  21136. * This flag can be used for type testing.
  21137. *
  21138. * @type {boolean}
  21139. * @readonly
  21140. * @default true
  21141. */
  21142. this.isCubeTexture = true;
  21143. /**
  21144. * If set to `true`, the texture is flipped along the vertical axis when
  21145. * uploaded to the GPU.
  21146. *
  21147. * Overwritten and set to `false` by default.
  21148. *
  21149. * @type {boolean}
  21150. * @default false
  21151. */
  21152. this.flipY = false;
  21153. }
  21154. /**
  21155. * Alias for {@link CubeTexture#image}.
  21156. *
  21157. * @type {Array<Image>}
  21158. */
  21159. get images() {
  21160. return this.image;
  21161. }
  21162. set images( value ) {
  21163. this.image = value;
  21164. }
  21165. }
  21166. /**
  21167. * Creates a texture from a canvas element.
  21168. *
  21169. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21170. * to `true` immediately since a canvas can directly be used for rendering.
  21171. *
  21172. * @augments Texture
  21173. */
  21174. class CanvasTexture extends Texture {
  21175. /**
  21176. * Constructs a new texture.
  21177. *
  21178. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21179. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21180. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21181. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21182. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21183. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21184. * @param {number} [format=RGBAFormat] - The texture format.
  21185. * @param {number} [type=UnsignedByteType] - The texture type.
  21186. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21187. */
  21188. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21189. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21190. /**
  21191. * This flag can be used for type testing.
  21192. *
  21193. * @type {boolean}
  21194. * @readonly
  21195. * @default true
  21196. */
  21197. this.isCanvasTexture = true;
  21198. this.needsUpdate = true;
  21199. }
  21200. }
  21201. /**
  21202. * This class can be used to automatically save the depth information of a
  21203. * rendering into a texture.
  21204. *
  21205. * @augments Texture
  21206. */
  21207. class DepthTexture extends Texture {
  21208. /**
  21209. * Constructs a new depth texture.
  21210. *
  21211. * @param {number} width - The width of the texture.
  21212. * @param {number} height - The height of the texture.
  21213. * @param {number} [type=UnsignedIntType] - The texture type.
  21214. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21215. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21216. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21217. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21218. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21219. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21220. * @param {number} [format=DepthFormat] - The texture format.
  21221. * @param {number} [depth=1] - The depth of the texture.
  21222. */
  21223. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21224. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21225. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21226. }
  21227. const image = { width: width, height: height, depth: depth };
  21228. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21229. /**
  21230. * This flag can be used for type testing.
  21231. *
  21232. * @type {boolean}
  21233. * @readonly
  21234. * @default true
  21235. */
  21236. this.isDepthTexture = true;
  21237. /**
  21238. * If set to `true`, the texture is flipped along the vertical axis when
  21239. * uploaded to the GPU.
  21240. *
  21241. * Overwritten and set to `false` by default.
  21242. *
  21243. * @type {boolean}
  21244. * @default false
  21245. */
  21246. this.flipY = false;
  21247. /**
  21248. * Whether to generate mipmaps (if possible) for a texture.
  21249. *
  21250. * Overwritten and set to `false` by default.
  21251. *
  21252. * @type {boolean}
  21253. * @default false
  21254. */
  21255. this.generateMipmaps = false;
  21256. /**
  21257. * Code corresponding to the depth compare function.
  21258. *
  21259. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21260. * @default null
  21261. */
  21262. this.compareFunction = null;
  21263. }
  21264. copy( source ) {
  21265. super.copy( source );
  21266. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21267. this.compareFunction = source.compareFunction;
  21268. return this;
  21269. }
  21270. toJSON( meta ) {
  21271. const data = super.toJSON( meta );
  21272. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21273. return data;
  21274. }
  21275. }
  21276. /**
  21277. * This class can be used to automatically save the depth information of a
  21278. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21279. *
  21280. * @augments DepthTexture
  21281. */
  21282. class CubeDepthTexture extends DepthTexture {
  21283. /**
  21284. * Constructs a new cube depth texture.
  21285. *
  21286. * @param {number} size - The size (width and height) of each cube face.
  21287. * @param {number} [type=UnsignedIntType] - The texture type.
  21288. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21289. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21290. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21291. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21292. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21293. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21294. * @param {number} [format=DepthFormat] - The texture format.
  21295. */
  21296. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21297. // Create 6 identical image descriptors for the cube faces
  21298. const image = { width: size, height: size, depth: 1 };
  21299. const images = [ image, image, image, image, image, image ];
  21300. // Call DepthTexture constructor with width, height
  21301. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21302. // Replace the single image with the array of 6 images
  21303. this.image = images;
  21304. /**
  21305. * This flag can be used for type testing.
  21306. *
  21307. * @type {boolean}
  21308. * @readonly
  21309. * @default true
  21310. */
  21311. this.isCubeDepthTexture = true;
  21312. /**
  21313. * Set to true for cube texture handling in WebGLTextures.
  21314. *
  21315. * @type {boolean}
  21316. * @readonly
  21317. * @default true
  21318. */
  21319. this.isCubeTexture = true;
  21320. }
  21321. /**
  21322. * Alias for {@link CubeDepthTexture#image}.
  21323. *
  21324. * @type {Array<Image>}
  21325. */
  21326. get images() {
  21327. return this.image;
  21328. }
  21329. set images( value ) {
  21330. this.image = value;
  21331. }
  21332. }
  21333. /**
  21334. * Represents a texture created externally with the same renderer context.
  21335. *
  21336. * This may be a texture from a protected media stream, device camera feed,
  21337. * or other data feeds like a depth sensor.
  21338. *
  21339. * Note that this class is only supported in {@link WebGLRenderer}, and in
  21340. * the {@link WebGPURenderer} WebGPU backend.
  21341. *
  21342. * @augments Texture
  21343. */
  21344. class ExternalTexture extends Texture {
  21345. /**
  21346. * Creates a new raw texture.
  21347. *
  21348. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21349. */
  21350. constructor( sourceTexture = null ) {
  21351. super();
  21352. /**
  21353. * The external source texture.
  21354. *
  21355. * @type {?(WebGLTexture|GPUTexture)}
  21356. * @default null
  21357. */
  21358. this.sourceTexture = sourceTexture;
  21359. /**
  21360. * This flag can be used for type testing.
  21361. *
  21362. * @type {boolean}
  21363. * @readonly
  21364. * @default true
  21365. */
  21366. this.isExternalTexture = true;
  21367. }
  21368. copy( source ) {
  21369. super.copy( source );
  21370. this.sourceTexture = source.sourceTexture;
  21371. return this;
  21372. }
  21373. }
  21374. /**
  21375. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21376. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21377. * of the axes.
  21378. *
  21379. * ```js
  21380. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21381. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21382. * const cube = new THREE.Mesh( geometry, material );
  21383. * scene.add( cube );
  21384. * ```
  21385. *
  21386. * @augments BufferGeometry
  21387. * @demo scenes/geometry-browser.html#BoxGeometry
  21388. */
  21389. class BoxGeometry extends BufferGeometry {
  21390. /**
  21391. * Constructs a new box geometry.
  21392. *
  21393. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21394. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21395. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21396. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21397. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21398. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21399. */
  21400. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21401. super();
  21402. this.type = 'BoxGeometry';
  21403. /**
  21404. * Holds the constructor parameters that have been
  21405. * used to generate the geometry. Any modification
  21406. * after instantiation does not change the geometry.
  21407. *
  21408. * @type {Object}
  21409. */
  21410. this.parameters = {
  21411. width: width,
  21412. height: height,
  21413. depth: depth,
  21414. widthSegments: widthSegments,
  21415. heightSegments: heightSegments,
  21416. depthSegments: depthSegments
  21417. };
  21418. const scope = this;
  21419. // segments
  21420. widthSegments = Math.floor( widthSegments );
  21421. heightSegments = Math.floor( heightSegments );
  21422. depthSegments = Math.floor( depthSegments );
  21423. // buffers
  21424. const indices = [];
  21425. const vertices = [];
  21426. const normals = [];
  21427. const uvs = [];
  21428. // helper variables
  21429. let numberOfVertices = 0;
  21430. let groupStart = 0;
  21431. // build each side of the box geometry
  21432. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21433. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21434. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21435. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21436. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21437. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21438. // build geometry
  21439. this.setIndex( indices );
  21440. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21441. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21442. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21443. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21444. const segmentWidth = width / gridX;
  21445. const segmentHeight = height / gridY;
  21446. const widthHalf = width / 2;
  21447. const heightHalf = height / 2;
  21448. const depthHalf = depth / 2;
  21449. const gridX1 = gridX + 1;
  21450. const gridY1 = gridY + 1;
  21451. let vertexCounter = 0;
  21452. let groupCount = 0;
  21453. const vector = new Vector3();
  21454. // generate vertices, normals and uvs
  21455. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21456. const y = iy * segmentHeight - heightHalf;
  21457. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21458. const x = ix * segmentWidth - widthHalf;
  21459. // set values to correct vector component
  21460. vector[ u ] = x * udir;
  21461. vector[ v ] = y * vdir;
  21462. vector[ w ] = depthHalf;
  21463. // now apply vector to vertex buffer
  21464. vertices.push( vector.x, vector.y, vector.z );
  21465. // set values to correct vector component
  21466. vector[ u ] = 0;
  21467. vector[ v ] = 0;
  21468. vector[ w ] = depth > 0 ? 1 : -1;
  21469. // now apply vector to normal buffer
  21470. normals.push( vector.x, vector.y, vector.z );
  21471. // uvs
  21472. uvs.push( ix / gridX );
  21473. uvs.push( 1 - ( iy / gridY ) );
  21474. // counters
  21475. vertexCounter += 1;
  21476. }
  21477. }
  21478. // indices
  21479. // 1. you need three indices to draw a single face
  21480. // 2. a single segment consists of two faces
  21481. // 3. so we need to generate six (2*3) indices per segment
  21482. for ( let iy = 0; iy < gridY; iy ++ ) {
  21483. for ( let ix = 0; ix < gridX; ix ++ ) {
  21484. const a = numberOfVertices + ix + gridX1 * iy;
  21485. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21486. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21487. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21488. // faces
  21489. indices.push( a, b, d );
  21490. indices.push( b, c, d );
  21491. // increase counter
  21492. groupCount += 6;
  21493. }
  21494. }
  21495. // add a group to the geometry. this will ensure multi material support
  21496. scope.addGroup( groupStart, groupCount, materialIndex );
  21497. // calculate new start value for groups
  21498. groupStart += groupCount;
  21499. // update total number of vertices
  21500. numberOfVertices += vertexCounter;
  21501. }
  21502. }
  21503. copy( source ) {
  21504. super.copy( source );
  21505. this.parameters = Object.assign( {}, source.parameters );
  21506. return this;
  21507. }
  21508. /**
  21509. * Factory method for creating an instance of this class from the given
  21510. * JSON object.
  21511. *
  21512. * @param {Object} data - A JSON object representing the serialized geometry.
  21513. * @return {BoxGeometry} A new instance.
  21514. */
  21515. static fromJSON( data ) {
  21516. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21517. }
  21518. }
  21519. /**
  21520. * A geometry class for representing a capsule.
  21521. *
  21522. * ```js
  21523. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21524. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21525. * const capsule = new THREE.Mesh( geometry, material );
  21526. * scene.add( capsule );
  21527. * ```
  21528. *
  21529. * @augments BufferGeometry
  21530. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21531. */
  21532. class CapsuleGeometry extends BufferGeometry {
  21533. /**
  21534. * Constructs a new capsule geometry.
  21535. *
  21536. * @param {number} [radius=1] - Radius of the capsule.
  21537. * @param {number} [height=1] - Height of the middle section.
  21538. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21539. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21540. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21541. */
  21542. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21543. super();
  21544. this.type = 'CapsuleGeometry';
  21545. /**
  21546. * Holds the constructor parameters that have been
  21547. * used to generate the geometry. Any modification
  21548. * after instantiation does not change the geometry.
  21549. *
  21550. * @type {Object}
  21551. */
  21552. this.parameters = {
  21553. radius: radius,
  21554. height: height,
  21555. capSegments: capSegments,
  21556. radialSegments: radialSegments,
  21557. heightSegments: heightSegments,
  21558. };
  21559. height = Math.max( 0, height );
  21560. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21561. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21562. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21563. // buffers
  21564. const indices = [];
  21565. const vertices = [];
  21566. const normals = [];
  21567. const uvs = [];
  21568. // helper variables
  21569. const halfHeight = height / 2;
  21570. const capArcLength = ( Math.PI / 2 ) * radius;
  21571. const cylinderPartLength = height;
  21572. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21573. const numVerticalSegments = capSegments * 2 + heightSegments;
  21574. const verticesPerRow = radialSegments + 1;
  21575. const normal = new Vector3();
  21576. const vertex = new Vector3();
  21577. // generate vertices, normals, and uvs
  21578. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21579. let currentArcLength = 0;
  21580. let profileY = 0;
  21581. let profileRadius = 0;
  21582. let normalYComponent = 0;
  21583. if ( iy <= capSegments ) {
  21584. // bottom cap
  21585. const segmentProgress = iy / capSegments;
  21586. const angle = ( segmentProgress * Math.PI ) / 2;
  21587. profileY = - halfHeight - radius * Math.cos( angle );
  21588. profileRadius = radius * Math.sin( angle );
  21589. normalYComponent = - radius * Math.cos( angle );
  21590. currentArcLength = segmentProgress * capArcLength;
  21591. } else if ( iy <= capSegments + heightSegments ) {
  21592. // middle section
  21593. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21594. profileY = - halfHeight + segmentProgress * height;
  21595. profileRadius = radius;
  21596. normalYComponent = 0;
  21597. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21598. } else {
  21599. // top cap
  21600. const segmentProgress =
  21601. ( iy - capSegments - heightSegments ) / capSegments;
  21602. const angle = ( segmentProgress * Math.PI ) / 2;
  21603. profileY = halfHeight + radius * Math.sin( angle );
  21604. profileRadius = radius * Math.cos( angle );
  21605. normalYComponent = radius * Math.sin( angle );
  21606. currentArcLength =
  21607. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21608. }
  21609. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21610. // special case for the poles
  21611. let uOffset = 0;
  21612. if ( iy === 0 ) {
  21613. uOffset = 0.5 / radialSegments;
  21614. } else if ( iy === numVerticalSegments ) {
  21615. uOffset = -0.5 / radialSegments;
  21616. }
  21617. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21618. const u = ix / radialSegments;
  21619. const theta = u * Math.PI * 2;
  21620. const sinTheta = Math.sin( theta );
  21621. const cosTheta = Math.cos( theta );
  21622. // vertex
  21623. vertex.x = - profileRadius * cosTheta;
  21624. vertex.y = profileY;
  21625. vertex.z = profileRadius * sinTheta;
  21626. vertices.push( vertex.x, vertex.y, vertex.z );
  21627. // normal
  21628. normal.set(
  21629. - profileRadius * cosTheta,
  21630. normalYComponent,
  21631. profileRadius * sinTheta
  21632. );
  21633. normal.normalize();
  21634. normals.push( normal.x, normal.y, normal.z );
  21635. // uv
  21636. uvs.push( u + uOffset, v );
  21637. }
  21638. if ( iy > 0 ) {
  21639. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  21640. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  21641. const i1 = prevIndexRow + ix;
  21642. const i2 = prevIndexRow + ix + 1;
  21643. const i3 = iy * verticesPerRow + ix;
  21644. const i4 = iy * verticesPerRow + ix + 1;
  21645. indices.push( i1, i2, i3 );
  21646. indices.push( i2, i4, i3 );
  21647. }
  21648. }
  21649. }
  21650. // build geometry
  21651. this.setIndex( indices );
  21652. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21653. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21654. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21655. }
  21656. copy( source ) {
  21657. super.copy( source );
  21658. this.parameters = Object.assign( {}, source.parameters );
  21659. return this;
  21660. }
  21661. /**
  21662. * Factory method for creating an instance of this class from the given
  21663. * JSON object.
  21664. *
  21665. * @param {Object} data - A JSON object representing the serialized geometry.
  21666. * @return {CapsuleGeometry} A new instance.
  21667. */
  21668. static fromJSON( data ) {
  21669. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  21670. }
  21671. }
  21672. /**
  21673. * A simple shape of Euclidean geometry. It is constructed from a
  21674. * number of triangular segments that are oriented around a central point and
  21675. * extend as far out as a given radius. It is built counter-clockwise from a
  21676. * start angle and a given central angle. It can also be used to create
  21677. * regular polygons, where the number of segments determines the number of
  21678. * sides.
  21679. *
  21680. * ```js
  21681. * const geometry = new THREE.CircleGeometry( 5, 32 );
  21682. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21683. * const circle = new THREE.Mesh( geometry, material );
  21684. * scene.add( circle )
  21685. * ```
  21686. *
  21687. * @augments BufferGeometry
  21688. * @demo scenes/geometry-browser.html#CircleGeometry
  21689. */
  21690. class CircleGeometry extends BufferGeometry {
  21691. /**
  21692. * Constructs a new circle geometry.
  21693. *
  21694. * @param {number} [radius=1] - Radius of the circle.
  21695. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  21696. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  21697. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  21698. * of the circular sector in radians. The default value results in a complete circle.
  21699. */
  21700. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21701. super();
  21702. this.type = 'CircleGeometry';
  21703. /**
  21704. * Holds the constructor parameters that have been
  21705. * used to generate the geometry. Any modification
  21706. * after instantiation does not change the geometry.
  21707. *
  21708. * @type {Object}
  21709. */
  21710. this.parameters = {
  21711. radius: radius,
  21712. segments: segments,
  21713. thetaStart: thetaStart,
  21714. thetaLength: thetaLength
  21715. };
  21716. segments = Math.max( 3, segments );
  21717. // buffers
  21718. const indices = [];
  21719. const vertices = [];
  21720. const normals = [];
  21721. const uvs = [];
  21722. // helper variables
  21723. const vertex = new Vector3();
  21724. const uv = new Vector2();
  21725. // center point
  21726. vertices.push( 0, 0, 0 );
  21727. normals.push( 0, 0, 1 );
  21728. uvs.push( 0.5, 0.5 );
  21729. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21730. const segment = thetaStart + s / segments * thetaLength;
  21731. // vertex
  21732. vertex.x = radius * Math.cos( segment );
  21733. vertex.y = radius * Math.sin( segment );
  21734. vertices.push( vertex.x, vertex.y, vertex.z );
  21735. // normal
  21736. normals.push( 0, 0, 1 );
  21737. // uvs
  21738. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21739. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21740. uvs.push( uv.x, uv.y );
  21741. }
  21742. // indices
  21743. for ( let i = 1; i <= segments; i ++ ) {
  21744. indices.push( i, i + 1, 0 );
  21745. }
  21746. // build geometry
  21747. this.setIndex( indices );
  21748. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21749. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21750. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21751. }
  21752. copy( source ) {
  21753. super.copy( source );
  21754. this.parameters = Object.assign( {}, source.parameters );
  21755. return this;
  21756. }
  21757. /**
  21758. * Factory method for creating an instance of this class from the given
  21759. * JSON object.
  21760. *
  21761. * @param {Object} data - A JSON object representing the serialized geometry.
  21762. * @return {CircleGeometry} A new instance.
  21763. */
  21764. static fromJSON( data ) {
  21765. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21766. }
  21767. }
  21768. /**
  21769. * A geometry class for representing a cylinder.
  21770. *
  21771. * ```js
  21772. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  21773. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21774. * const cylinder = new THREE.Mesh( geometry, material );
  21775. * scene.add( cylinder );
  21776. * ```
  21777. *
  21778. * @augments BufferGeometry
  21779. * @demo scenes/geometry-browser.html#CylinderGeometry
  21780. */
  21781. class CylinderGeometry extends BufferGeometry {
  21782. /**
  21783. * Constructs a new cylinder geometry.
  21784. *
  21785. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  21786. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  21787. * @param {number} [height=1] - Height of the cylinder.
  21788. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  21789. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  21790. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  21791. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  21792. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  21793. * The default value results in a complete cylinder.
  21794. */
  21795. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21796. super();
  21797. this.type = 'CylinderGeometry';
  21798. /**
  21799. * Holds the constructor parameters that have been
  21800. * used to generate the geometry. Any modification
  21801. * after instantiation does not change the geometry.
  21802. *
  21803. * @type {Object}
  21804. */
  21805. this.parameters = {
  21806. radiusTop: radiusTop,
  21807. radiusBottom: radiusBottom,
  21808. height: height,
  21809. radialSegments: radialSegments,
  21810. heightSegments: heightSegments,
  21811. openEnded: openEnded,
  21812. thetaStart: thetaStart,
  21813. thetaLength: thetaLength
  21814. };
  21815. const scope = this;
  21816. radialSegments = Math.floor( radialSegments );
  21817. heightSegments = Math.floor( heightSegments );
  21818. // buffers
  21819. const indices = [];
  21820. const vertices = [];
  21821. const normals = [];
  21822. const uvs = [];
  21823. // helper variables
  21824. let index = 0;
  21825. const indexArray = [];
  21826. const halfHeight = height / 2;
  21827. let groupStart = 0;
  21828. // generate geometry
  21829. generateTorso();
  21830. if ( openEnded === false ) {
  21831. if ( radiusTop > 0 ) generateCap( true );
  21832. if ( radiusBottom > 0 ) generateCap( false );
  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. function generateTorso() {
  21840. const normal = new Vector3();
  21841. const vertex = new Vector3();
  21842. let groupCount = 0;
  21843. // this will be used to calculate the normal
  21844. const slope = ( radiusBottom - radiusTop ) / height;
  21845. // generate vertices, normals and uvs
  21846. for ( let y = 0; y <= heightSegments; y ++ ) {
  21847. const indexRow = [];
  21848. const v = y / heightSegments;
  21849. // calculate the radius of the current row
  21850. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21851. for ( let x = 0; x <= radialSegments; x ++ ) {
  21852. const u = x / radialSegments;
  21853. const theta = u * thetaLength + thetaStart;
  21854. const sinTheta = Math.sin( theta );
  21855. const cosTheta = Math.cos( theta );
  21856. // vertex
  21857. vertex.x = radius * sinTheta;
  21858. vertex.y = - v * height + halfHeight;
  21859. vertex.z = radius * cosTheta;
  21860. vertices.push( vertex.x, vertex.y, vertex.z );
  21861. // normal
  21862. normal.set( sinTheta, slope, cosTheta ).normalize();
  21863. normals.push( normal.x, normal.y, normal.z );
  21864. // uv
  21865. uvs.push( u, 1 - v );
  21866. // save index of vertex in respective row
  21867. indexRow.push( index ++ );
  21868. }
  21869. // now save vertices of the row in our index array
  21870. indexArray.push( indexRow );
  21871. }
  21872. // generate indices
  21873. for ( let x = 0; x < radialSegments; x ++ ) {
  21874. for ( let y = 0; y < heightSegments; y ++ ) {
  21875. // we use the index array to access the correct indices
  21876. const a = indexArray[ y ][ x ];
  21877. const b = indexArray[ y + 1 ][ x ];
  21878. const c = indexArray[ y + 1 ][ x + 1 ];
  21879. const d = indexArray[ y ][ x + 1 ];
  21880. // faces
  21881. if ( radiusTop > 0 || y !== 0 ) {
  21882. indices.push( a, b, d );
  21883. groupCount += 3;
  21884. }
  21885. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  21886. indices.push( b, c, d );
  21887. groupCount += 3;
  21888. }
  21889. }
  21890. }
  21891. // add a group to the geometry. this will ensure multi material support
  21892. scope.addGroup( groupStart, groupCount, 0 );
  21893. // calculate new start value for groups
  21894. groupStart += groupCount;
  21895. }
  21896. function generateCap( top ) {
  21897. // save the index of the first center vertex
  21898. const centerIndexStart = index;
  21899. const uv = new Vector2();
  21900. const vertex = new Vector3();
  21901. let groupCount = 0;
  21902. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21903. const sign = ( top === true ) ? 1 : -1;
  21904. // first we generate the center vertex data of the cap.
  21905. // because the geometry needs one set of uvs per face,
  21906. // we must generate a center vertex per face/segment
  21907. for ( let x = 1; x <= radialSegments; x ++ ) {
  21908. // vertex
  21909. vertices.push( 0, halfHeight * sign, 0 );
  21910. // normal
  21911. normals.push( 0, sign, 0 );
  21912. // uv
  21913. uvs.push( 0.5, 0.5 );
  21914. // increase index
  21915. index ++;
  21916. }
  21917. // save the index of the last center vertex
  21918. const centerIndexEnd = index;
  21919. // now we generate the surrounding vertices, normals and uvs
  21920. for ( let x = 0; x <= radialSegments; x ++ ) {
  21921. const u = x / radialSegments;
  21922. const theta = u * thetaLength + thetaStart;
  21923. const cosTheta = Math.cos( theta );
  21924. const sinTheta = Math.sin( theta );
  21925. // vertex
  21926. vertex.x = radius * sinTheta;
  21927. vertex.y = halfHeight * sign;
  21928. vertex.z = radius * cosTheta;
  21929. vertices.push( vertex.x, vertex.y, vertex.z );
  21930. // normal
  21931. normals.push( 0, sign, 0 );
  21932. // uv
  21933. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21934. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21935. uvs.push( uv.x, uv.y );
  21936. // increase index
  21937. index ++;
  21938. }
  21939. // generate indices
  21940. for ( let x = 0; x < radialSegments; x ++ ) {
  21941. const c = centerIndexStart + x;
  21942. const i = centerIndexEnd + x;
  21943. if ( top === true ) {
  21944. // face top
  21945. indices.push( i, i + 1, c );
  21946. } else {
  21947. // face bottom
  21948. indices.push( i + 1, i, c );
  21949. }
  21950. groupCount += 3;
  21951. }
  21952. // add a group to the geometry. this will ensure multi material support
  21953. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21954. // calculate new start value for groups
  21955. groupStart += groupCount;
  21956. }
  21957. }
  21958. copy( source ) {
  21959. super.copy( source );
  21960. this.parameters = Object.assign( {}, source.parameters );
  21961. return this;
  21962. }
  21963. /**
  21964. * Factory method for creating an instance of this class from the given
  21965. * JSON object.
  21966. *
  21967. * @param {Object} data - A JSON object representing the serialized geometry.
  21968. * @return {CylinderGeometry} A new instance.
  21969. */
  21970. static fromJSON( data ) {
  21971. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21972. }
  21973. }
  21974. /**
  21975. * A geometry class for representing a cone.
  21976. *
  21977. * ```js
  21978. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  21979. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21980. * const cone = new THREE.Mesh(geometry, material );
  21981. * scene.add( cone );
  21982. * ```
  21983. *
  21984. * @augments CylinderGeometry
  21985. * @demo scenes/geometry-browser.html#ConeGeometry
  21986. */
  21987. class ConeGeometry extends CylinderGeometry {
  21988. /**
  21989. * Constructs a new cone geometry.
  21990. *
  21991. * @param {number} [radius=1] - Radius of the cone base.
  21992. * @param {number} [height=1] - Height of the cone.
  21993. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  21994. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  21995. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  21996. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  21997. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  21998. * The default value results in a complete cone.
  21999. */
  22000. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22001. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22002. this.type = 'ConeGeometry';
  22003. /**
  22004. * Holds the constructor parameters that have been
  22005. * used to generate the geometry. Any modification
  22006. * after instantiation does not change the geometry.
  22007. *
  22008. * @type {Object}
  22009. */
  22010. this.parameters = {
  22011. radius: radius,
  22012. height: height,
  22013. radialSegments: radialSegments,
  22014. heightSegments: heightSegments,
  22015. openEnded: openEnded,
  22016. thetaStart: thetaStart,
  22017. thetaLength: thetaLength
  22018. };
  22019. }
  22020. /**
  22021. * Factory method for creating an instance of this class from the given
  22022. * JSON object.
  22023. *
  22024. * @param {Object} data - A JSON object representing the serialized geometry.
  22025. * @return {ConeGeometry} A new instance.
  22026. */
  22027. static fromJSON( data ) {
  22028. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22029. }
  22030. }
  22031. /**
  22032. * A polyhedron is a solid in three dimensions with flat faces. This class
  22033. * will take an array of vertices, project them onto a sphere, and then
  22034. * divide them up to the desired level of detail.
  22035. *
  22036. * @augments BufferGeometry
  22037. */
  22038. class PolyhedronGeometry extends BufferGeometry {
  22039. /**
  22040. * Constructs a new polyhedron geometry.
  22041. *
  22042. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22043. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22044. * @param {number} [radius=1] - The radius of the shape.
  22045. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22046. */
  22047. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22048. super();
  22049. this.type = 'PolyhedronGeometry';
  22050. /**
  22051. * Holds the constructor parameters that have been
  22052. * used to generate the geometry. Any modification
  22053. * after instantiation does not change the geometry.
  22054. *
  22055. * @type {Object}
  22056. */
  22057. this.parameters = {
  22058. vertices: vertices,
  22059. indices: indices,
  22060. radius: radius,
  22061. detail: detail
  22062. };
  22063. // default buffer data
  22064. const vertexBuffer = [];
  22065. const uvBuffer = [];
  22066. // the subdivision creates the vertex buffer data
  22067. subdivide( detail );
  22068. // all vertices should lie on a conceptual sphere with a given radius
  22069. applyRadius( radius );
  22070. // finally, create the uv data
  22071. generateUVs();
  22072. // build non-indexed geometry
  22073. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22074. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22075. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22076. if ( detail === 0 ) {
  22077. this.computeVertexNormals(); // flat normals
  22078. } else {
  22079. this.normalizeNormals(); // smooth normals
  22080. }
  22081. // helper functions
  22082. function subdivide( detail ) {
  22083. const a = new Vector3();
  22084. const b = new Vector3();
  22085. const c = new Vector3();
  22086. // iterate over all faces and apply a subdivision with the given detail value
  22087. for ( let i = 0; i < indices.length; i += 3 ) {
  22088. // get the vertices of the face
  22089. getVertexByIndex( indices[ i + 0 ], a );
  22090. getVertexByIndex( indices[ i + 1 ], b );
  22091. getVertexByIndex( indices[ i + 2 ], c );
  22092. // perform subdivision
  22093. subdivideFace( a, b, c, detail );
  22094. }
  22095. }
  22096. function subdivideFace( a, b, c, detail ) {
  22097. const cols = detail + 1;
  22098. // we use this multidimensional array as a data structure for creating the subdivision
  22099. const v = [];
  22100. // construct all of the vertices for this subdivision
  22101. for ( let i = 0; i <= cols; i ++ ) {
  22102. v[ i ] = [];
  22103. const aj = a.clone().lerp( c, i / cols );
  22104. const bj = b.clone().lerp( c, i / cols );
  22105. const rows = cols - i;
  22106. for ( let j = 0; j <= rows; j ++ ) {
  22107. if ( j === 0 && i === cols ) {
  22108. v[ i ][ j ] = aj;
  22109. } else {
  22110. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22111. }
  22112. }
  22113. }
  22114. // construct all of the faces
  22115. for ( let i = 0; i < cols; i ++ ) {
  22116. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22117. const k = Math.floor( j / 2 );
  22118. if ( j % 2 === 0 ) {
  22119. pushVertex( v[ i ][ k + 1 ] );
  22120. pushVertex( v[ i + 1 ][ k ] );
  22121. pushVertex( v[ i ][ k ] );
  22122. } else {
  22123. pushVertex( v[ i ][ k + 1 ] );
  22124. pushVertex( v[ i + 1 ][ k + 1 ] );
  22125. pushVertex( v[ i + 1 ][ k ] );
  22126. }
  22127. }
  22128. }
  22129. }
  22130. function applyRadius( radius ) {
  22131. const vertex = new Vector3();
  22132. // iterate over the entire buffer and apply the radius to each vertex
  22133. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22134. vertex.x = vertexBuffer[ i + 0 ];
  22135. vertex.y = vertexBuffer[ i + 1 ];
  22136. vertex.z = vertexBuffer[ i + 2 ];
  22137. vertex.normalize().multiplyScalar( radius );
  22138. vertexBuffer[ i + 0 ] = vertex.x;
  22139. vertexBuffer[ i + 1 ] = vertex.y;
  22140. vertexBuffer[ i + 2 ] = vertex.z;
  22141. }
  22142. }
  22143. function generateUVs() {
  22144. const vertex = new Vector3();
  22145. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22146. vertex.x = vertexBuffer[ i + 0 ];
  22147. vertex.y = vertexBuffer[ i + 1 ];
  22148. vertex.z = vertexBuffer[ i + 2 ];
  22149. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22150. const v = inclination( vertex ) / Math.PI + 0.5;
  22151. uvBuffer.push( u, 1 - v );
  22152. }
  22153. correctUVs();
  22154. correctSeam();
  22155. }
  22156. function correctSeam() {
  22157. // handle case when face straddles the seam, see #3269
  22158. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22159. // uv data of a single face
  22160. const x0 = uvBuffer[ i + 0 ];
  22161. const x1 = uvBuffer[ i + 2 ];
  22162. const x2 = uvBuffer[ i + 4 ];
  22163. const max = Math.max( x0, x1, x2 );
  22164. const min = Math.min( x0, x1, x2 );
  22165. // 0.9 is somewhat arbitrary
  22166. if ( max > 0.9 && min < 0.1 ) {
  22167. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22168. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22169. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22170. }
  22171. }
  22172. }
  22173. function pushVertex( vertex ) {
  22174. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22175. }
  22176. function getVertexByIndex( index, vertex ) {
  22177. const stride = index * 3;
  22178. vertex.x = vertices[ stride + 0 ];
  22179. vertex.y = vertices[ stride + 1 ];
  22180. vertex.z = vertices[ stride + 2 ];
  22181. }
  22182. function correctUVs() {
  22183. const a = new Vector3();
  22184. const b = new Vector3();
  22185. const c = new Vector3();
  22186. const centroid = new Vector3();
  22187. const uvA = new Vector2();
  22188. const uvB = new Vector2();
  22189. const uvC = new Vector2();
  22190. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22191. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22192. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22193. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22194. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22195. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22196. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22197. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22198. const azi = azimuth( centroid );
  22199. correctUV( uvA, j + 0, a, azi );
  22200. correctUV( uvB, j + 2, b, azi );
  22201. correctUV( uvC, j + 4, c, azi );
  22202. }
  22203. }
  22204. function correctUV( uv, stride, vector, azimuth ) {
  22205. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22206. uvBuffer[ stride ] = uv.x - 1;
  22207. }
  22208. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22209. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22210. }
  22211. }
  22212. // Angle around the Y axis, counter-clockwise when looking from above.
  22213. function azimuth( vector ) {
  22214. return Math.atan2( vector.z, - vector.x );
  22215. }
  22216. // Angle above the XZ plane.
  22217. function inclination( vector ) {
  22218. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22219. }
  22220. }
  22221. copy( source ) {
  22222. super.copy( source );
  22223. this.parameters = Object.assign( {}, source.parameters );
  22224. return this;
  22225. }
  22226. /**
  22227. * Factory method for creating an instance of this class from the given
  22228. * JSON object.
  22229. *
  22230. * @param {Object} data - A JSON object representing the serialized geometry.
  22231. * @return {PolyhedronGeometry} A new instance.
  22232. */
  22233. static fromJSON( data ) {
  22234. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22235. }
  22236. }
  22237. /**
  22238. * A geometry class for representing a dodecahedron.
  22239. *
  22240. * ```js
  22241. * const geometry = new THREE.DodecahedronGeometry();
  22242. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22243. * const dodecahedron = new THREE.Mesh( geometry, material );
  22244. * scene.add( dodecahedron );
  22245. * ```
  22246. *
  22247. * @augments PolyhedronGeometry
  22248. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22249. */
  22250. class DodecahedronGeometry extends PolyhedronGeometry {
  22251. /**
  22252. * Constructs a new dodecahedron geometry.
  22253. *
  22254. * @param {number} [radius=1] - Radius of the dodecahedron.
  22255. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22256. */
  22257. constructor( radius = 1, detail = 0 ) {
  22258. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22259. const r = 1 / t;
  22260. const vertices = [
  22261. // (±1, ±1, ±1)
  22262. -1, -1, -1, -1, -1, 1,
  22263. -1, 1, -1, -1, 1, 1,
  22264. 1, -1, -1, 1, -1, 1,
  22265. 1, 1, -1, 1, 1, 1,
  22266. // (0, ±1/φ, ±φ)
  22267. 0, - r, - t, 0, - r, t,
  22268. 0, r, - t, 0, r, t,
  22269. // (±1/φ, ±φ, 0)
  22270. - r, - t, 0, - r, t, 0,
  22271. r, - t, 0, r, t, 0,
  22272. // (±φ, 0, ±1/φ)
  22273. - t, 0, - r, t, 0, - r,
  22274. - t, 0, r, t, 0, r
  22275. ];
  22276. const indices = [
  22277. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22278. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22279. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22280. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22281. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22282. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22283. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22284. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22285. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22286. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22287. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22288. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22289. ];
  22290. super( vertices, indices, radius, detail );
  22291. this.type = 'DodecahedronGeometry';
  22292. /**
  22293. * Holds the constructor parameters that have been
  22294. * used to generate the geometry. Any modification
  22295. * after instantiation does not change the geometry.
  22296. *
  22297. * @type {Object}
  22298. */
  22299. this.parameters = {
  22300. radius: radius,
  22301. detail: detail
  22302. };
  22303. }
  22304. /**
  22305. * Factory method for creating an instance of this class from the given
  22306. * JSON object.
  22307. *
  22308. * @param {Object} data - A JSON object representing the serialized geometry.
  22309. * @return {DodecahedronGeometry} A new instance.
  22310. */
  22311. static fromJSON( data ) {
  22312. return new DodecahedronGeometry( data.radius, data.detail );
  22313. }
  22314. }
  22315. const _v0$1 = /*@__PURE__*/ new Vector3();
  22316. const _v1$1 = /*@__PURE__*/ new Vector3();
  22317. const _normal = /*@__PURE__*/ new Vector3();
  22318. const _triangle = /*@__PURE__*/ new Triangle();
  22319. /**
  22320. * Can be used as a helper object to view the edges of a geometry.
  22321. *
  22322. * ```js
  22323. * const geometry = new THREE.BoxGeometry();
  22324. * const edges = new THREE.EdgesGeometry( geometry );
  22325. * const line = new THREE.LineSegments( edges );
  22326. * scene.add( line );
  22327. * ```
  22328. *
  22329. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22330. *
  22331. * @augments BufferGeometry
  22332. */
  22333. class EdgesGeometry extends BufferGeometry {
  22334. /**
  22335. * Constructs a new edges geometry.
  22336. *
  22337. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22338. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22339. * between the face normals of the adjoining faces exceeds this value.
  22340. */
  22341. constructor( geometry = null, thresholdAngle = 1 ) {
  22342. super();
  22343. this.type = 'EdgesGeometry';
  22344. /**
  22345. * Holds the constructor parameters that have been
  22346. * used to generate the geometry. Any modification
  22347. * after instantiation does not change the geometry.
  22348. *
  22349. * @type {Object}
  22350. */
  22351. this.parameters = {
  22352. geometry: geometry,
  22353. thresholdAngle: thresholdAngle
  22354. };
  22355. if ( geometry !== null ) {
  22356. const precisionPoints = 4;
  22357. const precision = Math.pow( 10, precisionPoints );
  22358. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22359. const indexAttr = geometry.getIndex();
  22360. const positionAttr = geometry.getAttribute( 'position' );
  22361. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22362. const indexArr = [ 0, 0, 0 ];
  22363. const vertKeys = [ 'a', 'b', 'c' ];
  22364. const hashes = new Array( 3 );
  22365. const edgeData = {};
  22366. const vertices = [];
  22367. for ( let i = 0; i < indexCount; i += 3 ) {
  22368. if ( indexAttr ) {
  22369. indexArr[ 0 ] = indexAttr.getX( i );
  22370. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22371. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22372. } else {
  22373. indexArr[ 0 ] = i;
  22374. indexArr[ 1 ] = i + 1;
  22375. indexArr[ 2 ] = i + 2;
  22376. }
  22377. const { a, b, c } = _triangle;
  22378. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22379. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22380. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22381. _triangle.getNormal( _normal );
  22382. // create hashes for the edge from the vertices
  22383. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22384. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22385. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22386. // skip degenerate triangles
  22387. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22388. continue;
  22389. }
  22390. // iterate over every edge
  22391. for ( let j = 0; j < 3; j ++ ) {
  22392. // get the first and next vertex making up the edge
  22393. const jNext = ( j + 1 ) % 3;
  22394. const vecHash0 = hashes[ j ];
  22395. const vecHash1 = hashes[ jNext ];
  22396. const v0 = _triangle[ vertKeys[ j ] ];
  22397. const v1 = _triangle[ vertKeys[ jNext ] ];
  22398. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22399. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22400. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22401. // if we found a sibling edge add it into the vertex array if
  22402. // it meets the angle threshold and delete the edge from the map.
  22403. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22404. vertices.push( v0.x, v0.y, v0.z );
  22405. vertices.push( v1.x, v1.y, v1.z );
  22406. }
  22407. edgeData[ reverseHash ] = null;
  22408. } else if ( ! ( hash in edgeData ) ) {
  22409. // if we've already got an edge here then skip adding a new one
  22410. edgeData[ hash ] = {
  22411. index0: indexArr[ j ],
  22412. index1: indexArr[ jNext ],
  22413. normal: _normal.clone(),
  22414. };
  22415. }
  22416. }
  22417. }
  22418. // iterate over all remaining, unmatched edges and add them to the vertex array
  22419. for ( const key in edgeData ) {
  22420. if ( edgeData[ key ] ) {
  22421. const { index0, index1 } = edgeData[ key ];
  22422. _v0$1.fromBufferAttribute( positionAttr, index0 );
  22423. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22424. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  22425. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22426. }
  22427. }
  22428. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22429. }
  22430. }
  22431. copy( source ) {
  22432. super.copy( source );
  22433. this.parameters = Object.assign( {}, source.parameters );
  22434. return this;
  22435. }
  22436. }
  22437. /**
  22438. * An abstract base class for creating an analytic curve object that contains methods
  22439. * for interpolation.
  22440. *
  22441. * @abstract
  22442. */
  22443. class Curve {
  22444. /**
  22445. * Constructs a new curve.
  22446. */
  22447. constructor() {
  22448. /**
  22449. * The type property is used for detecting the object type
  22450. * in context of serialization/deserialization.
  22451. *
  22452. * @type {string}
  22453. * @readonly
  22454. */
  22455. this.type = 'Curve';
  22456. /**
  22457. * This value determines the amount of divisions when calculating the
  22458. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22459. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22460. * recommended to increase the value of this property if the curve is very large.
  22461. *
  22462. * @type {number}
  22463. * @default 200
  22464. */
  22465. this.arcLengthDivisions = 200;
  22466. /**
  22467. * Must be set to `true` if the curve parameters have changed.
  22468. *
  22469. * @type {boolean}
  22470. * @default false
  22471. */
  22472. this.needsUpdate = false;
  22473. /**
  22474. * An internal cache that holds precomputed curve length values.
  22475. *
  22476. * @private
  22477. * @type {?Array<number>}
  22478. * @default null
  22479. */
  22480. this.cacheArcLengths = null;
  22481. }
  22482. /**
  22483. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22484. * for the given interpolation factor.
  22485. *
  22486. * @abstract
  22487. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22488. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22489. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22490. */
  22491. getPoint( /* t, optionalTarget */ ) {
  22492. warn( 'Curve: .getPoint() not implemented.' );
  22493. }
  22494. /**
  22495. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22496. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22497. * of the curve which equidistant samples.
  22498. *
  22499. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22500. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22501. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22502. */
  22503. getPointAt( u, optionalTarget ) {
  22504. const t = this.getUtoTmapping( u );
  22505. return this.getPoint( t, optionalTarget );
  22506. }
  22507. /**
  22508. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22509. * the curve shape.
  22510. *
  22511. * @param {number} [divisions=5] - The number of divisions.
  22512. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22513. */
  22514. getPoints( divisions = 5 ) {
  22515. const points = [];
  22516. for ( let d = 0; d <= divisions; d ++ ) {
  22517. points.push( this.getPoint( d / divisions ) );
  22518. }
  22519. return points;
  22520. }
  22521. // Get sequence of points using getPointAt( u )
  22522. /**
  22523. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22524. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22525. * curve.
  22526. *
  22527. * @param {number} [divisions=5] - The number of divisions.
  22528. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22529. */
  22530. getSpacedPoints( divisions = 5 ) {
  22531. const points = [];
  22532. for ( let d = 0; d <= divisions; d ++ ) {
  22533. points.push( this.getPointAt( d / divisions ) );
  22534. }
  22535. return points;
  22536. }
  22537. /**
  22538. * Returns the total arc length of the curve.
  22539. *
  22540. * @return {number} The length of the curve.
  22541. */
  22542. getLength() {
  22543. const lengths = this.getLengths();
  22544. return lengths[ lengths.length - 1 ];
  22545. }
  22546. /**
  22547. * Returns an array of cumulative segment lengths of the curve.
  22548. *
  22549. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22550. * @return {Array<number>} An array holding the cumulative segment lengths.
  22551. */
  22552. getLengths( divisions = this.arcLengthDivisions ) {
  22553. if ( this.cacheArcLengths &&
  22554. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22555. ! this.needsUpdate ) {
  22556. return this.cacheArcLengths;
  22557. }
  22558. this.needsUpdate = false;
  22559. const cache = [];
  22560. let current, last = this.getPoint( 0 );
  22561. let sum = 0;
  22562. cache.push( 0 );
  22563. for ( let p = 1; p <= divisions; p ++ ) {
  22564. current = this.getPoint( p / divisions );
  22565. sum += current.distanceTo( last );
  22566. cache.push( sum );
  22567. last = current;
  22568. }
  22569. this.cacheArcLengths = cache;
  22570. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22571. }
  22572. /**
  22573. * Update the cumulative segment distance cache. The method must be called
  22574. * every time curve parameters are changed. If an updated curve is part of a
  22575. * composed curve like {@link CurvePath}, this method must be called on the
  22576. * composed curve, too.
  22577. */
  22578. updateArcLengths() {
  22579. this.needsUpdate = true;
  22580. this.getLengths();
  22581. }
  22582. /**
  22583. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22584. * interpolation factor in the same range that can be ued to sample equidistant points
  22585. * from a curve.
  22586. *
  22587. * @param {number} u - The interpolation factor.
  22588. * @param {?number} distance - An optional distance on the curve.
  22589. * @return {number} The updated interpolation factor.
  22590. */
  22591. getUtoTmapping( u, distance = null ) {
  22592. const arcLengths = this.getLengths();
  22593. let i = 0;
  22594. const il = arcLengths.length;
  22595. let targetArcLength; // The targeted u distance value to get
  22596. if ( distance ) {
  22597. targetArcLength = distance;
  22598. } else {
  22599. targetArcLength = u * arcLengths[ il - 1 ];
  22600. }
  22601. // binary search for the index with largest value smaller than target u distance
  22602. let low = 0, high = il - 1, comparison;
  22603. while ( low <= high ) {
  22604. 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
  22605. comparison = arcLengths[ i ] - targetArcLength;
  22606. if ( comparison < 0 ) {
  22607. low = i + 1;
  22608. } else if ( comparison > 0 ) {
  22609. high = i - 1;
  22610. } else {
  22611. high = i;
  22612. break;
  22613. // DONE
  22614. }
  22615. }
  22616. i = high;
  22617. if ( arcLengths[ i ] === targetArcLength ) {
  22618. return i / ( il - 1 );
  22619. }
  22620. // we could get finer grain at lengths, or use simple interpolation between two points
  22621. const lengthBefore = arcLengths[ i ];
  22622. const lengthAfter = arcLengths[ i + 1 ];
  22623. const segmentLength = lengthAfter - lengthBefore;
  22624. // determine where we are between the 'before' and 'after' points
  22625. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22626. // add that fractional amount to t
  22627. const t = ( i + segmentFraction ) / ( il - 1 );
  22628. return t;
  22629. }
  22630. /**
  22631. * Returns a unit vector tangent for the given interpolation factor.
  22632. * If the derived curve does not implement its tangent derivation,
  22633. * two points a small delta apart will be used to find its gradient
  22634. * which seems to give a reasonable approximation.
  22635. *
  22636. * @param {number} t - The interpolation factor.
  22637. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22638. * @return {(Vector2|Vector3)} The tangent vector.
  22639. */
  22640. getTangent( t, optionalTarget ) {
  22641. const delta = 0.0001;
  22642. let t1 = t - delta;
  22643. let t2 = t + delta;
  22644. // Capping in case of danger
  22645. if ( t1 < 0 ) t1 = 0;
  22646. if ( t2 > 1 ) t2 = 1;
  22647. const pt1 = this.getPoint( t1 );
  22648. const pt2 = this.getPoint( t2 );
  22649. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22650. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22651. return tangent;
  22652. }
  22653. /**
  22654. * Same as {@link Curve#getTangent} but with equidistant samples.
  22655. *
  22656. * @param {number} u - The interpolation factor.
  22657. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22658. * @return {(Vector2|Vector3)} The tangent vector.
  22659. * @see {@link Curve#getPointAt}
  22660. */
  22661. getTangentAt( u, optionalTarget ) {
  22662. const t = this.getUtoTmapping( u );
  22663. return this.getTangent( t, optionalTarget );
  22664. }
  22665. /**
  22666. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  22667. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  22668. *
  22669. * @param {number} segments - The number of segments.
  22670. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  22671. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  22672. */
  22673. computeFrenetFrames( segments, closed = false ) {
  22674. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22675. const normal = new Vector3();
  22676. const tangents = [];
  22677. const normals = [];
  22678. const binormals = [];
  22679. const vec = new Vector3();
  22680. const mat = new Matrix4();
  22681. // compute the tangent vectors for each segment on the curve
  22682. for ( let i = 0; i <= segments; i ++ ) {
  22683. const u = i / segments;
  22684. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  22685. }
  22686. // select an initial normal vector perpendicular to the first tangent vector,
  22687. // and in the direction of the minimum tangent xyz component
  22688. normals[ 0 ] = new Vector3();
  22689. binormals[ 0 ] = new Vector3();
  22690. let min = Number.MAX_VALUE;
  22691. const tx = Math.abs( tangents[ 0 ].x );
  22692. const ty = Math.abs( tangents[ 0 ].y );
  22693. const tz = Math.abs( tangents[ 0 ].z );
  22694. if ( tx <= min ) {
  22695. min = tx;
  22696. normal.set( 1, 0, 0 );
  22697. }
  22698. if ( ty <= min ) {
  22699. min = ty;
  22700. normal.set( 0, 1, 0 );
  22701. }
  22702. if ( tz <= min ) {
  22703. normal.set( 0, 0, 1 );
  22704. }
  22705. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  22706. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  22707. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  22708. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22709. for ( let i = 1; i <= segments; i ++ ) {
  22710. normals[ i ] = normals[ i - 1 ].clone();
  22711. binormals[ i ] = binormals[ i - 1 ].clone();
  22712. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  22713. if ( vec.length() > Number.EPSILON ) {
  22714. vec.normalize();
  22715. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  22716. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  22717. }
  22718. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22719. }
  22720. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22721. if ( closed === true ) {
  22722. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  22723. theta /= segments;
  22724. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  22725. theta = - theta;
  22726. }
  22727. for ( let i = 1; i <= segments; i ++ ) {
  22728. // twist a little...
  22729. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  22730. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  22731. }
  22732. }
  22733. return {
  22734. tangents: tangents,
  22735. normals: normals,
  22736. binormals: binormals
  22737. };
  22738. }
  22739. /**
  22740. * Returns a new curve with copied values from this instance.
  22741. *
  22742. * @return {Curve} A clone of this instance.
  22743. */
  22744. clone() {
  22745. return new this.constructor().copy( this );
  22746. }
  22747. /**
  22748. * Copies the values of the given curve to this instance.
  22749. *
  22750. * @param {Curve} source - The curve to copy.
  22751. * @return {Curve} A reference to this curve.
  22752. */
  22753. copy( source ) {
  22754. this.arcLengthDivisions = source.arcLengthDivisions;
  22755. return this;
  22756. }
  22757. /**
  22758. * Serializes the curve into JSON.
  22759. *
  22760. * @return {Object} A JSON object representing the serialized curve.
  22761. * @see {@link ObjectLoader#parse}
  22762. */
  22763. toJSON() {
  22764. const data = {
  22765. metadata: {
  22766. version: 4.7,
  22767. type: 'Curve',
  22768. generator: 'Curve.toJSON'
  22769. }
  22770. };
  22771. data.arcLengthDivisions = this.arcLengthDivisions;
  22772. data.type = this.type;
  22773. return data;
  22774. }
  22775. /**
  22776. * Deserializes the curve from the given JSON.
  22777. *
  22778. * @param {Object} json - The JSON holding the serialized curve.
  22779. * @return {Curve} A reference to this curve.
  22780. */
  22781. fromJSON( json ) {
  22782. this.arcLengthDivisions = json.arcLengthDivisions;
  22783. return this;
  22784. }
  22785. }
  22786. /**
  22787. * A curve representing an ellipse.
  22788. *
  22789. * ```js
  22790. * const curve = new THREE.EllipseCurve(
  22791. * 0, 0,
  22792. * 10, 10,
  22793. * 0, 2 * Math.PI,
  22794. * false,
  22795. * 0
  22796. * );
  22797. *
  22798. * const points = curve.getPoints( 50 );
  22799. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  22800. *
  22801. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  22802. *
  22803. * // Create the final object to add to the scene
  22804. * const ellipse = new THREE.Line( geometry, material );
  22805. * ```
  22806. *
  22807. * @augments Curve
  22808. */
  22809. class EllipseCurve extends Curve {
  22810. /**
  22811. * Constructs a new ellipse curve.
  22812. *
  22813. * @param {number} [aX=0] - The X center of the ellipse.
  22814. * @param {number} [aY=0] - The Y center of the ellipse.
  22815. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  22816. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  22817. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22818. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22819. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22820. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22821. */
  22822. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  22823. super();
  22824. /**
  22825. * This flag can be used for type testing.
  22826. *
  22827. * @type {boolean}
  22828. * @readonly
  22829. * @default true
  22830. */
  22831. this.isEllipseCurve = true;
  22832. this.type = 'EllipseCurve';
  22833. /**
  22834. * The X center of the ellipse.
  22835. *
  22836. * @type {number}
  22837. * @default 0
  22838. */
  22839. this.aX = aX;
  22840. /**
  22841. * The Y center of the ellipse.
  22842. *
  22843. * @type {number}
  22844. * @default 0
  22845. */
  22846. this.aY = aY;
  22847. /**
  22848. * The radius of the ellipse in the x direction.
  22849. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  22850. *
  22851. * @type {number}
  22852. * @default 1
  22853. */
  22854. this.xRadius = xRadius;
  22855. /**
  22856. * The radius of the ellipse in the y direction.
  22857. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  22858. *
  22859. * @type {number}
  22860. * @default 1
  22861. */
  22862. this.yRadius = yRadius;
  22863. /**
  22864. * The start angle of the curve in radians starting from the positive X axis.
  22865. *
  22866. * @type {number}
  22867. * @default 0
  22868. */
  22869. this.aStartAngle = aStartAngle;
  22870. /**
  22871. * The end angle of the curve in radians starting from the positive X axis.
  22872. *
  22873. * @type {number}
  22874. * @default Math.PI*2
  22875. */
  22876. this.aEndAngle = aEndAngle;
  22877. /**
  22878. * Whether the ellipse is drawn clockwise or not.
  22879. *
  22880. * @type {boolean}
  22881. * @default false
  22882. */
  22883. this.aClockwise = aClockwise;
  22884. /**
  22885. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  22886. *
  22887. * @type {number}
  22888. * @default 0
  22889. */
  22890. this.aRotation = aRotation;
  22891. }
  22892. /**
  22893. * Returns a point on the curve.
  22894. *
  22895. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22896. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  22897. * @return {Vector2} The position on the curve.
  22898. */
  22899. getPoint( t, optionalTarget = new Vector2() ) {
  22900. const point = optionalTarget;
  22901. const twoPi = Math.PI * 2;
  22902. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22903. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  22904. // ensures that deltaAngle is 0 .. 2 PI
  22905. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  22906. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  22907. if ( deltaAngle < Number.EPSILON ) {
  22908. if ( samePoints ) {
  22909. deltaAngle = 0;
  22910. } else {
  22911. deltaAngle = twoPi;
  22912. }
  22913. }
  22914. if ( this.aClockwise === true && ! samePoints ) {
  22915. if ( deltaAngle === twoPi ) {
  22916. deltaAngle = - twoPi;
  22917. } else {
  22918. deltaAngle = deltaAngle - twoPi;
  22919. }
  22920. }
  22921. const angle = this.aStartAngle + t * deltaAngle;
  22922. let x = this.aX + this.xRadius * Math.cos( angle );
  22923. let y = this.aY + this.yRadius * Math.sin( angle );
  22924. if ( this.aRotation !== 0 ) {
  22925. const cos = Math.cos( this.aRotation );
  22926. const sin = Math.sin( this.aRotation );
  22927. const tx = x - this.aX;
  22928. const ty = y - this.aY;
  22929. // Rotate the point about the center of the ellipse.
  22930. x = tx * cos - ty * sin + this.aX;
  22931. y = tx * sin + ty * cos + this.aY;
  22932. }
  22933. return point.set( x, y );
  22934. }
  22935. copy( source ) {
  22936. super.copy( source );
  22937. this.aX = source.aX;
  22938. this.aY = source.aY;
  22939. this.xRadius = source.xRadius;
  22940. this.yRadius = source.yRadius;
  22941. this.aStartAngle = source.aStartAngle;
  22942. this.aEndAngle = source.aEndAngle;
  22943. this.aClockwise = source.aClockwise;
  22944. this.aRotation = source.aRotation;
  22945. return this;
  22946. }
  22947. toJSON() {
  22948. const data = super.toJSON();
  22949. data.aX = this.aX;
  22950. data.aY = this.aY;
  22951. data.xRadius = this.xRadius;
  22952. data.yRadius = this.yRadius;
  22953. data.aStartAngle = this.aStartAngle;
  22954. data.aEndAngle = this.aEndAngle;
  22955. data.aClockwise = this.aClockwise;
  22956. data.aRotation = this.aRotation;
  22957. return data;
  22958. }
  22959. fromJSON( json ) {
  22960. super.fromJSON( json );
  22961. this.aX = json.aX;
  22962. this.aY = json.aY;
  22963. this.xRadius = json.xRadius;
  22964. this.yRadius = json.yRadius;
  22965. this.aStartAngle = json.aStartAngle;
  22966. this.aEndAngle = json.aEndAngle;
  22967. this.aClockwise = json.aClockwise;
  22968. this.aRotation = json.aRotation;
  22969. return this;
  22970. }
  22971. }
  22972. /**
  22973. * A curve representing an arc.
  22974. *
  22975. * @augments EllipseCurve
  22976. */
  22977. class ArcCurve extends EllipseCurve {
  22978. /**
  22979. * Constructs a new arc curve.
  22980. *
  22981. * @param {number} [aX=0] - The X center of the ellipse.
  22982. * @param {number} [aY=0] - The Y center of the ellipse.
  22983. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  22984. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  22985. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  22986. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  22987. */
  22988. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  22989. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  22990. /**
  22991. * This flag can be used for type testing.
  22992. *
  22993. * @type {boolean}
  22994. * @readonly
  22995. * @default true
  22996. */
  22997. this.isArcCurve = true;
  22998. this.type = 'ArcCurve';
  22999. }
  23000. }
  23001. function CubicPoly() {
  23002. /**
  23003. * Centripetal CatmullRom Curve - which is useful for avoiding
  23004. * cusps and self-intersections in non-uniform catmull rom curves.
  23005. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23006. *
  23007. * curve.type accepts centripetal(default), chordal and catmullrom
  23008. * curve.tension is used for catmullrom which defaults to 0.5
  23009. */
  23010. /*
  23011. Based on an optimized c++ solution in
  23012. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23013. - http://ideone.com/NoEbVM
  23014. This CubicPoly class could be used for reusing some variables and calculations,
  23015. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23016. which can be placed in CurveUtils.
  23017. */
  23018. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23019. /*
  23020. * Compute coefficients for a cubic polynomial
  23021. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23022. * such that
  23023. * p(0) = x0, p(1) = x1
  23024. * and
  23025. * p'(0) = t0, p'(1) = t1.
  23026. */
  23027. function init( x0, x1, t0, t1 ) {
  23028. c0 = x0;
  23029. c1 = t0;
  23030. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23031. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23032. }
  23033. return {
  23034. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23035. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23036. },
  23037. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23038. // compute tangents when parameterized in [t1,t2]
  23039. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23040. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23041. // rescale tangents for parametrization in [0,1]
  23042. t1 *= dt1;
  23043. t2 *= dt1;
  23044. init( x1, x2, t1, t2 );
  23045. },
  23046. calc: function ( t ) {
  23047. const t2 = t * t;
  23048. const t3 = t2 * t;
  23049. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23050. }
  23051. };
  23052. }
  23053. //
  23054. const tmp = /*@__PURE__*/ new Vector3();
  23055. const px = /*@__PURE__*/ new CubicPoly();
  23056. const py = /*@__PURE__*/ new CubicPoly();
  23057. const pz = /*@__PURE__*/ new CubicPoly();
  23058. /**
  23059. * A curve representing a Catmull-Rom spline.
  23060. *
  23061. * ```js
  23062. * //Create a closed wavey loop
  23063. * const curve = new THREE.CatmullRomCurve3( [
  23064. * new THREE.Vector3( -10, 0, 10 ),
  23065. * new THREE.Vector3( -5, 5, 5 ),
  23066. * new THREE.Vector3( 0, 0, 0 ),
  23067. * new THREE.Vector3( 5, -5, 5 ),
  23068. * new THREE.Vector3( 10, 0, 10 )
  23069. * ] );
  23070. *
  23071. * const points = curve.getPoints( 50 );
  23072. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23073. *
  23074. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23075. *
  23076. * // Create the final object to add to the scene
  23077. * const curveObject = new THREE.Line( geometry, material );
  23078. * ```
  23079. *
  23080. * @augments Curve
  23081. */
  23082. class CatmullRomCurve3 extends Curve {
  23083. /**
  23084. * Constructs a new Catmull-Rom curve.
  23085. *
  23086. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23087. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23088. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23089. * @param {number} [tension=0.5] - Tension of the curve.
  23090. */
  23091. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23092. super();
  23093. /**
  23094. * This flag can be used for type testing.
  23095. *
  23096. * @type {boolean}
  23097. * @readonly
  23098. * @default true
  23099. */
  23100. this.isCatmullRomCurve3 = true;
  23101. this.type = 'CatmullRomCurve3';
  23102. /**
  23103. * An array of 3D points defining the curve.
  23104. *
  23105. * @type {Array<Vector3>}
  23106. */
  23107. this.points = points;
  23108. /**
  23109. * Whether the curve is closed or not.
  23110. *
  23111. * @type {boolean}
  23112. * @default false
  23113. */
  23114. this.closed = closed;
  23115. /**
  23116. * The curve type.
  23117. *
  23118. * @type {('centripetal'|'chordal'|'catmullrom')}
  23119. * @default 'centripetal'
  23120. */
  23121. this.curveType = curveType;
  23122. /**
  23123. * Tension of the curve.
  23124. *
  23125. * @type {number}
  23126. * @default 0.5
  23127. */
  23128. this.tension = tension;
  23129. }
  23130. /**
  23131. * Returns a point on the curve.
  23132. *
  23133. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23134. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23135. * @return {Vector3} The position on the curve.
  23136. */
  23137. getPoint( t, optionalTarget = new Vector3() ) {
  23138. const point = optionalTarget;
  23139. const points = this.points;
  23140. const l = points.length;
  23141. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23142. let intPoint = Math.floor( p );
  23143. let weight = p - intPoint;
  23144. if ( this.closed ) {
  23145. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23146. } else if ( weight === 0 && intPoint === l - 1 ) {
  23147. intPoint = l - 2;
  23148. weight = 1;
  23149. }
  23150. let p0, p3; // 4 points (p1 & p2 defined below)
  23151. if ( this.closed || intPoint > 0 ) {
  23152. p0 = points[ ( intPoint - 1 ) % l ];
  23153. } else {
  23154. // extrapolate first point
  23155. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23156. p0 = tmp;
  23157. }
  23158. const p1 = points[ intPoint % l ];
  23159. const p2 = points[ ( intPoint + 1 ) % l ];
  23160. if ( this.closed || intPoint + 2 < l ) {
  23161. p3 = points[ ( intPoint + 2 ) % l ];
  23162. } else {
  23163. // extrapolate last point
  23164. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23165. p3 = tmp;
  23166. }
  23167. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23168. // init Centripetal / Chordal Catmull-Rom
  23169. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23170. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23171. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23172. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23173. // safety check for repeated points
  23174. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23175. if ( dt0 < 1e-4 ) dt0 = dt1;
  23176. if ( dt2 < 1e-4 ) dt2 = dt1;
  23177. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23178. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23179. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23180. } else if ( this.curveType === 'catmullrom' ) {
  23181. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23182. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23183. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23184. }
  23185. point.set(
  23186. px.calc( weight ),
  23187. py.calc( weight ),
  23188. pz.calc( weight )
  23189. );
  23190. return point;
  23191. }
  23192. copy( source ) {
  23193. super.copy( source );
  23194. this.points = [];
  23195. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23196. const point = source.points[ i ];
  23197. this.points.push( point.clone() );
  23198. }
  23199. this.closed = source.closed;
  23200. this.curveType = source.curveType;
  23201. this.tension = source.tension;
  23202. return this;
  23203. }
  23204. toJSON() {
  23205. const data = super.toJSON();
  23206. data.points = [];
  23207. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23208. const point = this.points[ i ];
  23209. data.points.push( point.toArray() );
  23210. }
  23211. data.closed = this.closed;
  23212. data.curveType = this.curveType;
  23213. data.tension = this.tension;
  23214. return data;
  23215. }
  23216. fromJSON( json ) {
  23217. super.fromJSON( json );
  23218. this.points = [];
  23219. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23220. const point = json.points[ i ];
  23221. this.points.push( new Vector3().fromArray( point ) );
  23222. }
  23223. this.closed = json.closed;
  23224. this.curveType = json.curveType;
  23225. this.tension = json.tension;
  23226. return this;
  23227. }
  23228. }
  23229. /**
  23230. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23231. *
  23232. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23233. *
  23234. * @module Interpolations
  23235. */
  23236. /**
  23237. * Computes a point on a Catmull-Rom spline.
  23238. *
  23239. * @param {number} t - The interpolation factor.
  23240. * @param {number} p0 - The first control point.
  23241. * @param {number} p1 - The second control point.
  23242. * @param {number} p2 - The third control point.
  23243. * @param {number} p3 - The fourth control point.
  23244. * @return {number} The calculated point on a Catmull-Rom spline.
  23245. */
  23246. function CatmullRom( t, p0, p1, p2, p3 ) {
  23247. const v0 = ( p2 - p0 ) * 0.5;
  23248. const v1 = ( p3 - p1 ) * 0.5;
  23249. const t2 = t * t;
  23250. const t3 = t * t2;
  23251. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23252. }
  23253. //
  23254. function QuadraticBezierP0( t, p ) {
  23255. const k = 1 - t;
  23256. return k * k * p;
  23257. }
  23258. function QuadraticBezierP1( t, p ) {
  23259. return 2 * ( 1 - t ) * t * p;
  23260. }
  23261. function QuadraticBezierP2( t, p ) {
  23262. return t * t * p;
  23263. }
  23264. /**
  23265. * Computes a point on a Quadratic Bezier curve.
  23266. *
  23267. * @param {number} t - The interpolation factor.
  23268. * @param {number} p0 - The first control point.
  23269. * @param {number} p1 - The second control point.
  23270. * @param {number} p2 - The third control point.
  23271. * @return {number} The calculated point on a Quadratic Bezier curve.
  23272. */
  23273. function QuadraticBezier( t, p0, p1, p2 ) {
  23274. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23275. QuadraticBezierP2( t, p2 );
  23276. }
  23277. //
  23278. function CubicBezierP0( t, p ) {
  23279. const k = 1 - t;
  23280. return k * k * k * p;
  23281. }
  23282. function CubicBezierP1( t, p ) {
  23283. const k = 1 - t;
  23284. return 3 * k * k * t * p;
  23285. }
  23286. function CubicBezierP2( t, p ) {
  23287. return 3 * ( 1 - t ) * t * t * p;
  23288. }
  23289. function CubicBezierP3( t, p ) {
  23290. return t * t * t * p;
  23291. }
  23292. /**
  23293. * Computes a point on a Cubic Bezier curve.
  23294. *
  23295. * @param {number} t - The interpolation factor.
  23296. * @param {number} p0 - The first control point.
  23297. * @param {number} p1 - The second control point.
  23298. * @param {number} p2 - The third control point.
  23299. * @param {number} p3 - The fourth control point.
  23300. * @return {number} The calculated point on a Cubic Bezier curve.
  23301. */
  23302. function CubicBezier( t, p0, p1, p2, p3 ) {
  23303. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23304. CubicBezierP3( t, p3 );
  23305. }
  23306. /**
  23307. * A curve representing a 2D Cubic Bezier curve.
  23308. *
  23309. * ```js
  23310. * const curve = new THREE.CubicBezierCurve(
  23311. * new THREE.Vector2( - 0, 0 ),
  23312. * new THREE.Vector2( - 5, 15 ),
  23313. * new THREE.Vector2( 20, 15 ),
  23314. * new THREE.Vector2( 10, 0 )
  23315. * );
  23316. *
  23317. * const points = curve.getPoints( 50 );
  23318. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23319. *
  23320. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23321. *
  23322. * // Create the final object to add to the scene
  23323. * const curveObject = new THREE.Line( geometry, material );
  23324. * ```
  23325. *
  23326. * @augments Curve
  23327. */
  23328. class CubicBezierCurve extends Curve {
  23329. /**
  23330. * Constructs a new Cubic Bezier curve.
  23331. *
  23332. * @param {Vector2} [v0] - The start point.
  23333. * @param {Vector2} [v1] - The first control point.
  23334. * @param {Vector2} [v2] - The second control point.
  23335. * @param {Vector2} [v3] - The end point.
  23336. */
  23337. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23338. super();
  23339. /**
  23340. * This flag can be used for type testing.
  23341. *
  23342. * @type {boolean}
  23343. * @readonly
  23344. * @default true
  23345. */
  23346. this.isCubicBezierCurve = true;
  23347. this.type = 'CubicBezierCurve';
  23348. /**
  23349. * The start point.
  23350. *
  23351. * @type {Vector2}
  23352. */
  23353. this.v0 = v0;
  23354. /**
  23355. * The first control point.
  23356. *
  23357. * @type {Vector2}
  23358. */
  23359. this.v1 = v1;
  23360. /**
  23361. * The second control point.
  23362. *
  23363. * @type {Vector2}
  23364. */
  23365. this.v2 = v2;
  23366. /**
  23367. * The end point.
  23368. *
  23369. * @type {Vector2}
  23370. */
  23371. this.v3 = v3;
  23372. }
  23373. /**
  23374. * Returns a point on the curve.
  23375. *
  23376. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23377. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23378. * @return {Vector2} The position on the curve.
  23379. */
  23380. getPoint( t, optionalTarget = new Vector2() ) {
  23381. const point = optionalTarget;
  23382. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23383. point.set(
  23384. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23385. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23386. );
  23387. return point;
  23388. }
  23389. copy( source ) {
  23390. super.copy( source );
  23391. this.v0.copy( source.v0 );
  23392. this.v1.copy( source.v1 );
  23393. this.v2.copy( source.v2 );
  23394. this.v3.copy( source.v3 );
  23395. return this;
  23396. }
  23397. toJSON() {
  23398. const data = super.toJSON();
  23399. data.v0 = this.v0.toArray();
  23400. data.v1 = this.v1.toArray();
  23401. data.v2 = this.v2.toArray();
  23402. data.v3 = this.v3.toArray();
  23403. return data;
  23404. }
  23405. fromJSON( json ) {
  23406. super.fromJSON( json );
  23407. this.v0.fromArray( json.v0 );
  23408. this.v1.fromArray( json.v1 );
  23409. this.v2.fromArray( json.v2 );
  23410. this.v3.fromArray( json.v3 );
  23411. return this;
  23412. }
  23413. }
  23414. /**
  23415. * A curve representing a 3D Cubic Bezier curve.
  23416. *
  23417. * @augments Curve
  23418. */
  23419. class CubicBezierCurve3 extends Curve {
  23420. /**
  23421. * Constructs a new Cubic Bezier curve.
  23422. *
  23423. * @param {Vector3} [v0] - The start point.
  23424. * @param {Vector3} [v1] - The first control point.
  23425. * @param {Vector3} [v2] - The second control point.
  23426. * @param {Vector3} [v3] - The end point.
  23427. */
  23428. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23429. super();
  23430. /**
  23431. * This flag can be used for type testing.
  23432. *
  23433. * @type {boolean}
  23434. * @readonly
  23435. * @default true
  23436. */
  23437. this.isCubicBezierCurve3 = true;
  23438. this.type = 'CubicBezierCurve3';
  23439. /**
  23440. * The start point.
  23441. *
  23442. * @type {Vector3}
  23443. */
  23444. this.v0 = v0;
  23445. /**
  23446. * The first control point.
  23447. *
  23448. * @type {Vector3}
  23449. */
  23450. this.v1 = v1;
  23451. /**
  23452. * The second control point.
  23453. *
  23454. * @type {Vector3}
  23455. */
  23456. this.v2 = v2;
  23457. /**
  23458. * The end point.
  23459. *
  23460. * @type {Vector3}
  23461. */
  23462. this.v3 = v3;
  23463. }
  23464. /**
  23465. * Returns a point on the curve.
  23466. *
  23467. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23468. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23469. * @return {Vector3} The position on the curve.
  23470. */
  23471. getPoint( t, optionalTarget = new Vector3() ) {
  23472. const point = optionalTarget;
  23473. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23474. point.set(
  23475. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23476. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23477. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23478. );
  23479. return point;
  23480. }
  23481. copy( source ) {
  23482. super.copy( source );
  23483. this.v0.copy( source.v0 );
  23484. this.v1.copy( source.v1 );
  23485. this.v2.copy( source.v2 );
  23486. this.v3.copy( source.v3 );
  23487. return this;
  23488. }
  23489. toJSON() {
  23490. const data = super.toJSON();
  23491. data.v0 = this.v0.toArray();
  23492. data.v1 = this.v1.toArray();
  23493. data.v2 = this.v2.toArray();
  23494. data.v3 = this.v3.toArray();
  23495. return data;
  23496. }
  23497. fromJSON( json ) {
  23498. super.fromJSON( json );
  23499. this.v0.fromArray( json.v0 );
  23500. this.v1.fromArray( json.v1 );
  23501. this.v2.fromArray( json.v2 );
  23502. this.v3.fromArray( json.v3 );
  23503. return this;
  23504. }
  23505. }
  23506. /**
  23507. * A curve representing a 2D line segment.
  23508. *
  23509. * @augments Curve
  23510. */
  23511. class LineCurve extends Curve {
  23512. /**
  23513. * Constructs a new line curve.
  23514. *
  23515. * @param {Vector2} [v1] - The start point.
  23516. * @param {Vector2} [v2] - The end point.
  23517. */
  23518. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23519. super();
  23520. /**
  23521. * This flag can be used for type testing.
  23522. *
  23523. * @type {boolean}
  23524. * @readonly
  23525. * @default true
  23526. */
  23527. this.isLineCurve = true;
  23528. this.type = 'LineCurve';
  23529. /**
  23530. * The start point.
  23531. *
  23532. * @type {Vector2}
  23533. */
  23534. this.v1 = v1;
  23535. /**
  23536. * The end point.
  23537. *
  23538. * @type {Vector2}
  23539. */
  23540. this.v2 = v2;
  23541. }
  23542. /**
  23543. * Returns a point on the line.
  23544. *
  23545. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23546. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23547. * @return {Vector2} The position on the line.
  23548. */
  23549. getPoint( t, optionalTarget = new Vector2() ) {
  23550. const point = optionalTarget;
  23551. if ( t === 1 ) {
  23552. point.copy( this.v2 );
  23553. } else {
  23554. point.copy( this.v2 ).sub( this.v1 );
  23555. point.multiplyScalar( t ).add( this.v1 );
  23556. }
  23557. return point;
  23558. }
  23559. // Line curve is linear, so we can overwrite default getPointAt
  23560. getPointAt( u, optionalTarget ) {
  23561. return this.getPoint( u, optionalTarget );
  23562. }
  23563. getTangent( t, optionalTarget = new Vector2() ) {
  23564. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23565. }
  23566. getTangentAt( u, optionalTarget ) {
  23567. return this.getTangent( u, optionalTarget );
  23568. }
  23569. copy( source ) {
  23570. super.copy( source );
  23571. this.v1.copy( source.v1 );
  23572. this.v2.copy( source.v2 );
  23573. return this;
  23574. }
  23575. toJSON() {
  23576. const data = super.toJSON();
  23577. data.v1 = this.v1.toArray();
  23578. data.v2 = this.v2.toArray();
  23579. return data;
  23580. }
  23581. fromJSON( json ) {
  23582. super.fromJSON( json );
  23583. this.v1.fromArray( json.v1 );
  23584. this.v2.fromArray( json.v2 );
  23585. return this;
  23586. }
  23587. }
  23588. /**
  23589. * A curve representing a 3D line segment.
  23590. *
  23591. * @augments Curve
  23592. */
  23593. class LineCurve3 extends Curve {
  23594. /**
  23595. * Constructs a new line curve.
  23596. *
  23597. * @param {Vector3} [v1] - The start point.
  23598. * @param {Vector3} [v2] - The end point.
  23599. */
  23600. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23601. super();
  23602. /**
  23603. * This flag can be used for type testing.
  23604. *
  23605. * @type {boolean}
  23606. * @readonly
  23607. * @default true
  23608. */
  23609. this.isLineCurve3 = true;
  23610. this.type = 'LineCurve3';
  23611. /**
  23612. * The start point.
  23613. *
  23614. * @type {Vector3}
  23615. */
  23616. this.v1 = v1;
  23617. /**
  23618. * The end point.
  23619. *
  23620. * @type {Vector2}
  23621. */
  23622. this.v2 = v2;
  23623. }
  23624. /**
  23625. * Returns a point on the line.
  23626. *
  23627. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23628. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23629. * @return {Vector3} The position on the line.
  23630. */
  23631. getPoint( t, optionalTarget = new Vector3() ) {
  23632. const point = optionalTarget;
  23633. if ( t === 1 ) {
  23634. point.copy( this.v2 );
  23635. } else {
  23636. point.copy( this.v2 ).sub( this.v1 );
  23637. point.multiplyScalar( t ).add( this.v1 );
  23638. }
  23639. return point;
  23640. }
  23641. // Line curve is linear, so we can overwrite default getPointAt
  23642. getPointAt( u, optionalTarget ) {
  23643. return this.getPoint( u, optionalTarget );
  23644. }
  23645. getTangent( t, optionalTarget = new Vector3() ) {
  23646. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23647. }
  23648. getTangentAt( u, optionalTarget ) {
  23649. return this.getTangent( u, optionalTarget );
  23650. }
  23651. copy( source ) {
  23652. super.copy( source );
  23653. this.v1.copy( source.v1 );
  23654. this.v2.copy( source.v2 );
  23655. return this;
  23656. }
  23657. toJSON() {
  23658. const data = super.toJSON();
  23659. data.v1 = this.v1.toArray();
  23660. data.v2 = this.v2.toArray();
  23661. return data;
  23662. }
  23663. fromJSON( json ) {
  23664. super.fromJSON( json );
  23665. this.v1.fromArray( json.v1 );
  23666. this.v2.fromArray( json.v2 );
  23667. return this;
  23668. }
  23669. }
  23670. /**
  23671. * A curve representing a 2D Quadratic Bezier curve.
  23672. *
  23673. * ```js
  23674. * const curve = new THREE.QuadraticBezierCurve(
  23675. * new THREE.Vector2( - 10, 0 ),
  23676. * new THREE.Vector2( 20, 15 ),
  23677. * new THREE.Vector2( 10, 0 )
  23678. * )
  23679. *
  23680. * const points = curve.getPoints( 50 );
  23681. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23682. *
  23683. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23684. *
  23685. * // Create the final object to add to the scene
  23686. * const curveObject = new THREE.Line( geometry, material );
  23687. * ```
  23688. *
  23689. * @augments Curve
  23690. */
  23691. class QuadraticBezierCurve extends Curve {
  23692. /**
  23693. * Constructs a new Quadratic Bezier curve.
  23694. *
  23695. * @param {Vector2} [v0] - The start point.
  23696. * @param {Vector2} [v1] - The control point.
  23697. * @param {Vector2} [v2] - The end point.
  23698. */
  23699. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  23700. super();
  23701. /**
  23702. * This flag can be used for type testing.
  23703. *
  23704. * @type {boolean}
  23705. * @readonly
  23706. * @default true
  23707. */
  23708. this.isQuadraticBezierCurve = true;
  23709. this.type = 'QuadraticBezierCurve';
  23710. /**
  23711. * The start point.
  23712. *
  23713. * @type {Vector2}
  23714. */
  23715. this.v0 = v0;
  23716. /**
  23717. * The control point.
  23718. *
  23719. * @type {Vector2}
  23720. */
  23721. this.v1 = v1;
  23722. /**
  23723. * The end point.
  23724. *
  23725. * @type {Vector2}
  23726. */
  23727. this.v2 = v2;
  23728. }
  23729. /**
  23730. * Returns a point on the curve.
  23731. *
  23732. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23733. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23734. * @return {Vector2} The position on the curve.
  23735. */
  23736. getPoint( t, optionalTarget = new Vector2() ) {
  23737. const point = optionalTarget;
  23738. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23739. point.set(
  23740. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23741. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23742. );
  23743. return point;
  23744. }
  23745. copy( source ) {
  23746. super.copy( source );
  23747. this.v0.copy( source.v0 );
  23748. this.v1.copy( source.v1 );
  23749. this.v2.copy( source.v2 );
  23750. return this;
  23751. }
  23752. toJSON() {
  23753. const data = super.toJSON();
  23754. data.v0 = this.v0.toArray();
  23755. data.v1 = this.v1.toArray();
  23756. data.v2 = this.v2.toArray();
  23757. return data;
  23758. }
  23759. fromJSON( json ) {
  23760. super.fromJSON( json );
  23761. this.v0.fromArray( json.v0 );
  23762. this.v1.fromArray( json.v1 );
  23763. this.v2.fromArray( json.v2 );
  23764. return this;
  23765. }
  23766. }
  23767. /**
  23768. * A curve representing a 3D Quadratic Bezier curve.
  23769. *
  23770. * @augments Curve
  23771. */
  23772. class QuadraticBezierCurve3 extends Curve {
  23773. /**
  23774. * Constructs a new Quadratic Bezier curve.
  23775. *
  23776. * @param {Vector3} [v0] - The start point.
  23777. * @param {Vector3} [v1] - The control point.
  23778. * @param {Vector3} [v2] - The end point.
  23779. */
  23780. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23781. super();
  23782. /**
  23783. * This flag can be used for type testing.
  23784. *
  23785. * @type {boolean}
  23786. * @readonly
  23787. * @default true
  23788. */
  23789. this.isQuadraticBezierCurve3 = true;
  23790. this.type = 'QuadraticBezierCurve3';
  23791. /**
  23792. * The start point.
  23793. *
  23794. * @type {Vector3}
  23795. */
  23796. this.v0 = v0;
  23797. /**
  23798. * The control point.
  23799. *
  23800. * @type {Vector3}
  23801. */
  23802. this.v1 = v1;
  23803. /**
  23804. * The end point.
  23805. *
  23806. * @type {Vector3}
  23807. */
  23808. this.v2 = v2;
  23809. }
  23810. /**
  23811. * Returns a point on the curve.
  23812. *
  23813. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23814. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23815. * @return {Vector3} The position on the curve.
  23816. */
  23817. getPoint( t, optionalTarget = new Vector3() ) {
  23818. const point = optionalTarget;
  23819. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23820. point.set(
  23821. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23822. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23823. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23824. );
  23825. return point;
  23826. }
  23827. copy( source ) {
  23828. super.copy( source );
  23829. this.v0.copy( source.v0 );
  23830. this.v1.copy( source.v1 );
  23831. this.v2.copy( source.v2 );
  23832. return this;
  23833. }
  23834. toJSON() {
  23835. const data = super.toJSON();
  23836. data.v0 = this.v0.toArray();
  23837. data.v1 = this.v1.toArray();
  23838. data.v2 = this.v2.toArray();
  23839. return data;
  23840. }
  23841. fromJSON( json ) {
  23842. super.fromJSON( json );
  23843. this.v0.fromArray( json.v0 );
  23844. this.v1.fromArray( json.v1 );
  23845. this.v2.fromArray( json.v2 );
  23846. return this;
  23847. }
  23848. }
  23849. /**
  23850. * A curve representing a 2D spline curve.
  23851. *
  23852. * ```js
  23853. * // Create a sine-like wave
  23854. * const curve = new THREE.SplineCurve( [
  23855. * new THREE.Vector2( -10, 0 ),
  23856. * new THREE.Vector2( -5, 5 ),
  23857. * new THREE.Vector2( 0, 0 ),
  23858. * new THREE.Vector2( 5, -5 ),
  23859. * new THREE.Vector2( 10, 0 )
  23860. * ] );
  23861. *
  23862. * const points = curve.getPoints( 50 );
  23863. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23864. *
  23865. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23866. *
  23867. * // Create the final object to add to the scene
  23868. * const splineObject = new THREE.Line( geometry, material );
  23869. * ```
  23870. *
  23871. * @augments Curve
  23872. */
  23873. class SplineCurve extends Curve {
  23874. /**
  23875. * Constructs a new 2D spline curve.
  23876. *
  23877. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  23878. */
  23879. constructor( points = [] ) {
  23880. super();
  23881. /**
  23882. * This flag can be used for type testing.
  23883. *
  23884. * @type {boolean}
  23885. * @readonly
  23886. * @default true
  23887. */
  23888. this.isSplineCurve = true;
  23889. this.type = 'SplineCurve';
  23890. /**
  23891. * An array of 2D points defining the curve.
  23892. *
  23893. * @type {Array<Vector2>}
  23894. */
  23895. this.points = points;
  23896. }
  23897. /**
  23898. * Returns a point on the curve.
  23899. *
  23900. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23901. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23902. * @return {Vector2} The position on the curve.
  23903. */
  23904. getPoint( t, optionalTarget = new Vector2() ) {
  23905. const point = optionalTarget;
  23906. const points = this.points;
  23907. const p = ( points.length - 1 ) * t;
  23908. const intPoint = Math.floor( p );
  23909. const weight = p - intPoint;
  23910. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23911. const p1 = points[ intPoint ];
  23912. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23913. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23914. point.set(
  23915. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23916. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23917. );
  23918. return point;
  23919. }
  23920. copy( source ) {
  23921. super.copy( source );
  23922. this.points = [];
  23923. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23924. const point = source.points[ i ];
  23925. this.points.push( point.clone() );
  23926. }
  23927. return this;
  23928. }
  23929. toJSON() {
  23930. const data = super.toJSON();
  23931. data.points = [];
  23932. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23933. const point = this.points[ i ];
  23934. data.points.push( point.toArray() );
  23935. }
  23936. return data;
  23937. }
  23938. fromJSON( json ) {
  23939. super.fromJSON( json );
  23940. this.points = [];
  23941. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23942. const point = json.points[ i ];
  23943. this.points.push( new Vector2().fromArray( point ) );
  23944. }
  23945. return this;
  23946. }
  23947. }
  23948. var Curves = /*#__PURE__*/Object.freeze({
  23949. __proto__: null,
  23950. ArcCurve: ArcCurve,
  23951. CatmullRomCurve3: CatmullRomCurve3,
  23952. CubicBezierCurve: CubicBezierCurve,
  23953. CubicBezierCurve3: CubicBezierCurve3,
  23954. EllipseCurve: EllipseCurve,
  23955. LineCurve: LineCurve,
  23956. LineCurve3: LineCurve3,
  23957. QuadraticBezierCurve: QuadraticBezierCurve,
  23958. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23959. SplineCurve: SplineCurve
  23960. });
  23961. /**
  23962. * A base class extending {@link Curve}. `CurvePath` is simply an
  23963. * array of connected curves, but retains the API of a curve.
  23964. *
  23965. * @augments Curve
  23966. */
  23967. class CurvePath extends Curve {
  23968. /**
  23969. * Constructs a new curve path.
  23970. */
  23971. constructor() {
  23972. super();
  23973. this.type = 'CurvePath';
  23974. /**
  23975. * An array of curves defining the
  23976. * path.
  23977. *
  23978. * @type {Array<Curve>}
  23979. */
  23980. this.curves = [];
  23981. /**
  23982. * Whether the path should automatically be closed
  23983. * by a line curve.
  23984. *
  23985. * @type {boolean}
  23986. * @default false
  23987. */
  23988. this.autoClose = false;
  23989. }
  23990. /**
  23991. * Adds a curve to this curve path.
  23992. *
  23993. * @param {Curve} curve - The curve to add.
  23994. */
  23995. add( curve ) {
  23996. this.curves.push( curve );
  23997. }
  23998. /**
  23999. * Adds a line curve to close the path.
  24000. *
  24001. * @return {CurvePath} A reference to this curve path.
  24002. */
  24003. closePath() {
  24004. // Add a line curve if start and end of lines are not connected
  24005. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24006. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24007. if ( ! startPoint.equals( endPoint ) ) {
  24008. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24009. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24010. }
  24011. return this;
  24012. }
  24013. /**
  24014. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24015. * for the given interpolation factor.
  24016. *
  24017. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24018. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24019. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24020. */
  24021. getPoint( t, optionalTarget ) {
  24022. // To get accurate point with reference to
  24023. // entire path distance at time t,
  24024. // following has to be done:
  24025. // 1. Length of each sub path have to be known
  24026. // 2. Locate and identify type of curve
  24027. // 3. Get t for the curve
  24028. // 4. Return curve.getPointAt(t')
  24029. const d = t * this.getLength();
  24030. const curveLengths = this.getCurveLengths();
  24031. let i = 0;
  24032. // To think about boundaries points.
  24033. while ( i < curveLengths.length ) {
  24034. if ( curveLengths[ i ] >= d ) {
  24035. const diff = curveLengths[ i ] - d;
  24036. const curve = this.curves[ i ];
  24037. const segmentLength = curve.getLength();
  24038. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24039. return curve.getPointAt( u, optionalTarget );
  24040. }
  24041. i ++;
  24042. }
  24043. return null;
  24044. // loop where sum != 0, sum > d , sum+1 <d
  24045. }
  24046. getLength() {
  24047. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24048. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24049. // getPoint() depends on getLength
  24050. const lens = this.getCurveLengths();
  24051. return lens[ lens.length - 1 ];
  24052. }
  24053. updateArcLengths() {
  24054. // cacheLengths must be recalculated.
  24055. this.needsUpdate = true;
  24056. this.cacheLengths = null;
  24057. this.getCurveLengths();
  24058. }
  24059. /**
  24060. * Returns list of cumulative curve lengths of the defined curves.
  24061. *
  24062. * @return {Array<number>} The curve lengths.
  24063. */
  24064. getCurveLengths() {
  24065. // Compute lengths and cache them
  24066. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24067. // We use cache values if curves and cache array are same length
  24068. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24069. return this.cacheLengths;
  24070. }
  24071. // Get length of sub-curve
  24072. // Push sums into cached array
  24073. const lengths = [];
  24074. let sums = 0;
  24075. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24076. sums += this.curves[ i ].getLength();
  24077. lengths.push( sums );
  24078. }
  24079. this.cacheLengths = lengths;
  24080. return lengths;
  24081. }
  24082. getSpacedPoints( divisions = 40 ) {
  24083. const points = [];
  24084. for ( let i = 0; i <= divisions; i ++ ) {
  24085. points.push( this.getPoint( i / divisions ) );
  24086. }
  24087. if ( this.autoClose ) {
  24088. points.push( points[ 0 ] );
  24089. }
  24090. return points;
  24091. }
  24092. getPoints( divisions = 12 ) {
  24093. const points = [];
  24094. let last;
  24095. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24096. const curve = curves[ i ];
  24097. const resolution = curve.isEllipseCurve ? divisions * 2
  24098. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24099. : curve.isSplineCurve ? divisions * curve.points.length
  24100. : divisions;
  24101. const pts = curve.getPoints( resolution );
  24102. for ( let j = 0; j < pts.length; j ++ ) {
  24103. const point = pts[ j ];
  24104. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24105. points.push( point );
  24106. last = point;
  24107. }
  24108. }
  24109. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24110. points.push( points[ 0 ] );
  24111. }
  24112. return points;
  24113. }
  24114. copy( source ) {
  24115. super.copy( source );
  24116. this.curves = [];
  24117. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24118. const curve = source.curves[ i ];
  24119. this.curves.push( curve.clone() );
  24120. }
  24121. this.autoClose = source.autoClose;
  24122. return this;
  24123. }
  24124. toJSON() {
  24125. const data = super.toJSON();
  24126. data.autoClose = this.autoClose;
  24127. data.curves = [];
  24128. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24129. const curve = this.curves[ i ];
  24130. data.curves.push( curve.toJSON() );
  24131. }
  24132. return data;
  24133. }
  24134. fromJSON( json ) {
  24135. super.fromJSON( json );
  24136. this.autoClose = json.autoClose;
  24137. this.curves = [];
  24138. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24139. const curve = json.curves[ i ];
  24140. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24141. }
  24142. return this;
  24143. }
  24144. }
  24145. /**
  24146. * A 2D path representation. The class provides methods for creating paths
  24147. * and contours of 2D shapes similar to the 2D Canvas API.
  24148. *
  24149. * ```js
  24150. * const path = new THREE.Path();
  24151. *
  24152. * path.lineTo( 0, 0.8 );
  24153. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24154. * path.lineTo( 1, 1 );
  24155. *
  24156. * const points = path.getPoints();
  24157. *
  24158. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24159. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24160. *
  24161. * const line = new THREE.Line( geometry, material );
  24162. * scene.add( line );
  24163. * ```
  24164. *
  24165. * @augments CurvePath
  24166. */
  24167. class Path extends CurvePath {
  24168. /**
  24169. * Constructs a new path.
  24170. *
  24171. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24172. */
  24173. constructor( points ) {
  24174. super();
  24175. this.type = 'Path';
  24176. /**
  24177. * The current offset of the path. Any new curve added will start here.
  24178. *
  24179. * @type {Vector2}
  24180. */
  24181. this.currentPoint = new Vector2();
  24182. if ( points ) {
  24183. this.setFromPoints( points );
  24184. }
  24185. }
  24186. /**
  24187. * Creates a path from the given list of points. The points are added
  24188. * to the path as instances of {@link LineCurve}.
  24189. *
  24190. * @param {Array<Vector2>} points - An array of 2D points.
  24191. * @return {Path} A reference to this path.
  24192. */
  24193. setFromPoints( points ) {
  24194. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24195. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24196. this.lineTo( points[ i ].x, points[ i ].y );
  24197. }
  24198. return this;
  24199. }
  24200. /**
  24201. * Moves {@link Path#currentPoint} to the given point.
  24202. *
  24203. * @param {number} x - The x coordinate.
  24204. * @param {number} y - The y coordinate.
  24205. * @return {Path} A reference to this path.
  24206. */
  24207. moveTo( x, y ) {
  24208. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24209. return this;
  24210. }
  24211. /**
  24212. * Adds an instance of {@link LineCurve} to the path by connecting
  24213. * the current point with the given one.
  24214. *
  24215. * @param {number} x - The x coordinate of the end point.
  24216. * @param {number} y - The y coordinate of the end point.
  24217. * @return {Path} A reference to this path.
  24218. */
  24219. lineTo( x, y ) {
  24220. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24221. this.curves.push( curve );
  24222. this.currentPoint.set( x, y );
  24223. return this;
  24224. }
  24225. /**
  24226. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24227. * the current point with the given one.
  24228. *
  24229. * @param {number} aCPx - The x coordinate of the control point.
  24230. * @param {number} aCPy - The y coordinate of the control point.
  24231. * @param {number} aX - The x coordinate of the end point.
  24232. * @param {number} aY - The y coordinate of the end point.
  24233. * @return {Path} A reference to this path.
  24234. */
  24235. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24236. const curve = new QuadraticBezierCurve(
  24237. this.currentPoint.clone(),
  24238. new Vector2( aCPx, aCPy ),
  24239. new Vector2( aX, aY )
  24240. );
  24241. this.curves.push( curve );
  24242. this.currentPoint.set( aX, aY );
  24243. return this;
  24244. }
  24245. /**
  24246. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24247. * the current point with the given one.
  24248. *
  24249. * @param {number} aCP1x - The x coordinate of the first control point.
  24250. * @param {number} aCP1y - The y coordinate of the first control point.
  24251. * @param {number} aCP2x - The x coordinate of the second control point.
  24252. * @param {number} aCP2y - The y coordinate of the second control point.
  24253. * @param {number} aX - The x coordinate of the end point.
  24254. * @param {number} aY - The y coordinate of the end point.
  24255. * @return {Path} A reference to this path.
  24256. */
  24257. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24258. const curve = new CubicBezierCurve(
  24259. this.currentPoint.clone(),
  24260. new Vector2( aCP1x, aCP1y ),
  24261. new Vector2( aCP2x, aCP2y ),
  24262. new Vector2( aX, aY )
  24263. );
  24264. this.curves.push( curve );
  24265. this.currentPoint.set( aX, aY );
  24266. return this;
  24267. }
  24268. /**
  24269. * Adds an instance of {@link SplineCurve} to the path by connecting
  24270. * the current point with the given list of points.
  24271. *
  24272. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24273. * @return {Path} A reference to this path.
  24274. */
  24275. splineThru( pts ) {
  24276. const npts = [ this.currentPoint.clone() ].concat( pts );
  24277. const curve = new SplineCurve( npts );
  24278. this.curves.push( curve );
  24279. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24280. return this;
  24281. }
  24282. /**
  24283. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24284. * to the current point.
  24285. *
  24286. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24287. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24288. * @param {number} [aRadius=1] - The radius of the arc.
  24289. * @param {number} [aStartAngle=0] - The start angle in radians.
  24290. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24291. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24292. * @return {Path} A reference to this path.
  24293. */
  24294. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24295. const x0 = this.currentPoint.x;
  24296. const y0 = this.currentPoint.y;
  24297. this.absarc( aX + x0, aY + y0, aRadius,
  24298. aStartAngle, aEndAngle, aClockwise );
  24299. return this;
  24300. }
  24301. /**
  24302. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24303. *
  24304. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24305. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24306. * @param {number} [aRadius=1] - The radius of the arc.
  24307. * @param {number} [aStartAngle=0] - The start angle in radians.
  24308. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24309. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24310. * @return {Path} A reference to this path.
  24311. */
  24312. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24313. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24314. return this;
  24315. }
  24316. /**
  24317. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24318. * to the current point
  24319. *
  24320. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24321. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24322. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24323. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24324. * @param {number} [aStartAngle=0] - The start angle in radians.
  24325. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24326. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24327. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24328. * @return {Path} A reference to this path.
  24329. */
  24330. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24331. const x0 = this.currentPoint.x;
  24332. const y0 = this.currentPoint.y;
  24333. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24334. return this;
  24335. }
  24336. /**
  24337. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24338. *
  24339. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24340. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24341. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24342. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24343. * @param {number} [aStartAngle=0] - The start angle in radians.
  24344. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24345. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24346. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24347. * @return {Path} A reference to this path.
  24348. */
  24349. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24350. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24351. if ( this.curves.length > 0 ) {
  24352. // if a previous curve is present, attempt to join
  24353. const firstPoint = curve.getPoint( 0 );
  24354. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24355. this.lineTo( firstPoint.x, firstPoint.y );
  24356. }
  24357. }
  24358. this.curves.push( curve );
  24359. const lastPoint = curve.getPoint( 1 );
  24360. this.currentPoint.copy( lastPoint );
  24361. return this;
  24362. }
  24363. copy( source ) {
  24364. super.copy( source );
  24365. this.currentPoint.copy( source.currentPoint );
  24366. return this;
  24367. }
  24368. toJSON() {
  24369. const data = super.toJSON();
  24370. data.currentPoint = this.currentPoint.toArray();
  24371. return data;
  24372. }
  24373. fromJSON( json ) {
  24374. super.fromJSON( json );
  24375. this.currentPoint.fromArray( json.currentPoint );
  24376. return this;
  24377. }
  24378. }
  24379. /**
  24380. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24381. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24382. * points, or to get triangulated faces.
  24383. *
  24384. * ```js
  24385. * const heartShape = new THREE.Shape();
  24386. *
  24387. * heartShape.moveTo( 25, 25 );
  24388. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24389. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24390. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24391. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24392. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24393. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24394. *
  24395. * const extrudeSettings = {
  24396. * depth: 8,
  24397. * bevelEnabled: true,
  24398. * bevelSegments: 2,
  24399. * steps: 2,
  24400. * bevelSize: 1,
  24401. * bevelThickness: 1
  24402. * };
  24403. *
  24404. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24405. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24406. * ```
  24407. *
  24408. * @augments Path
  24409. */
  24410. class Shape extends Path {
  24411. /**
  24412. * Constructs a new shape.
  24413. *
  24414. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24415. */
  24416. constructor( points ) {
  24417. super( points );
  24418. /**
  24419. * The UUID of the shape.
  24420. *
  24421. * @type {string}
  24422. * @readonly
  24423. */
  24424. this.uuid = generateUUID();
  24425. this.type = 'Shape';
  24426. /**
  24427. * Defines the holes in the shape. Hole definitions must use the
  24428. * opposite winding order (CW/CCW) than the outer shape.
  24429. *
  24430. * @type {Array<Path>}
  24431. * @readonly
  24432. */
  24433. this.holes = [];
  24434. }
  24435. /**
  24436. * Returns an array representing each contour of the holes
  24437. * as a list of 2D points.
  24438. *
  24439. * @param {number} divisions - The fineness of the result.
  24440. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24441. */
  24442. getPointsHoles( divisions ) {
  24443. const holesPts = [];
  24444. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24445. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24446. }
  24447. return holesPts;
  24448. }
  24449. // get points of shape and holes (keypoints based on segments parameter)
  24450. /**
  24451. * Returns an object that holds contour data for the shape and its holes as
  24452. * arrays of 2D points.
  24453. *
  24454. * @param {number} divisions - The fineness of the result.
  24455. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24456. */
  24457. extractPoints( divisions ) {
  24458. return {
  24459. shape: this.getPoints( divisions ),
  24460. holes: this.getPointsHoles( divisions )
  24461. };
  24462. }
  24463. copy( source ) {
  24464. super.copy( source );
  24465. this.holes = [];
  24466. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24467. const hole = source.holes[ i ];
  24468. this.holes.push( hole.clone() );
  24469. }
  24470. return this;
  24471. }
  24472. toJSON() {
  24473. const data = super.toJSON();
  24474. data.uuid = this.uuid;
  24475. data.holes = [];
  24476. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24477. const hole = this.holes[ i ];
  24478. data.holes.push( hole.toJSON() );
  24479. }
  24480. return data;
  24481. }
  24482. fromJSON( json ) {
  24483. super.fromJSON( json );
  24484. this.uuid = json.uuid;
  24485. this.holes = [];
  24486. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24487. const hole = json.holes[ i ];
  24488. this.holes.push( new Path().fromJSON( hole ) );
  24489. }
  24490. return this;
  24491. }
  24492. }
  24493. /* eslint-disable */
  24494. // copy of mapbox/earcut version 3.0.2
  24495. // https://github.com/mapbox/earcut/tree/v3.0.2
  24496. function earcut(data, holeIndices, dim = 2) {
  24497. const hasHoles = holeIndices && holeIndices.length;
  24498. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24499. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24500. const triangles = [];
  24501. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24502. let minX, minY, invSize;
  24503. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24504. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24505. if (data.length > 80 * dim) {
  24506. minX = data[0];
  24507. minY = data[1];
  24508. let maxX = minX;
  24509. let maxY = minY;
  24510. for (let i = dim; i < outerLen; i += dim) {
  24511. const x = data[i];
  24512. const y = data[i + 1];
  24513. if (x < minX) minX = x;
  24514. if (y < minY) minY = y;
  24515. if (x > maxX) maxX = x;
  24516. if (y > maxY) maxY = y;
  24517. }
  24518. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24519. invSize = Math.max(maxX - minX, maxY - minY);
  24520. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24521. }
  24522. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24523. return triangles;
  24524. }
  24525. // create a circular doubly linked list from polygon points in the specified winding order
  24526. function linkedList(data, start, end, dim, clockwise) {
  24527. let last;
  24528. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24529. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24530. } else {
  24531. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24532. }
  24533. if (last && equals(last, last.next)) {
  24534. removeNode(last);
  24535. last = last.next;
  24536. }
  24537. return last;
  24538. }
  24539. // eliminate colinear or duplicate points
  24540. function filterPoints(start, end) {
  24541. if (!start) return start;
  24542. if (!end) end = start;
  24543. let p = start,
  24544. again;
  24545. do {
  24546. again = false;
  24547. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24548. removeNode(p);
  24549. p = end = p.prev;
  24550. if (p === p.next) break;
  24551. again = true;
  24552. } else {
  24553. p = p.next;
  24554. }
  24555. } while (again || p !== end);
  24556. return end;
  24557. }
  24558. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24559. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24560. if (!ear) return;
  24561. // interlink polygon nodes in z-order
  24562. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24563. let stop = ear;
  24564. // iterate through ears, slicing them one by one
  24565. while (ear.prev !== ear.next) {
  24566. const prev = ear.prev;
  24567. const next = ear.next;
  24568. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24569. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24570. removeNode(ear);
  24571. // skipping the next vertex leads to less sliver triangles
  24572. ear = next.next;
  24573. stop = next.next;
  24574. continue;
  24575. }
  24576. ear = next;
  24577. // if we looped through the whole remaining polygon and can't find any more ears
  24578. if (ear === stop) {
  24579. // try filtering points and slicing again
  24580. if (!pass) {
  24581. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24582. // if this didn't work, try curing all small self-intersections locally
  24583. } else if (pass === 1) {
  24584. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24585. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24586. // as a last resort, try splitting the remaining polygon into two
  24587. } else if (pass === 2) {
  24588. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24589. }
  24590. break;
  24591. }
  24592. }
  24593. }
  24594. // check whether a polygon node forms a valid ear with adjacent nodes
  24595. function isEar(ear) {
  24596. const a = ear.prev,
  24597. b = ear,
  24598. c = ear.next;
  24599. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24600. // now make sure we don't have other points inside the potential ear
  24601. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24602. // triangle bbox
  24603. const x0 = Math.min(ax, bx, cx),
  24604. y0 = Math.min(ay, by, cy),
  24605. x1 = Math.max(ax, bx, cx),
  24606. y1 = Math.max(ay, by, cy);
  24607. let p = c.next;
  24608. while (p !== a) {
  24609. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24610. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24611. area(p.prev, p, p.next) >= 0) return false;
  24612. p = p.next;
  24613. }
  24614. return true;
  24615. }
  24616. function isEarHashed(ear, minX, minY, invSize) {
  24617. const a = ear.prev,
  24618. b = ear,
  24619. c = ear.next;
  24620. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24621. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24622. // triangle bbox
  24623. const x0 = Math.min(ax, bx, cx),
  24624. y0 = Math.min(ay, by, cy),
  24625. x1 = Math.max(ax, bx, cx),
  24626. y1 = Math.max(ay, by, cy);
  24627. // z-order range for the current triangle bbox;
  24628. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24629. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24630. let p = ear.prevZ,
  24631. n = ear.nextZ;
  24632. // look for points inside the triangle in both directions
  24633. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24634. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24635. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24636. p = p.prevZ;
  24637. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24638. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24639. n = n.nextZ;
  24640. }
  24641. // look for remaining points in decreasing z-order
  24642. while (p && p.z >= minZ) {
  24643. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24644. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24645. p = p.prevZ;
  24646. }
  24647. // look for remaining points in increasing z-order
  24648. while (n && n.z <= maxZ) {
  24649. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24650. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24651. n = n.nextZ;
  24652. }
  24653. return true;
  24654. }
  24655. // go through all polygon nodes and cure small local self-intersections
  24656. function cureLocalIntersections(start, triangles) {
  24657. let p = start;
  24658. do {
  24659. const a = p.prev,
  24660. b = p.next.next;
  24661. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24662. triangles.push(a.i, p.i, b.i);
  24663. // remove two nodes involved
  24664. removeNode(p);
  24665. removeNode(p.next);
  24666. p = start = b;
  24667. }
  24668. p = p.next;
  24669. } while (p !== start);
  24670. return filterPoints(p);
  24671. }
  24672. // try splitting polygon into two and triangulate them independently
  24673. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  24674. // look for a valid diagonal that divides the polygon into two
  24675. let a = start;
  24676. do {
  24677. let b = a.next.next;
  24678. while (b !== a.prev) {
  24679. if (a.i !== b.i && isValidDiagonal(a, b)) {
  24680. // split the polygon in two by the diagonal
  24681. let c = splitPolygon(a, b);
  24682. // filter colinear points around the cuts
  24683. a = filterPoints(a, a.next);
  24684. c = filterPoints(c, c.next);
  24685. // run earcut on each half
  24686. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  24687. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  24688. return;
  24689. }
  24690. b = b.next;
  24691. }
  24692. a = a.next;
  24693. } while (a !== start);
  24694. }
  24695. // link every hole into the outer loop, producing a single-ring polygon without holes
  24696. function eliminateHoles(data, holeIndices, outerNode, dim) {
  24697. const queue = [];
  24698. for (let i = 0, len = holeIndices.length; i < len; i++) {
  24699. const start = holeIndices[i] * dim;
  24700. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24701. const list = linkedList(data, start, end, dim, false);
  24702. if (list === list.next) list.steiner = true;
  24703. queue.push(getLeftmost(list));
  24704. }
  24705. queue.sort(compareXYSlope);
  24706. // process holes from left to right
  24707. for (let i = 0; i < queue.length; i++) {
  24708. outerNode = eliminateHole(queue[i], outerNode);
  24709. }
  24710. return outerNode;
  24711. }
  24712. function compareXYSlope(a, b) {
  24713. let result = a.x - b.x;
  24714. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  24715. // the bridge to the outer shell is always the point that they meet at.
  24716. if (result === 0) {
  24717. result = a.y - b.y;
  24718. if (result === 0) {
  24719. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  24720. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  24721. result = aSlope - bSlope;
  24722. }
  24723. }
  24724. return result;
  24725. }
  24726. // find a bridge between vertices that connects hole with an outer ring and link it
  24727. function eliminateHole(hole, outerNode) {
  24728. const bridge = findHoleBridge(hole, outerNode);
  24729. if (!bridge) {
  24730. return outerNode;
  24731. }
  24732. const bridgeReverse = splitPolygon(bridge, hole);
  24733. // filter collinear points around the cuts
  24734. filterPoints(bridgeReverse, bridgeReverse.next);
  24735. return filterPoints(bridge, bridge.next);
  24736. }
  24737. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  24738. function findHoleBridge(hole, outerNode) {
  24739. let p = outerNode;
  24740. const hx = hole.x;
  24741. const hy = hole.y;
  24742. let qx = -Infinity;
  24743. let m;
  24744. // find a segment intersected by a ray from the hole's leftmost point to the left;
  24745. // segment's endpoint with lesser x will be potential connection point
  24746. // unless they intersect at a vertex, then choose the vertex
  24747. if (equals(hole, p)) return p;
  24748. do {
  24749. if (equals(hole, p.next)) return p.next;
  24750. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  24751. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  24752. if (x <= hx && x > qx) {
  24753. qx = x;
  24754. m = p.x < p.next.x ? p : p.next;
  24755. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  24756. }
  24757. }
  24758. p = p.next;
  24759. } while (p !== outerNode);
  24760. if (!m) return null;
  24761. // look for points inside the triangle of hole point, segment intersection and endpoint;
  24762. // if there are no points found, we have a valid connection;
  24763. // otherwise choose the point of the minimum angle with the ray as connection point
  24764. const stop = m;
  24765. const mx = m.x;
  24766. const my = m.y;
  24767. let tanMin = Infinity;
  24768. p = m;
  24769. do {
  24770. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  24771. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  24772. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  24773. if (locallyInside(p, hole) &&
  24774. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  24775. m = p;
  24776. tanMin = tan;
  24777. }
  24778. }
  24779. p = p.next;
  24780. } while (p !== stop);
  24781. return m;
  24782. }
  24783. // whether sector in vertex m contains sector in vertex p in the same coordinates
  24784. function sectorContainsSector(m, p) {
  24785. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  24786. }
  24787. // interlink polygon nodes in z-order
  24788. function indexCurve(start, minX, minY, invSize) {
  24789. let p = start;
  24790. do {
  24791. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  24792. p.prevZ = p.prev;
  24793. p.nextZ = p.next;
  24794. p = p.next;
  24795. } while (p !== start);
  24796. p.prevZ.nextZ = null;
  24797. p.prevZ = null;
  24798. sortLinked(p);
  24799. }
  24800. // Simon Tatham's linked list merge sort algorithm
  24801. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  24802. function sortLinked(list) {
  24803. let numMerges;
  24804. let inSize = 1;
  24805. do {
  24806. let p = list;
  24807. let e;
  24808. list = null;
  24809. let tail = null;
  24810. numMerges = 0;
  24811. while (p) {
  24812. numMerges++;
  24813. let q = p;
  24814. let pSize = 0;
  24815. for (let i = 0; i < inSize; i++) {
  24816. pSize++;
  24817. q = q.nextZ;
  24818. if (!q) break;
  24819. }
  24820. let qSize = inSize;
  24821. while (pSize > 0 || (qSize > 0 && q)) {
  24822. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  24823. e = p;
  24824. p = p.nextZ;
  24825. pSize--;
  24826. } else {
  24827. e = q;
  24828. q = q.nextZ;
  24829. qSize--;
  24830. }
  24831. if (tail) tail.nextZ = e;
  24832. else list = e;
  24833. e.prevZ = tail;
  24834. tail = e;
  24835. }
  24836. p = q;
  24837. }
  24838. tail.nextZ = null;
  24839. inSize *= 2;
  24840. } while (numMerges > 1);
  24841. return list;
  24842. }
  24843. // z-order of a point given coords and inverse of the longer side of data bbox
  24844. function zOrder(x, y, minX, minY, invSize) {
  24845. // coords are transformed into non-negative 15-bit integer range
  24846. x = (x - minX) * invSize | 0;
  24847. y = (y - minY) * invSize | 0;
  24848. x = (x | (x << 8)) & 0x00FF00FF;
  24849. x = (x | (x << 4)) & 0x0F0F0F0F;
  24850. x = (x | (x << 2)) & 0x33333333;
  24851. x = (x | (x << 1)) & 0x55555555;
  24852. y = (y | (y << 8)) & 0x00FF00FF;
  24853. y = (y | (y << 4)) & 0x0F0F0F0F;
  24854. y = (y | (y << 2)) & 0x33333333;
  24855. y = (y | (y << 1)) & 0x55555555;
  24856. return x | (y << 1);
  24857. }
  24858. // find the leftmost node of a polygon ring
  24859. function getLeftmost(start) {
  24860. let p = start,
  24861. leftmost = start;
  24862. do {
  24863. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  24864. p = p.next;
  24865. } while (p !== start);
  24866. return leftmost;
  24867. }
  24868. // check if a point lies within a convex triangle
  24869. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  24870. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  24871. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  24872. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  24873. }
  24874. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  24875. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  24876. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  24877. }
  24878. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  24879. function isValidDiagonal(a, b) {
  24880. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  24881. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  24882. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  24883. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  24884. }
  24885. // signed area of a triangle
  24886. function area(p, q, r) {
  24887. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  24888. }
  24889. // check if two points are equal
  24890. function equals(p1, p2) {
  24891. return p1.x === p2.x && p1.y === p2.y;
  24892. }
  24893. // check if two segments intersect
  24894. function intersects(p1, q1, p2, q2) {
  24895. const o1 = sign(area(p1, q1, p2));
  24896. const o2 = sign(area(p1, q1, q2));
  24897. const o3 = sign(area(p2, q2, p1));
  24898. const o4 = sign(area(p2, q2, q1));
  24899. if (o1 !== o2 && o3 !== o4) return true; // general case
  24900. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  24901. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  24902. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  24903. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  24904. return false;
  24905. }
  24906. // for collinear points p, q, r, check if point q lies on segment pr
  24907. function onSegment(p, q, r) {
  24908. 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);
  24909. }
  24910. function sign(num) {
  24911. return num > 0 ? 1 : num < 0 ? -1 : 0;
  24912. }
  24913. // check if a polygon diagonal intersects any polygon segments
  24914. function intersectsPolygon(a, b) {
  24915. let p = a;
  24916. do {
  24917. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  24918. intersects(p, p.next, a, b)) return true;
  24919. p = p.next;
  24920. } while (p !== a);
  24921. return false;
  24922. }
  24923. // check if a polygon diagonal is locally inside the polygon
  24924. function locallyInside(a, b) {
  24925. return area(a.prev, a, a.next) < 0 ?
  24926. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  24927. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24928. }
  24929. // check if the middle point of a polygon diagonal is inside the polygon
  24930. function middleInside(a, b) {
  24931. let p = a;
  24932. let inside = false;
  24933. const px = (a.x + b.x) / 2;
  24934. const py = (a.y + b.y) / 2;
  24935. do {
  24936. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  24937. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  24938. inside = !inside;
  24939. p = p.next;
  24940. } while (p !== a);
  24941. return inside;
  24942. }
  24943. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24944. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24945. function splitPolygon(a, b) {
  24946. const a2 = createNode(a.i, a.x, a.y),
  24947. b2 = createNode(b.i, b.x, b.y),
  24948. an = a.next,
  24949. bp = b.prev;
  24950. a.next = b;
  24951. b.prev = a;
  24952. a2.next = an;
  24953. an.prev = a2;
  24954. b2.next = a2;
  24955. a2.prev = b2;
  24956. bp.next = b2;
  24957. b2.prev = bp;
  24958. return b2;
  24959. }
  24960. // create a node and optionally link it with previous one (in a circular doubly linked list)
  24961. function insertNode(i, x, y, last) {
  24962. const p = createNode(i, x, y);
  24963. if (!last) {
  24964. p.prev = p;
  24965. p.next = p;
  24966. } else {
  24967. p.next = last.next;
  24968. p.prev = last;
  24969. last.next.prev = p;
  24970. last.next = p;
  24971. }
  24972. return p;
  24973. }
  24974. function removeNode(p) {
  24975. p.next.prev = p.prev;
  24976. p.prev.next = p.next;
  24977. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24978. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24979. }
  24980. function createNode(i, x, y) {
  24981. return {
  24982. i, // vertex index in coordinates array
  24983. x, y, // vertex coordinates
  24984. prev: null, // previous and next vertex nodes in a polygon ring
  24985. next: null,
  24986. z: 0, // z-order curve value
  24987. prevZ: null, // previous and next nodes in z-order
  24988. nextZ: null,
  24989. steiner: false // indicates whether this is a steiner point
  24990. };
  24991. }
  24992. function signedArea(data, start, end, dim) {
  24993. let sum = 0;
  24994. for (let i = start, j = end - dim; i < end; i += dim) {
  24995. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24996. j = i;
  24997. }
  24998. return sum;
  24999. }
  25000. /**
  25001. * An implementation of the earcut polygon triangulation algorithm.
  25002. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25003. *
  25004. * @see https://github.com/mapbox/earcut
  25005. */
  25006. class Earcut {
  25007. /**
  25008. * Triangulates the given shape definition by returning an array of triangles.
  25009. *
  25010. * @param {Array<number>} data - An array with 2D points.
  25011. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25012. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25013. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25014. * representing vertex indices.
  25015. */
  25016. static triangulate( data, holeIndices, dim = 2 ) {
  25017. return earcut( data, holeIndices, dim );
  25018. }
  25019. }
  25020. /**
  25021. * A class containing utility functions for shapes.
  25022. *
  25023. * @hideconstructor
  25024. */
  25025. class ShapeUtils {
  25026. /**
  25027. * Calculate area of a ( 2D ) contour polygon.
  25028. *
  25029. * @param {Array<Vector2>} contour - An array of 2D points.
  25030. * @return {number} The area.
  25031. */
  25032. static area( contour ) {
  25033. const n = contour.length;
  25034. let a = 0.0;
  25035. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25036. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25037. }
  25038. return a * 0.5;
  25039. }
  25040. /**
  25041. * Returns `true` if the given contour uses a clockwise winding order.
  25042. *
  25043. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25044. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25045. */
  25046. static isClockWise( pts ) {
  25047. return ShapeUtils.area( pts ) < 0;
  25048. }
  25049. /**
  25050. * Triangulates the given shape definition.
  25051. *
  25052. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25053. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25054. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25055. */
  25056. static triangulateShape( contour, holes ) {
  25057. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25058. const holeIndices = []; // array of hole indices
  25059. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25060. removeDupEndPts( contour );
  25061. addContour( vertices, contour );
  25062. //
  25063. let holeIndex = contour.length;
  25064. holes.forEach( removeDupEndPts );
  25065. for ( let i = 0; i < holes.length; i ++ ) {
  25066. holeIndices.push( holeIndex );
  25067. holeIndex += holes[ i ].length;
  25068. addContour( vertices, holes[ i ] );
  25069. }
  25070. //
  25071. const triangles = Earcut.triangulate( vertices, holeIndices );
  25072. //
  25073. for ( let i = 0; i < triangles.length; i += 3 ) {
  25074. faces.push( triangles.slice( i, i + 3 ) );
  25075. }
  25076. return faces;
  25077. }
  25078. }
  25079. function removeDupEndPts( points ) {
  25080. const l = points.length;
  25081. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25082. points.pop();
  25083. }
  25084. }
  25085. function addContour( vertices, contour ) {
  25086. for ( let i = 0; i < contour.length; i ++ ) {
  25087. vertices.push( contour[ i ].x );
  25088. vertices.push( contour[ i ].y );
  25089. }
  25090. }
  25091. /**
  25092. * Creates extruded geometry from a path shape.
  25093. *
  25094. * ```js
  25095. * const length = 12, width = 8;
  25096. *
  25097. * const shape = new THREE.Shape();
  25098. * shape.moveTo( 0,0 );
  25099. * shape.lineTo( 0, width );
  25100. * shape.lineTo( length, width );
  25101. * shape.lineTo( length, 0 );
  25102. * shape.lineTo( 0, 0 );
  25103. *
  25104. * const geometry = new THREE.ExtrudeGeometry( shape );
  25105. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25106. * const mesh = new THREE.Mesh( geometry, material ) ;
  25107. * scene.add( mesh );
  25108. * ```
  25109. *
  25110. * @augments BufferGeometry
  25111. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25112. */
  25113. class ExtrudeGeometry extends BufferGeometry {
  25114. /**
  25115. * Constructs a new extrude geometry.
  25116. *
  25117. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25118. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25119. */
  25120. 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 = {} ) {
  25121. super();
  25122. this.type = 'ExtrudeGeometry';
  25123. /**
  25124. * Holds the constructor parameters that have been
  25125. * used to generate the geometry. Any modification
  25126. * after instantiation does not change the geometry.
  25127. *
  25128. * @type {Object}
  25129. */
  25130. this.parameters = {
  25131. shapes: shapes,
  25132. options: options
  25133. };
  25134. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25135. const scope = this;
  25136. const verticesArray = [];
  25137. const uvArray = [];
  25138. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25139. const shape = shapes[ i ];
  25140. addShape( shape );
  25141. }
  25142. // build geometry
  25143. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25144. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25145. this.computeVertexNormals();
  25146. // functions
  25147. function addShape( shape ) {
  25148. const placeholder = [];
  25149. // options
  25150. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25151. const steps = options.steps !== undefined ? options.steps : 1;
  25152. const depth = options.depth !== undefined ? options.depth : 1;
  25153. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25154. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25155. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25156. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25157. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25158. const extrudePath = options.extrudePath;
  25159. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25160. //
  25161. let extrudePts, extrudeByPath = false;
  25162. let splineTube, binormal, normal, position2;
  25163. if ( extrudePath ) {
  25164. extrudePts = extrudePath.getSpacedPoints( steps );
  25165. extrudeByPath = true;
  25166. bevelEnabled = false; // bevels not supported for path extrusion
  25167. // SETUP TNB variables
  25168. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25169. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25170. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25171. binormal = new Vector3();
  25172. normal = new Vector3();
  25173. position2 = new Vector3();
  25174. }
  25175. // Safeguards if bevels are not enabled
  25176. if ( ! bevelEnabled ) {
  25177. bevelSegments = 0;
  25178. bevelThickness = 0;
  25179. bevelSize = 0;
  25180. bevelOffset = 0;
  25181. }
  25182. // Variables initialization
  25183. const shapePoints = shape.extractPoints( curveSegments );
  25184. let vertices = shapePoints.shape;
  25185. const holes = shapePoints.holes;
  25186. const reverse = ! ShapeUtils.isClockWise( vertices );
  25187. if ( reverse ) {
  25188. vertices = vertices.reverse();
  25189. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25190. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25191. const ahole = holes[ h ];
  25192. if ( ShapeUtils.isClockWise( ahole ) ) {
  25193. holes[ h ] = ahole.reverse();
  25194. }
  25195. }
  25196. }
  25197. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  25198. * @param {Array<Vector2>} points
  25199. */
  25200. function mergeOverlappingPoints( points ) {
  25201. const THRESHOLD = 1e-10;
  25202. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25203. let prevPos = points[ 0 ];
  25204. for ( let i = 1; i <= points.length; i ++ ) {
  25205. const currentIndex = i % points.length;
  25206. const currentPos = points[ currentIndex ];
  25207. const dx = currentPos.x - prevPos.x;
  25208. const dy = currentPos.y - prevPos.y;
  25209. const distSq = dx * dx + dy * dy;
  25210. const scalingFactorSqrt = Math.max(
  25211. Math.abs( currentPos.x ),
  25212. Math.abs( currentPos.y ),
  25213. Math.abs( prevPos.x ),
  25214. Math.abs( prevPos.y )
  25215. );
  25216. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25217. if ( distSq <= thresholdSqScaled ) {
  25218. points.splice( currentIndex, 1 );
  25219. i --;
  25220. continue;
  25221. }
  25222. prevPos = currentPos;
  25223. }
  25224. }
  25225. mergeOverlappingPoints( vertices );
  25226. holes.forEach( mergeOverlappingPoints );
  25227. const numHoles = holes.length;
  25228. /* Vertices */
  25229. const contour = vertices; // vertices has all points but contour has only points of circumference
  25230. for ( let h = 0; h < numHoles; h ++ ) {
  25231. const ahole = holes[ h ];
  25232. vertices = vertices.concat( ahole );
  25233. }
  25234. function scalePt2( pt, vec, size ) {
  25235. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25236. return pt.clone().addScaledVector( vec, size );
  25237. }
  25238. const vlen = vertices.length;
  25239. // Find directions for point movement
  25240. function getBevelVec( inPt, inPrev, inNext ) {
  25241. // computes for inPt the corresponding point inPt' on a new contour
  25242. // shifted by 1 unit (length of normalized vector) to the left
  25243. // if we walk along contour clockwise, this new contour is outside the old one
  25244. //
  25245. // inPt' is the intersection of the two lines parallel to the two
  25246. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25247. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25248. // good reading for geometry algorithms (here: line-line intersection)
  25249. // http://geomalgorithms.com/a05-_intersect-1.html
  25250. const v_prev_x = inPt.x - inPrev.x,
  25251. v_prev_y = inPt.y - inPrev.y;
  25252. const v_next_x = inNext.x - inPt.x,
  25253. v_next_y = inNext.y - inPt.y;
  25254. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25255. // check for collinear edges
  25256. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25257. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25258. // not collinear
  25259. // length of vectors for normalizing
  25260. const v_prev_len = Math.sqrt( v_prev_lensq );
  25261. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25262. // shift adjacent points by unit vectors to the left
  25263. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25264. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25265. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25266. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25267. // scaling factor for v_prev to intersection point
  25268. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25269. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25270. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25271. // vector from inPt to intersection point
  25272. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25273. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25274. // Don't normalize!, otherwise sharp corners become ugly
  25275. // but prevent crazy spikes
  25276. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25277. if ( v_trans_lensq <= 2 ) {
  25278. return new Vector2( v_trans_x, v_trans_y );
  25279. } else {
  25280. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25281. }
  25282. } else {
  25283. // handle special case of collinear edges
  25284. let direction_eq = false; // assumes: opposite
  25285. if ( v_prev_x > Number.EPSILON ) {
  25286. if ( v_next_x > Number.EPSILON ) {
  25287. direction_eq = true;
  25288. }
  25289. } else {
  25290. if ( v_prev_x < - Number.EPSILON ) {
  25291. if ( v_next_x < - Number.EPSILON ) {
  25292. direction_eq = true;
  25293. }
  25294. } else {
  25295. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25296. direction_eq = true;
  25297. }
  25298. }
  25299. }
  25300. if ( direction_eq ) {
  25301. // log("Warning: lines are a straight sequence");
  25302. v_trans_x = - v_prev_y;
  25303. v_trans_y = v_prev_x;
  25304. shrink_by = Math.sqrt( v_prev_lensq );
  25305. } else {
  25306. // log("Warning: lines are a straight spike");
  25307. v_trans_x = v_prev_x;
  25308. v_trans_y = v_prev_y;
  25309. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25310. }
  25311. }
  25312. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25313. }
  25314. const contourMovements = [];
  25315. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25316. if ( j === il ) j = 0;
  25317. if ( k === il ) k = 0;
  25318. // (j)---(i)---(k)
  25319. // log('i,j,k', i, j , k)
  25320. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25321. }
  25322. const holesMovements = [];
  25323. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25324. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25325. const ahole = holes[ h ];
  25326. oneHoleMovements = [];
  25327. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25328. if ( j === il ) j = 0;
  25329. if ( k === il ) k = 0;
  25330. // (j)---(i)---(k)
  25331. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25332. }
  25333. holesMovements.push( oneHoleMovements );
  25334. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25335. }
  25336. let faces;
  25337. if ( bevelSegments === 0 ) {
  25338. faces = ShapeUtils.triangulateShape( contour, holes );
  25339. } else {
  25340. const contractedContourVertices = [];
  25341. const expandedHoleVertices = [];
  25342. // Loop bevelSegments, 1 for the front, 1 for the back
  25343. for ( let b = 0; b < bevelSegments; b ++ ) {
  25344. //for ( b = bevelSegments; b > 0; b -- ) {
  25345. const t = b / bevelSegments;
  25346. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25347. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25348. // contract shape
  25349. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25350. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25351. v( vert.x, vert.y, - z );
  25352. if ( t === 0 ) contractedContourVertices.push( vert );
  25353. }
  25354. // expand holes
  25355. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25356. const ahole = holes[ h ];
  25357. oneHoleMovements = holesMovements[ h ];
  25358. const oneHoleVertices = [];
  25359. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25360. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25361. v( vert.x, vert.y, - z );
  25362. if ( t === 0 ) oneHoleVertices.push( vert );
  25363. }
  25364. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25365. }
  25366. }
  25367. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25368. }
  25369. const flen = faces.length;
  25370. const bs = bevelSize + bevelOffset;
  25371. // Back facing vertices
  25372. for ( let i = 0; i < vlen; i ++ ) {
  25373. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25374. if ( ! extrudeByPath ) {
  25375. v( vert.x, vert.y, 0 );
  25376. } else {
  25377. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25378. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25379. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25380. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25381. v( position2.x, position2.y, position2.z );
  25382. }
  25383. }
  25384. // Add stepped vertices...
  25385. // Including front facing vertices
  25386. for ( let s = 1; s <= steps; s ++ ) {
  25387. for ( let i = 0; i < vlen; i ++ ) {
  25388. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25389. if ( ! extrudeByPath ) {
  25390. v( vert.x, vert.y, depth / steps * s );
  25391. } else {
  25392. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25393. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25394. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25395. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25396. v( position2.x, position2.y, position2.z );
  25397. }
  25398. }
  25399. }
  25400. // Add bevel segments planes
  25401. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25402. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25403. const t = b / bevelSegments;
  25404. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25405. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25406. // contract shape
  25407. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25408. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25409. v( vert.x, vert.y, depth + z );
  25410. }
  25411. // expand holes
  25412. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25413. const ahole = holes[ h ];
  25414. oneHoleMovements = holesMovements[ h ];
  25415. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25416. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25417. if ( ! extrudeByPath ) {
  25418. v( vert.x, vert.y, depth + z );
  25419. } else {
  25420. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25421. }
  25422. }
  25423. }
  25424. }
  25425. /* Faces */
  25426. // Top and bottom faces
  25427. buildLidFaces();
  25428. // Sides faces
  25429. buildSideFaces();
  25430. ///// Internal functions
  25431. function buildLidFaces() {
  25432. const start = verticesArray.length / 3;
  25433. if ( bevelEnabled ) {
  25434. let layer = 0; // steps + 1
  25435. let offset = vlen * layer;
  25436. // Bottom faces
  25437. for ( let i = 0; i < flen; i ++ ) {
  25438. const face = faces[ i ];
  25439. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25440. }
  25441. layer = steps + bevelSegments * 2;
  25442. offset = vlen * layer;
  25443. // Top faces
  25444. for ( let i = 0; i < flen; i ++ ) {
  25445. const face = faces[ i ];
  25446. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25447. }
  25448. } else {
  25449. // Bottom faces
  25450. for ( let i = 0; i < flen; i ++ ) {
  25451. const face = faces[ i ];
  25452. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25453. }
  25454. // Top faces
  25455. for ( let i = 0; i < flen; i ++ ) {
  25456. const face = faces[ i ];
  25457. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25458. }
  25459. }
  25460. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25461. }
  25462. // Create faces for the z-sides of the shape
  25463. function buildSideFaces() {
  25464. const start = verticesArray.length / 3;
  25465. let layeroffset = 0;
  25466. sidewalls( contour, layeroffset );
  25467. layeroffset += contour.length;
  25468. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25469. const ahole = holes[ h ];
  25470. sidewalls( ahole, layeroffset );
  25471. //, true
  25472. layeroffset += ahole.length;
  25473. }
  25474. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25475. }
  25476. function sidewalls( contour, layeroffset ) {
  25477. let i = contour.length;
  25478. while ( -- i >= 0 ) {
  25479. const j = i;
  25480. let k = i - 1;
  25481. if ( k < 0 ) k = contour.length - 1;
  25482. //log('b', i,j, i-1, k,vertices.length);
  25483. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25484. const slen1 = vlen * s;
  25485. const slen2 = vlen * ( s + 1 );
  25486. const a = layeroffset + j + slen1,
  25487. b = layeroffset + k + slen1,
  25488. c = layeroffset + k + slen2,
  25489. d = layeroffset + j + slen2;
  25490. f4( a, b, c, d );
  25491. }
  25492. }
  25493. }
  25494. function v( x, y, z ) {
  25495. placeholder.push( x );
  25496. placeholder.push( y );
  25497. placeholder.push( z );
  25498. }
  25499. function f3( a, b, c ) {
  25500. addVertex( a );
  25501. addVertex( b );
  25502. addVertex( c );
  25503. const nextIndex = verticesArray.length / 3;
  25504. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25505. addUV( uvs[ 0 ] );
  25506. addUV( uvs[ 1 ] );
  25507. addUV( uvs[ 2 ] );
  25508. }
  25509. function f4( a, b, c, d ) {
  25510. addVertex( a );
  25511. addVertex( b );
  25512. addVertex( d );
  25513. addVertex( b );
  25514. addVertex( c );
  25515. addVertex( d );
  25516. const nextIndex = verticesArray.length / 3;
  25517. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25518. addUV( uvs[ 0 ] );
  25519. addUV( uvs[ 1 ] );
  25520. addUV( uvs[ 3 ] );
  25521. addUV( uvs[ 1 ] );
  25522. addUV( uvs[ 2 ] );
  25523. addUV( uvs[ 3 ] );
  25524. }
  25525. function addVertex( index ) {
  25526. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25527. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25528. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25529. }
  25530. function addUV( vector2 ) {
  25531. uvArray.push( vector2.x );
  25532. uvArray.push( vector2.y );
  25533. }
  25534. }
  25535. }
  25536. copy( source ) {
  25537. super.copy( source );
  25538. this.parameters = Object.assign( {}, source.parameters );
  25539. return this;
  25540. }
  25541. toJSON() {
  25542. const data = super.toJSON();
  25543. const shapes = this.parameters.shapes;
  25544. const options = this.parameters.options;
  25545. return toJSON$1( shapes, options, data );
  25546. }
  25547. /**
  25548. * Factory method for creating an instance of this class from the given
  25549. * JSON object.
  25550. *
  25551. * @param {Object} data - A JSON object representing the serialized geometry.
  25552. * @param {Array<Shape>} shapes - An array of shapes.
  25553. * @return {ExtrudeGeometry} A new instance.
  25554. */
  25555. static fromJSON( data, shapes ) {
  25556. const geometryShapes = [];
  25557. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25558. const shape = shapes[ data.shapes[ j ] ];
  25559. geometryShapes.push( shape );
  25560. }
  25561. const extrudePath = data.options.extrudePath;
  25562. if ( extrudePath !== undefined ) {
  25563. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25564. }
  25565. return new ExtrudeGeometry( geometryShapes, data.options );
  25566. }
  25567. }
  25568. const WorldUVGenerator = {
  25569. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25570. const a_x = vertices[ indexA * 3 ];
  25571. const a_y = vertices[ indexA * 3 + 1 ];
  25572. const b_x = vertices[ indexB * 3 ];
  25573. const b_y = vertices[ indexB * 3 + 1 ];
  25574. const c_x = vertices[ indexC * 3 ];
  25575. const c_y = vertices[ indexC * 3 + 1 ];
  25576. return [
  25577. new Vector2( a_x, a_y ),
  25578. new Vector2( b_x, b_y ),
  25579. new Vector2( c_x, c_y )
  25580. ];
  25581. },
  25582. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25583. const a_x = vertices[ indexA * 3 ];
  25584. const a_y = vertices[ indexA * 3 + 1 ];
  25585. const a_z = vertices[ indexA * 3 + 2 ];
  25586. const b_x = vertices[ indexB * 3 ];
  25587. const b_y = vertices[ indexB * 3 + 1 ];
  25588. const b_z = vertices[ indexB * 3 + 2 ];
  25589. const c_x = vertices[ indexC * 3 ];
  25590. const c_y = vertices[ indexC * 3 + 1 ];
  25591. const c_z = vertices[ indexC * 3 + 2 ];
  25592. const d_x = vertices[ indexD * 3 ];
  25593. const d_y = vertices[ indexD * 3 + 1 ];
  25594. const d_z = vertices[ indexD * 3 + 2 ];
  25595. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25596. return [
  25597. new Vector2( a_x, 1 - a_z ),
  25598. new Vector2( b_x, 1 - b_z ),
  25599. new Vector2( c_x, 1 - c_z ),
  25600. new Vector2( d_x, 1 - d_z )
  25601. ];
  25602. } else {
  25603. return [
  25604. new Vector2( a_y, 1 - a_z ),
  25605. new Vector2( b_y, 1 - b_z ),
  25606. new Vector2( c_y, 1 - c_z ),
  25607. new Vector2( d_y, 1 - d_z )
  25608. ];
  25609. }
  25610. }
  25611. };
  25612. function toJSON$1( shapes, options, data ) {
  25613. data.shapes = [];
  25614. if ( Array.isArray( shapes ) ) {
  25615. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25616. const shape = shapes[ i ];
  25617. data.shapes.push( shape.uuid );
  25618. }
  25619. } else {
  25620. data.shapes.push( shapes.uuid );
  25621. }
  25622. data.options = Object.assign( {}, options );
  25623. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25624. return data;
  25625. }
  25626. /**
  25627. * A geometry class for representing an icosahedron.
  25628. *
  25629. * ```js
  25630. * const geometry = new THREE.IcosahedronGeometry();
  25631. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25632. * const icosahedron = new THREE.Mesh( geometry, material );
  25633. * scene.add( icosahedron );
  25634. * ```
  25635. *
  25636. * @augments PolyhedronGeometry
  25637. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  25638. */
  25639. class IcosahedronGeometry extends PolyhedronGeometry {
  25640. /**
  25641. * Constructs a new icosahedron geometry.
  25642. *
  25643. * @param {number} [radius=1] - Radius of the icosahedron.
  25644. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25645. */
  25646. constructor( radius = 1, detail = 0 ) {
  25647. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25648. const vertices = [
  25649. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25650. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  25651. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  25652. ];
  25653. const indices = [
  25654. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25655. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25656. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25657. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25658. ];
  25659. super( vertices, indices, radius, detail );
  25660. this.type = 'IcosahedronGeometry';
  25661. /**
  25662. * Holds the constructor parameters that have been
  25663. * used to generate the geometry. Any modification
  25664. * after instantiation does not change the geometry.
  25665. *
  25666. * @type {Object}
  25667. */
  25668. this.parameters = {
  25669. radius: radius,
  25670. detail: detail
  25671. };
  25672. }
  25673. /**
  25674. * Factory method for creating an instance of this class from the given
  25675. * JSON object.
  25676. *
  25677. * @param {Object} data - A JSON object representing the serialized geometry.
  25678. * @return {IcosahedronGeometry} A new instance.
  25679. */
  25680. static fromJSON( data ) {
  25681. return new IcosahedronGeometry( data.radius, data.detail );
  25682. }
  25683. }
  25684. /**
  25685. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  25686. *
  25687. * ```js
  25688. * const points = [];
  25689. * for ( let i = 0; i < 10; i ++ ) {
  25690. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  25691. * }
  25692. * const geometry = new THREE.LatheGeometry( points );
  25693. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25694. * const lathe = new THREE.Mesh( geometry, material );
  25695. * scene.add( lathe );
  25696. * ```
  25697. *
  25698. * @augments BufferGeometry
  25699. * @demo scenes/geometry-browser.html#LatheGeometry
  25700. */
  25701. class LatheGeometry extends BufferGeometry {
  25702. /**
  25703. * Constructs a new lathe geometry.
  25704. *
  25705. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  25706. * must be greater than zero.
  25707. * @param {number} [segments=12] - The number of circumference segments to generate.
  25708. * @param {number} [phiStart=0] - The starting angle in radians.
  25709. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  25710. * closed lathe, less than 2PI is a portion.
  25711. */
  25712. 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 ) {
  25713. super();
  25714. this.type = 'LatheGeometry';
  25715. /**
  25716. * Holds the constructor parameters that have been
  25717. * used to generate the geometry. Any modification
  25718. * after instantiation does not change the geometry.
  25719. *
  25720. * @type {Object}
  25721. */
  25722. this.parameters = {
  25723. points: points,
  25724. segments: segments,
  25725. phiStart: phiStart,
  25726. phiLength: phiLength
  25727. };
  25728. segments = Math.floor( segments );
  25729. // clamp phiLength so it's in range of [ 0, 2PI ]
  25730. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  25731. // buffers
  25732. const indices = [];
  25733. const vertices = [];
  25734. const uvs = [];
  25735. const initNormals = [];
  25736. const normals = [];
  25737. // helper variables
  25738. const inverseSegments = 1.0 / segments;
  25739. const vertex = new Vector3();
  25740. const uv = new Vector2();
  25741. const normal = new Vector3();
  25742. const curNormal = new Vector3();
  25743. const prevNormal = new Vector3();
  25744. let dx = 0;
  25745. let dy = 0;
  25746. // pre-compute normals for initial "meridian"
  25747. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25748. switch ( j ) {
  25749. case 0: // special handling for 1st vertex on path
  25750. dx = points[ j + 1 ].x - points[ j ].x;
  25751. dy = points[ j + 1 ].y - points[ j ].y;
  25752. normal.x = dy * 1.0;
  25753. normal.y = - dx;
  25754. normal.z = dy * 0.0;
  25755. prevNormal.copy( normal );
  25756. normal.normalize();
  25757. initNormals.push( normal.x, normal.y, normal.z );
  25758. break;
  25759. case ( points.length - 1 ): // special handling for last Vertex on path
  25760. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  25761. break;
  25762. default: // default handling for all vertices in between
  25763. dx = points[ j + 1 ].x - points[ j ].x;
  25764. dy = points[ j + 1 ].y - points[ j ].y;
  25765. normal.x = dy * 1.0;
  25766. normal.y = - dx;
  25767. normal.z = dy * 0.0;
  25768. curNormal.copy( normal );
  25769. normal.x += prevNormal.x;
  25770. normal.y += prevNormal.y;
  25771. normal.z += prevNormal.z;
  25772. normal.normalize();
  25773. initNormals.push( normal.x, normal.y, normal.z );
  25774. prevNormal.copy( curNormal );
  25775. }
  25776. }
  25777. // generate vertices, uvs and normals
  25778. for ( let i = 0; i <= segments; i ++ ) {
  25779. const phi = phiStart + i * inverseSegments * phiLength;
  25780. const sin = Math.sin( phi );
  25781. const cos = Math.cos( phi );
  25782. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  25783. // vertex
  25784. vertex.x = points[ j ].x * sin;
  25785. vertex.y = points[ j ].y;
  25786. vertex.z = points[ j ].x * cos;
  25787. vertices.push( vertex.x, vertex.y, vertex.z );
  25788. // uv
  25789. uv.x = i / segments;
  25790. uv.y = j / ( points.length - 1 );
  25791. uvs.push( uv.x, uv.y );
  25792. // normal
  25793. const x = initNormals[ 3 * j + 0 ] * sin;
  25794. const y = initNormals[ 3 * j + 1 ];
  25795. const z = initNormals[ 3 * j + 0 ] * cos;
  25796. normals.push( x, y, z );
  25797. }
  25798. }
  25799. // indices
  25800. for ( let i = 0; i < segments; i ++ ) {
  25801. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  25802. const base = j + i * points.length;
  25803. const a = base;
  25804. const b = base + points.length;
  25805. const c = base + points.length + 1;
  25806. const d = base + 1;
  25807. // faces
  25808. indices.push( a, b, d );
  25809. indices.push( c, d, b );
  25810. }
  25811. }
  25812. // build geometry
  25813. this.setIndex( indices );
  25814. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25815. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25816. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25817. }
  25818. copy( source ) {
  25819. super.copy( source );
  25820. this.parameters = Object.assign( {}, source.parameters );
  25821. return this;
  25822. }
  25823. /**
  25824. * Factory method for creating an instance of this class from the given
  25825. * JSON object.
  25826. *
  25827. * @param {Object} data - A JSON object representing the serialized geometry.
  25828. * @return {LatheGeometry} A new instance.
  25829. */
  25830. static fromJSON( data ) {
  25831. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  25832. }
  25833. }
  25834. /**
  25835. * A geometry class for representing an octahedron.
  25836. *
  25837. * ```js
  25838. * const geometry = new THREE.OctahedronGeometry();
  25839. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25840. * const octahedron = new THREE.Mesh( geometry, material );
  25841. * scene.add( octahedron );
  25842. * ```
  25843. *
  25844. * @augments PolyhedronGeometry
  25845. * @demo scenes/geometry-browser.html#OctahedronGeometry
  25846. */
  25847. class OctahedronGeometry extends PolyhedronGeometry {
  25848. /**
  25849. * Constructs a new octahedron geometry.
  25850. *
  25851. * @param {number} [radius=1] - Radius of the octahedron.
  25852. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  25853. */
  25854. constructor( radius = 1, detail = 0 ) {
  25855. const vertices = [
  25856. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  25857. 0, -1, 0, 0, 0, 1, 0, 0, -1
  25858. ];
  25859. const indices = [
  25860. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  25861. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  25862. 1, 3, 4, 1, 4, 2
  25863. ];
  25864. super( vertices, indices, radius, detail );
  25865. this.type = 'OctahedronGeometry';
  25866. /**
  25867. * Holds the constructor parameters that have been
  25868. * used to generate the geometry. Any modification
  25869. * after instantiation does not change the geometry.
  25870. *
  25871. * @type {Object}
  25872. */
  25873. this.parameters = {
  25874. radius: radius,
  25875. detail: detail
  25876. };
  25877. }
  25878. /**
  25879. * Factory method for creating an instance of this class from the given
  25880. * JSON object.
  25881. *
  25882. * @param {Object} data - A JSON object representing the serialized geometry.
  25883. * @return {OctahedronGeometry} A new instance.
  25884. */
  25885. static fromJSON( data ) {
  25886. return new OctahedronGeometry( data.radius, data.detail );
  25887. }
  25888. }
  25889. /**
  25890. * A geometry class for representing a plane.
  25891. *
  25892. * ```js
  25893. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  25894. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25895. * const plane = new THREE.Mesh( geometry, material );
  25896. * scene.add( plane );
  25897. * ```
  25898. *
  25899. * @augments BufferGeometry
  25900. * @demo scenes/geometry-browser.html#PlaneGeometry
  25901. */
  25902. class PlaneGeometry extends BufferGeometry {
  25903. /**
  25904. * Constructs a new plane geometry.
  25905. *
  25906. * @param {number} [width=1] - The width along the X axis.
  25907. * @param {number} [height=1] - The height along the Y axis
  25908. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  25909. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  25910. */
  25911. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  25912. super();
  25913. this.type = 'PlaneGeometry';
  25914. /**
  25915. * Holds the constructor parameters that have been
  25916. * used to generate the geometry. Any modification
  25917. * after instantiation does not change the geometry.
  25918. *
  25919. * @type {Object}
  25920. */
  25921. this.parameters = {
  25922. width: width,
  25923. height: height,
  25924. widthSegments: widthSegments,
  25925. heightSegments: heightSegments
  25926. };
  25927. const width_half = width / 2;
  25928. const height_half = height / 2;
  25929. const gridX = Math.floor( widthSegments );
  25930. const gridY = Math.floor( heightSegments );
  25931. const gridX1 = gridX + 1;
  25932. const gridY1 = gridY + 1;
  25933. const segment_width = width / gridX;
  25934. const segment_height = height / gridY;
  25935. //
  25936. const indices = [];
  25937. const vertices = [];
  25938. const normals = [];
  25939. const uvs = [];
  25940. for ( let iy = 0; iy < gridY1; iy ++ ) {
  25941. const y = iy * segment_height - height_half;
  25942. for ( let ix = 0; ix < gridX1; ix ++ ) {
  25943. const x = ix * segment_width - width_half;
  25944. vertices.push( x, - y, 0 );
  25945. normals.push( 0, 0, 1 );
  25946. uvs.push( ix / gridX );
  25947. uvs.push( 1 - ( iy / gridY ) );
  25948. }
  25949. }
  25950. for ( let iy = 0; iy < gridY; iy ++ ) {
  25951. for ( let ix = 0; ix < gridX; ix ++ ) {
  25952. const a = ix + gridX1 * iy;
  25953. const b = ix + gridX1 * ( iy + 1 );
  25954. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  25955. const d = ( ix + 1 ) + gridX1 * iy;
  25956. indices.push( a, b, d );
  25957. indices.push( b, c, d );
  25958. }
  25959. }
  25960. this.setIndex( indices );
  25961. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  25962. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  25963. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  25964. }
  25965. copy( source ) {
  25966. super.copy( source );
  25967. this.parameters = Object.assign( {}, source.parameters );
  25968. return this;
  25969. }
  25970. /**
  25971. * Factory method for creating an instance of this class from the given
  25972. * JSON object.
  25973. *
  25974. * @param {Object} data - A JSON object representing the serialized geometry.
  25975. * @return {PlaneGeometry} A new instance.
  25976. */
  25977. static fromJSON( data ) {
  25978. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  25979. }
  25980. }
  25981. /**
  25982. * A class for generating a two-dimensional ring geometry.
  25983. *
  25984. * ```js
  25985. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  25986. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  25987. * const mesh = new THREE.Mesh( geometry, material );
  25988. * scene.add( mesh );
  25989. * ```
  25990. *
  25991. * @augments BufferGeometry
  25992. * @demo scenes/geometry-browser.html#RingGeometry
  25993. */
  25994. class RingGeometry extends BufferGeometry {
  25995. /**
  25996. * Constructs a new ring geometry.
  25997. *
  25998. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  25999. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26000. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26001. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26002. * @param {number} [thetaStart=0] - Starting angle in radians.
  26003. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26004. */
  26005. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26006. super();
  26007. this.type = 'RingGeometry';
  26008. /**
  26009. * Holds the constructor parameters that have been
  26010. * used to generate the geometry. Any modification
  26011. * after instantiation does not change the geometry.
  26012. *
  26013. * @type {Object}
  26014. */
  26015. this.parameters = {
  26016. innerRadius: innerRadius,
  26017. outerRadius: outerRadius,
  26018. thetaSegments: thetaSegments,
  26019. phiSegments: phiSegments,
  26020. thetaStart: thetaStart,
  26021. thetaLength: thetaLength
  26022. };
  26023. thetaSegments = Math.max( 3, thetaSegments );
  26024. phiSegments = Math.max( 1, phiSegments );
  26025. // buffers
  26026. const indices = [];
  26027. const vertices = [];
  26028. const normals = [];
  26029. const uvs = [];
  26030. // some helper variables
  26031. let radius = innerRadius;
  26032. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26033. const vertex = new Vector3();
  26034. const uv = new Vector2();
  26035. // generate vertices, normals and uvs
  26036. for ( let j = 0; j <= phiSegments; j ++ ) {
  26037. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26038. // values are generate from the inside of the ring to the outside
  26039. const segment = thetaStart + i / thetaSegments * thetaLength;
  26040. // vertex
  26041. vertex.x = radius * Math.cos( segment );
  26042. vertex.y = radius * Math.sin( segment );
  26043. vertices.push( vertex.x, vertex.y, vertex.z );
  26044. // normal
  26045. normals.push( 0, 0, 1 );
  26046. // uv
  26047. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26048. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26049. uvs.push( uv.x, uv.y );
  26050. }
  26051. // increase the radius for next row of vertices
  26052. radius += radiusStep;
  26053. }
  26054. // indices
  26055. for ( let j = 0; j < phiSegments; j ++ ) {
  26056. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26057. for ( let i = 0; i < thetaSegments; i ++ ) {
  26058. const segment = i + thetaSegmentLevel;
  26059. const a = segment;
  26060. const b = segment + thetaSegments + 1;
  26061. const c = segment + thetaSegments + 2;
  26062. const d = segment + 1;
  26063. // faces
  26064. indices.push( a, b, d );
  26065. indices.push( b, c, d );
  26066. }
  26067. }
  26068. // build geometry
  26069. this.setIndex( indices );
  26070. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26071. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26072. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26073. }
  26074. copy( source ) {
  26075. super.copy( source );
  26076. this.parameters = Object.assign( {}, source.parameters );
  26077. return this;
  26078. }
  26079. /**
  26080. * Factory method for creating an instance of this class from the given
  26081. * JSON object.
  26082. *
  26083. * @param {Object} data - A JSON object representing the serialized geometry.
  26084. * @return {RingGeometry} A new instance.
  26085. */
  26086. static fromJSON( data ) {
  26087. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26088. }
  26089. }
  26090. /**
  26091. * Creates an one-sided polygonal geometry from one or more path shapes.
  26092. *
  26093. * ```js
  26094. * const arcShape = new THREE.Shape()
  26095. * .moveTo( 5, 1 )
  26096. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26097. *
  26098. * const geometry = new THREE.ShapeGeometry( arcShape );
  26099. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26100. * const mesh = new THREE.Mesh( geometry, material ) ;
  26101. * scene.add( mesh );
  26102. * ```
  26103. *
  26104. * @augments BufferGeometry
  26105. * @demo scenes/geometry-browser.html#ShapeGeometry
  26106. */
  26107. class ShapeGeometry extends BufferGeometry {
  26108. /**
  26109. * Constructs a new shape geometry.
  26110. *
  26111. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26112. * @param {number} [curveSegments=12] - Number of segments per shape.
  26113. */
  26114. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26115. super();
  26116. this.type = 'ShapeGeometry';
  26117. /**
  26118. * Holds the constructor parameters that have been
  26119. * used to generate the geometry. Any modification
  26120. * after instantiation does not change the geometry.
  26121. *
  26122. * @type {Object}
  26123. */
  26124. this.parameters = {
  26125. shapes: shapes,
  26126. curveSegments: curveSegments
  26127. };
  26128. // buffers
  26129. const indices = [];
  26130. const vertices = [];
  26131. const normals = [];
  26132. const uvs = [];
  26133. // helper variables
  26134. let groupStart = 0;
  26135. let groupCount = 0;
  26136. // allow single and array values for "shapes" parameter
  26137. if ( Array.isArray( shapes ) === false ) {
  26138. addShape( shapes );
  26139. } else {
  26140. for ( let i = 0; i < shapes.length; i ++ ) {
  26141. addShape( shapes[ i ] );
  26142. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26143. groupStart += groupCount;
  26144. groupCount = 0;
  26145. }
  26146. }
  26147. // build geometry
  26148. this.setIndex( indices );
  26149. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26150. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26151. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26152. // helper functions
  26153. function addShape( shape ) {
  26154. const indexOffset = vertices.length / 3;
  26155. const points = shape.extractPoints( curveSegments );
  26156. let shapeVertices = points.shape;
  26157. const shapeHoles = points.holes;
  26158. // check direction of vertices
  26159. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26160. shapeVertices = shapeVertices.reverse();
  26161. }
  26162. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26163. const shapeHole = shapeHoles[ i ];
  26164. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26165. shapeHoles[ i ] = shapeHole.reverse();
  26166. }
  26167. }
  26168. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26169. // join vertices of inner and outer paths to a single array
  26170. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26171. const shapeHole = shapeHoles[ i ];
  26172. shapeVertices = shapeVertices.concat( shapeHole );
  26173. }
  26174. // vertices, normals, uvs
  26175. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26176. const vertex = shapeVertices[ i ];
  26177. vertices.push( vertex.x, vertex.y, 0 );
  26178. normals.push( 0, 0, 1 );
  26179. uvs.push( vertex.x, vertex.y ); // world uvs
  26180. }
  26181. // indices
  26182. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26183. const face = faces[ i ];
  26184. const a = face[ 0 ] + indexOffset;
  26185. const b = face[ 1 ] + indexOffset;
  26186. const c = face[ 2 ] + indexOffset;
  26187. indices.push( a, b, c );
  26188. groupCount += 3;
  26189. }
  26190. }
  26191. }
  26192. copy( source ) {
  26193. super.copy( source );
  26194. this.parameters = Object.assign( {}, source.parameters );
  26195. return this;
  26196. }
  26197. toJSON() {
  26198. const data = super.toJSON();
  26199. const shapes = this.parameters.shapes;
  26200. return toJSON( shapes, data );
  26201. }
  26202. /**
  26203. * Factory method for creating an instance of this class from the given
  26204. * JSON object.
  26205. *
  26206. * @param {Object} data - A JSON object representing the serialized geometry.
  26207. * @param {Array<Shape>} shapes - An array of shapes.
  26208. * @return {ShapeGeometry} A new instance.
  26209. */
  26210. static fromJSON( data, shapes ) {
  26211. const geometryShapes = [];
  26212. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26213. const shape = shapes[ data.shapes[ j ] ];
  26214. geometryShapes.push( shape );
  26215. }
  26216. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26217. }
  26218. }
  26219. function toJSON( shapes, data ) {
  26220. data.shapes = [];
  26221. if ( Array.isArray( shapes ) ) {
  26222. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26223. const shape = shapes[ i ];
  26224. data.shapes.push( shape.uuid );
  26225. }
  26226. } else {
  26227. data.shapes.push( shapes.uuid );
  26228. }
  26229. return data;
  26230. }
  26231. /**
  26232. * A class for generating a sphere geometry.
  26233. *
  26234. * ```js
  26235. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26236. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26237. * const sphere = new THREE.Mesh( geometry, material );
  26238. * scene.add( sphere );
  26239. * ```
  26240. *
  26241. * @augments BufferGeometry
  26242. * @demo scenes/geometry-browser.html#SphereGeometry
  26243. */
  26244. class SphereGeometry extends BufferGeometry {
  26245. /**
  26246. * Constructs a new sphere geometry.
  26247. *
  26248. * @param {number} [radius=1] - The sphere radius.
  26249. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26250. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26251. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26252. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26253. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26254. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26255. */
  26256. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26257. super();
  26258. this.type = 'SphereGeometry';
  26259. /**
  26260. * Holds the constructor parameters that have been
  26261. * used to generate the geometry. Any modification
  26262. * after instantiation does not change the geometry.
  26263. *
  26264. * @type {Object}
  26265. */
  26266. this.parameters = {
  26267. radius: radius,
  26268. widthSegments: widthSegments,
  26269. heightSegments: heightSegments,
  26270. phiStart: phiStart,
  26271. phiLength: phiLength,
  26272. thetaStart: thetaStart,
  26273. thetaLength: thetaLength
  26274. };
  26275. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26276. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26277. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26278. let index = 0;
  26279. const grid = [];
  26280. const vertex = new Vector3();
  26281. const normal = new Vector3();
  26282. // buffers
  26283. const indices = [];
  26284. const vertices = [];
  26285. const normals = [];
  26286. const uvs = [];
  26287. // generate vertices, normals and uvs
  26288. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26289. const verticesRow = [];
  26290. const v = iy / heightSegments;
  26291. // special case for the poles
  26292. let uOffset = 0;
  26293. if ( iy === 0 && thetaStart === 0 ) {
  26294. uOffset = 0.5 / widthSegments;
  26295. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26296. uOffset = -0.5 / widthSegments;
  26297. }
  26298. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26299. const u = ix / widthSegments;
  26300. // vertex
  26301. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26302. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26303. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26304. vertices.push( vertex.x, vertex.y, vertex.z );
  26305. // normal
  26306. normal.copy( vertex ).normalize();
  26307. normals.push( normal.x, normal.y, normal.z );
  26308. // uv
  26309. uvs.push( u + uOffset, 1 - v );
  26310. verticesRow.push( index ++ );
  26311. }
  26312. grid.push( verticesRow );
  26313. }
  26314. // indices
  26315. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26316. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26317. const a = grid[ iy ][ ix + 1 ];
  26318. const b = grid[ iy ][ ix ];
  26319. const c = grid[ iy + 1 ][ ix ];
  26320. const d = grid[ iy + 1 ][ ix + 1 ];
  26321. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26322. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26323. }
  26324. }
  26325. // build geometry
  26326. this.setIndex( indices );
  26327. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26328. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26329. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26330. }
  26331. copy( source ) {
  26332. super.copy( source );
  26333. this.parameters = Object.assign( {}, source.parameters );
  26334. return this;
  26335. }
  26336. /**
  26337. * Factory method for creating an instance of this class from the given
  26338. * JSON object.
  26339. *
  26340. * @param {Object} data - A JSON object representing the serialized geometry.
  26341. * @return {SphereGeometry} A new instance.
  26342. */
  26343. static fromJSON( data ) {
  26344. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26345. }
  26346. }
  26347. /**
  26348. * A geometry class for representing an tetrahedron.
  26349. *
  26350. * ```js
  26351. * const geometry = new THREE.TetrahedronGeometry();
  26352. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26353. * const tetrahedron = new THREE.Mesh( geometry, material );
  26354. * scene.add( tetrahedron );
  26355. * ```
  26356. *
  26357. * @augments PolyhedronGeometry
  26358. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26359. */
  26360. class TetrahedronGeometry extends PolyhedronGeometry {
  26361. /**
  26362. * Constructs a new tetrahedron geometry.
  26363. *
  26364. * @param {number} [radius=1] - Radius of the tetrahedron.
  26365. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26366. */
  26367. constructor( radius = 1, detail = 0 ) {
  26368. const vertices = [
  26369. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26370. ];
  26371. const indices = [
  26372. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26373. ];
  26374. super( vertices, indices, radius, detail );
  26375. this.type = 'TetrahedronGeometry';
  26376. /**
  26377. * Holds the constructor parameters that have been
  26378. * used to generate the geometry. Any modification
  26379. * after instantiation does not change the geometry.
  26380. *
  26381. * @type {Object}
  26382. */
  26383. this.parameters = {
  26384. radius: radius,
  26385. detail: detail
  26386. };
  26387. }
  26388. /**
  26389. * Factory method for creating an instance of this class from the given
  26390. * JSON object.
  26391. *
  26392. * @param {Object} data - A JSON object representing the serialized geometry.
  26393. * @return {TetrahedronGeometry} A new instance.
  26394. */
  26395. static fromJSON( data ) {
  26396. return new TetrahedronGeometry( data.radius, data.detail );
  26397. }
  26398. }
  26399. /**
  26400. * A geometry class for representing an torus.
  26401. *
  26402. * ```js
  26403. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26404. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26405. * const torus = new THREE.Mesh( geometry, material );
  26406. * scene.add( torus );
  26407. * ```
  26408. *
  26409. * @augments BufferGeometry
  26410. * @demo scenes/geometry-browser.html#TorusGeometry
  26411. */
  26412. class TorusGeometry extends BufferGeometry {
  26413. /**
  26414. * Constructs a new torus geometry.
  26415. *
  26416. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26417. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26418. * @param {number} [radialSegments=12] - The number of radial segments.
  26419. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26420. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26421. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26422. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26423. */
  26424. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26425. super();
  26426. this.type = 'TorusGeometry';
  26427. /**
  26428. * Holds the constructor parameters that have been
  26429. * used to generate the geometry. Any modification
  26430. * after instantiation does not change the geometry.
  26431. *
  26432. * @type {Object}
  26433. */
  26434. this.parameters = {
  26435. radius: radius,
  26436. tube: tube,
  26437. radialSegments: radialSegments,
  26438. tubularSegments: tubularSegments,
  26439. arc: arc,
  26440. thetaStart: thetaStart,
  26441. thetaLength: thetaLength,
  26442. };
  26443. radialSegments = Math.floor( radialSegments );
  26444. tubularSegments = Math.floor( tubularSegments );
  26445. // buffers
  26446. const indices = [];
  26447. const vertices = [];
  26448. const normals = [];
  26449. const uvs = [];
  26450. // helper variables
  26451. const center = new Vector3();
  26452. const vertex = new Vector3();
  26453. const normal = new Vector3();
  26454. // generate vertices, normals and uvs
  26455. for ( let j = 0; j <= radialSegments; j ++ ) {
  26456. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26457. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26458. const u = i / tubularSegments * arc;
  26459. // vertex
  26460. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26461. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26462. vertex.z = tube * Math.sin( v );
  26463. vertices.push( vertex.x, vertex.y, vertex.z );
  26464. // normal
  26465. center.x = radius * Math.cos( u );
  26466. center.y = radius * Math.sin( u );
  26467. normal.subVectors( vertex, center ).normalize();
  26468. normals.push( normal.x, normal.y, normal.z );
  26469. // uv
  26470. uvs.push( i / tubularSegments );
  26471. uvs.push( j / radialSegments );
  26472. }
  26473. }
  26474. // generate indices
  26475. for ( let j = 1; j <= radialSegments; j ++ ) {
  26476. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26477. // indices
  26478. const a = ( tubularSegments + 1 ) * j + i - 1;
  26479. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26480. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26481. const d = ( tubularSegments + 1 ) * j + i;
  26482. // faces
  26483. indices.push( a, b, d );
  26484. indices.push( b, c, d );
  26485. }
  26486. }
  26487. // build geometry
  26488. this.setIndex( indices );
  26489. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26490. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26491. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26492. }
  26493. copy( source ) {
  26494. super.copy( source );
  26495. this.parameters = Object.assign( {}, source.parameters );
  26496. return this;
  26497. }
  26498. /**
  26499. * Factory method for creating an instance of this class from the given
  26500. * JSON object.
  26501. *
  26502. * @param {Object} data - A JSON object representing the serialized geometry.
  26503. * @return {TorusGeometry} A new instance.
  26504. */
  26505. static fromJSON( data ) {
  26506. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26507. }
  26508. }
  26509. /**
  26510. * Creates a torus knot, the particular shape of which is defined by a pair
  26511. * of coprime integers, p and q. If p and q are not coprime, the result will
  26512. * be a torus link.
  26513. *
  26514. * ```js
  26515. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26516. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26517. * const torusKnot = new THREE.Mesh( geometry, material );
  26518. * scene.add( torusKnot );
  26519. * ```
  26520. *
  26521. * @augments BufferGeometry
  26522. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26523. */
  26524. class TorusKnotGeometry extends BufferGeometry {
  26525. /**
  26526. * Constructs a new torus knot geometry.
  26527. *
  26528. * @param {number} [radius=1] - Radius of the torus knot.
  26529. * @param {number} [tube=0.4] - Radius of the tube.
  26530. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26531. * @param {number} [radialSegments=8] - The number of radial segments.
  26532. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26533. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26534. */
  26535. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26536. super();
  26537. this.type = 'TorusKnotGeometry';
  26538. /**
  26539. * Holds the constructor parameters that have been
  26540. * used to generate the geometry. Any modification
  26541. * after instantiation does not change the geometry.
  26542. *
  26543. * @type {Object}
  26544. */
  26545. this.parameters = {
  26546. radius: radius,
  26547. tube: tube,
  26548. tubularSegments: tubularSegments,
  26549. radialSegments: radialSegments,
  26550. p: p,
  26551. q: q
  26552. };
  26553. tubularSegments = Math.floor( tubularSegments );
  26554. radialSegments = Math.floor( radialSegments );
  26555. // buffers
  26556. const indices = [];
  26557. const vertices = [];
  26558. const normals = [];
  26559. const uvs = [];
  26560. // helper variables
  26561. const vertex = new Vector3();
  26562. const normal = new Vector3();
  26563. const P1 = new Vector3();
  26564. const P2 = new Vector3();
  26565. const B = new Vector3();
  26566. const T = new Vector3();
  26567. const N = new Vector3();
  26568. // generate vertices, normals and uvs
  26569. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26570. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26571. const u = i / tubularSegments * p * Math.PI * 2;
  26572. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26573. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26574. calculatePositionOnCurve( u, p, q, radius, P1 );
  26575. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26576. // calculate orthonormal basis
  26577. T.subVectors( P2, P1 );
  26578. N.addVectors( P2, P1 );
  26579. B.crossVectors( T, N );
  26580. N.crossVectors( B, T );
  26581. // normalize B, N. T can be ignored, we don't use it
  26582. B.normalize();
  26583. N.normalize();
  26584. for ( let j = 0; j <= radialSegments; ++ j ) {
  26585. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26586. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26587. const v = j / radialSegments * Math.PI * 2;
  26588. const cx = - tube * Math.cos( v );
  26589. const cy = tube * Math.sin( v );
  26590. // now calculate the final vertex position.
  26591. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26592. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26593. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26594. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26595. vertices.push( vertex.x, vertex.y, vertex.z );
  26596. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26597. normal.subVectors( vertex, P1 ).normalize();
  26598. normals.push( normal.x, normal.y, normal.z );
  26599. // uv
  26600. uvs.push( i / tubularSegments );
  26601. uvs.push( j / radialSegments );
  26602. }
  26603. }
  26604. // generate indices
  26605. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26606. for ( let i = 1; i <= radialSegments; i ++ ) {
  26607. // indices
  26608. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26609. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26610. const c = ( radialSegments + 1 ) * j + i;
  26611. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26612. // faces
  26613. indices.push( a, b, d );
  26614. indices.push( b, c, d );
  26615. }
  26616. }
  26617. // build geometry
  26618. this.setIndex( indices );
  26619. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26620. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26621. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26622. // this function calculates the current position on the torus curve
  26623. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26624. const cu = Math.cos( u );
  26625. const su = Math.sin( u );
  26626. const quOverP = q / p * u;
  26627. const cs = Math.cos( quOverP );
  26628. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26629. position.y = radius * ( 2 + cs ) * su * 0.5;
  26630. position.z = radius * Math.sin( quOverP ) * 0.5;
  26631. }
  26632. }
  26633. copy( source ) {
  26634. super.copy( source );
  26635. this.parameters = Object.assign( {}, source.parameters );
  26636. return this;
  26637. }
  26638. /**
  26639. * Factory method for creating an instance of this class from the given
  26640. * JSON object.
  26641. *
  26642. * @param {Object} data - A JSON object representing the serialized geometry.
  26643. * @return {TorusKnotGeometry} A new instance.
  26644. */
  26645. static fromJSON( data ) {
  26646. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26647. }
  26648. }
  26649. /**
  26650. * Creates a tube that extrudes along a 3D curve.
  26651. *
  26652. * ```js
  26653. * class CustomSinCurve extends THREE.Curve {
  26654. *
  26655. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26656. *
  26657. * const tx = t * 3 - 1.5;
  26658. * const ty = Math.sin( 2 * Math.PI * t );
  26659. * const tz = 0;
  26660. *
  26661. * return optionalTarget.set( tx, ty, tz );
  26662. * }
  26663. *
  26664. * }
  26665. *
  26666. * const path = new CustomSinCurve( 10 );
  26667. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  26668. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26669. * const mesh = new THREE.Mesh( geometry, material );
  26670. * scene.add( mesh );
  26671. * ```
  26672. *
  26673. * @augments BufferGeometry
  26674. * @demo scenes/geometry-browser.html#TubeGeometry
  26675. */
  26676. class TubeGeometry extends BufferGeometry {
  26677. /**
  26678. * Constructs a new tube geometry.
  26679. *
  26680. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  26681. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  26682. * @param {number} [radius=1] -The radius of the tube.
  26683. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  26684. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  26685. */
  26686. 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 ) {
  26687. super();
  26688. this.type = 'TubeGeometry';
  26689. /**
  26690. * Holds the constructor parameters that have been
  26691. * used to generate the geometry. Any modification
  26692. * after instantiation does not change the geometry.
  26693. *
  26694. * @type {Object}
  26695. */
  26696. this.parameters = {
  26697. path: path,
  26698. tubularSegments: tubularSegments,
  26699. radius: radius,
  26700. radialSegments: radialSegments,
  26701. closed: closed
  26702. };
  26703. const frames = path.computeFrenetFrames( tubularSegments, closed );
  26704. // expose internals
  26705. this.tangents = frames.tangents;
  26706. this.normals = frames.normals;
  26707. this.binormals = frames.binormals;
  26708. // helper variables
  26709. const vertex = new Vector3();
  26710. const normal = new Vector3();
  26711. const uv = new Vector2();
  26712. let P = new Vector3();
  26713. // buffer
  26714. const vertices = [];
  26715. const normals = [];
  26716. const uvs = [];
  26717. const indices = [];
  26718. // create buffer data
  26719. generateBufferData();
  26720. // build geometry
  26721. this.setIndex( indices );
  26722. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26723. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26724. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26725. // functions
  26726. function generateBufferData() {
  26727. for ( let i = 0; i < tubularSegments; i ++ ) {
  26728. generateSegment( i );
  26729. }
  26730. // if the geometry is not closed, generate the last row of vertices and normals
  26731. // at the regular position on the given path
  26732. //
  26733. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  26734. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  26735. // uvs are generated in a separate function.
  26736. // this makes it easy compute correct values for closed geometries
  26737. generateUVs();
  26738. // finally create faces
  26739. generateIndices();
  26740. }
  26741. function generateSegment( i ) {
  26742. // we use getPointAt to sample evenly distributed points from the given path
  26743. P = path.getPointAt( i / tubularSegments, P );
  26744. // retrieve corresponding normal and binormal
  26745. const N = frames.normals[ i ];
  26746. const B = frames.binormals[ i ];
  26747. // generate normals and vertices for the current segment
  26748. for ( let j = 0; j <= radialSegments; j ++ ) {
  26749. const v = j / radialSegments * Math.PI * 2;
  26750. const sin = Math.sin( v );
  26751. const cos = - Math.cos( v );
  26752. // normal
  26753. normal.x = ( cos * N.x + sin * B.x );
  26754. normal.y = ( cos * N.y + sin * B.y );
  26755. normal.z = ( cos * N.z + sin * B.z );
  26756. normal.normalize();
  26757. normals.push( normal.x, normal.y, normal.z );
  26758. // vertex
  26759. vertex.x = P.x + radius * normal.x;
  26760. vertex.y = P.y + radius * normal.y;
  26761. vertex.z = P.z + radius * normal.z;
  26762. vertices.push( vertex.x, vertex.y, vertex.z );
  26763. }
  26764. }
  26765. function generateIndices() {
  26766. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26767. for ( let i = 1; i <= radialSegments; i ++ ) {
  26768. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26769. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26770. const c = ( radialSegments + 1 ) * j + i;
  26771. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26772. // faces
  26773. indices.push( a, b, d );
  26774. indices.push( b, c, d );
  26775. }
  26776. }
  26777. }
  26778. function generateUVs() {
  26779. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26780. for ( let j = 0; j <= radialSegments; j ++ ) {
  26781. uv.x = i / tubularSegments;
  26782. uv.y = j / radialSegments;
  26783. uvs.push( uv.x, uv.y );
  26784. }
  26785. }
  26786. }
  26787. }
  26788. copy( source ) {
  26789. super.copy( source );
  26790. this.parameters = Object.assign( {}, source.parameters );
  26791. return this;
  26792. }
  26793. toJSON() {
  26794. const data = super.toJSON();
  26795. data.path = this.parameters.path.toJSON();
  26796. return data;
  26797. }
  26798. /**
  26799. * Factory method for creating an instance of this class from the given
  26800. * JSON object.
  26801. *
  26802. * @param {Object} data - A JSON object representing the serialized geometry.
  26803. * @return {TubeGeometry} A new instance.
  26804. */
  26805. static fromJSON( data ) {
  26806. // This only works for built-in curves (e.g. CatmullRomCurve3).
  26807. // User defined curves or instances of CurvePath will not be deserialized.
  26808. return new TubeGeometry(
  26809. new Curves[ data.path.type ]().fromJSON( data.path ),
  26810. data.tubularSegments,
  26811. data.radius,
  26812. data.radialSegments,
  26813. data.closed
  26814. );
  26815. }
  26816. }
  26817. /**
  26818. * Can be used as a helper object to visualize a geometry as a wireframe.
  26819. *
  26820. * ```js
  26821. * const geometry = new THREE.SphereGeometry();
  26822. *
  26823. * const wireframe = new THREE.WireframeGeometry( geometry );
  26824. *
  26825. * const line = new THREE.LineSegments( wireframe );
  26826. * line.material.depthWrite = false;
  26827. * line.material.opacity = 0.25;
  26828. * line.material.transparent = true;
  26829. *
  26830. * scene.add( line );
  26831. * ```
  26832. *
  26833. * Note: It is not yet possible to serialize/deserialize instances of this class.
  26834. *
  26835. * @augments BufferGeometry
  26836. */
  26837. class WireframeGeometry extends BufferGeometry {
  26838. /**
  26839. * Constructs a new wireframe geometry.
  26840. *
  26841. * @param {?BufferGeometry} [geometry=null] - The geometry.
  26842. */
  26843. constructor( geometry = null ) {
  26844. super();
  26845. this.type = 'WireframeGeometry';
  26846. /**
  26847. * Holds the constructor parameters that have been
  26848. * used to generate the geometry. Any modification
  26849. * after instantiation does not change the geometry.
  26850. *
  26851. * @type {Object}
  26852. */
  26853. this.parameters = {
  26854. geometry: geometry
  26855. };
  26856. if ( geometry !== null ) {
  26857. // buffer
  26858. const vertices = [];
  26859. const edges = new Set();
  26860. // helper variables
  26861. const start = new Vector3();
  26862. const end = new Vector3();
  26863. if ( geometry.index !== null ) {
  26864. // indexed BufferGeometry
  26865. const position = geometry.attributes.position;
  26866. const indices = geometry.index;
  26867. let groups = geometry.groups;
  26868. if ( groups.length === 0 ) {
  26869. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  26870. }
  26871. // create a data structure that contains all edges without duplicates
  26872. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  26873. const group = groups[ o ];
  26874. const groupStart = group.start;
  26875. const groupCount = group.count;
  26876. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  26877. for ( let j = 0; j < 3; j ++ ) {
  26878. const index1 = indices.getX( i + j );
  26879. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  26880. start.fromBufferAttribute( position, index1 );
  26881. end.fromBufferAttribute( position, index2 );
  26882. if ( isUniqueEdge( start, end, edges ) === true ) {
  26883. vertices.push( start.x, start.y, start.z );
  26884. vertices.push( end.x, end.y, end.z );
  26885. }
  26886. }
  26887. }
  26888. }
  26889. } else {
  26890. // non-indexed BufferGeometry
  26891. const position = geometry.attributes.position;
  26892. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  26893. for ( let j = 0; j < 3; j ++ ) {
  26894. // three edges per triangle, an edge is represented as (index1, index2)
  26895. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  26896. const index1 = 3 * i + j;
  26897. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  26898. start.fromBufferAttribute( position, index1 );
  26899. end.fromBufferAttribute( position, index2 );
  26900. if ( isUniqueEdge( start, end, edges ) === true ) {
  26901. vertices.push( start.x, start.y, start.z );
  26902. vertices.push( end.x, end.y, end.z );
  26903. }
  26904. }
  26905. }
  26906. }
  26907. // build geometry
  26908. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26909. }
  26910. }
  26911. copy( source ) {
  26912. super.copy( source );
  26913. this.parameters = Object.assign( {}, source.parameters );
  26914. return this;
  26915. }
  26916. }
  26917. function isUniqueEdge( start, end, edges ) {
  26918. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  26919. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  26920. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  26921. return false;
  26922. } else {
  26923. edges.add( hash1 );
  26924. edges.add( hash2 );
  26925. return true;
  26926. }
  26927. }
  26928. var Geometries = /*#__PURE__*/Object.freeze({
  26929. __proto__: null,
  26930. BoxGeometry: BoxGeometry,
  26931. CapsuleGeometry: CapsuleGeometry,
  26932. CircleGeometry: CircleGeometry,
  26933. ConeGeometry: ConeGeometry,
  26934. CylinderGeometry: CylinderGeometry,
  26935. DodecahedronGeometry: DodecahedronGeometry,
  26936. EdgesGeometry: EdgesGeometry,
  26937. ExtrudeGeometry: ExtrudeGeometry,
  26938. IcosahedronGeometry: IcosahedronGeometry,
  26939. LatheGeometry: LatheGeometry,
  26940. OctahedronGeometry: OctahedronGeometry,
  26941. PlaneGeometry: PlaneGeometry,
  26942. PolyhedronGeometry: PolyhedronGeometry,
  26943. RingGeometry: RingGeometry,
  26944. ShapeGeometry: ShapeGeometry,
  26945. SphereGeometry: SphereGeometry,
  26946. TetrahedronGeometry: TetrahedronGeometry,
  26947. TorusGeometry: TorusGeometry,
  26948. TorusKnotGeometry: TorusKnotGeometry,
  26949. TubeGeometry: TubeGeometry,
  26950. WireframeGeometry: WireframeGeometry
  26951. });
  26952. /**
  26953. * This material can receive shadows, but otherwise is completely transparent.
  26954. *
  26955. * ```js
  26956. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  26957. * geometry.rotateX( - Math.PI / 2 );
  26958. *
  26959. * const material = new THREE.ShadowMaterial();
  26960. * material.opacity = 0.2;
  26961. *
  26962. * const plane = new THREE.Mesh( geometry, material );
  26963. * plane.position.y = -200;
  26964. * plane.receiveShadow = true;
  26965. * scene.add( plane );
  26966. * ```
  26967. *
  26968. * @augments Material
  26969. */
  26970. class ShadowMaterial extends Material {
  26971. /**
  26972. * Constructs a new shadow material.
  26973. *
  26974. * @param {Object} [parameters] - An object with one or more properties
  26975. * defining the material's appearance. Any property of the material
  26976. * (including any property from inherited materials) can be passed
  26977. * in here. Color values can be passed any type of value accepted
  26978. * by {@link Color#set}.
  26979. */
  26980. constructor( parameters ) {
  26981. super();
  26982. /**
  26983. * This flag can be used for type testing.
  26984. *
  26985. * @type {boolean}
  26986. * @readonly
  26987. * @default true
  26988. */
  26989. this.isShadowMaterial = true;
  26990. this.type = 'ShadowMaterial';
  26991. /**
  26992. * Color of the material.
  26993. *
  26994. * @type {Color}
  26995. * @default (0,0,0)
  26996. */
  26997. this.color = new Color( 0x000000 );
  26998. /**
  26999. * Overwritten since shadow materials are transparent
  27000. * by default.
  27001. *
  27002. * @type {boolean}
  27003. * @default true
  27004. */
  27005. this.transparent = true;
  27006. /**
  27007. * Whether the material is affected by fog or not.
  27008. *
  27009. * @type {boolean}
  27010. * @default true
  27011. */
  27012. this.fog = true;
  27013. this.setValues( parameters );
  27014. }
  27015. copy( source ) {
  27016. super.copy( source );
  27017. this.color.copy( source.color );
  27018. this.fog = source.fog;
  27019. return this;
  27020. }
  27021. }
  27022. /**
  27023. * Provides utility functions for managing uniforms.
  27024. *
  27025. * @module UniformsUtils
  27026. */
  27027. /**
  27028. * Clones the given uniform definitions by performing a deep-copy. That means
  27029. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27030. * the cloned uniform will refer to a new object reference.
  27031. *
  27032. * @param {Object} src - An object representing uniform definitions.
  27033. * @return {Object} The cloned uniforms.
  27034. */
  27035. function cloneUniforms( src ) {
  27036. const dst = {};
  27037. for ( const u in src ) {
  27038. dst[ u ] = {};
  27039. for ( const p in src[ u ] ) {
  27040. const property = src[ u ][ p ];
  27041. if ( property && ( property.isColor ||
  27042. property.isMatrix3 || property.isMatrix4 ||
  27043. property.isVector2 || property.isVector3 || property.isVector4 ||
  27044. property.isTexture || property.isQuaternion ) ) {
  27045. if ( property.isRenderTargetTexture ) {
  27046. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27047. dst[ u ][ p ] = null;
  27048. } else {
  27049. dst[ u ][ p ] = property.clone();
  27050. }
  27051. } else if ( Array.isArray( property ) ) {
  27052. dst[ u ][ p ] = property.slice();
  27053. } else {
  27054. dst[ u ][ p ] = property;
  27055. }
  27056. }
  27057. }
  27058. return dst;
  27059. }
  27060. /**
  27061. * Merges the given uniform definitions into a single object. Since the
  27062. * method internally uses cloneUniforms(), it performs a deep-copy when
  27063. * producing the merged uniform definitions.
  27064. *
  27065. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27066. * @return {Object} The merged uniforms.
  27067. */
  27068. function mergeUniforms( uniforms ) {
  27069. const merged = {};
  27070. for ( let u = 0; u < uniforms.length; u ++ ) {
  27071. const tmp = cloneUniforms( uniforms[ u ] );
  27072. for ( const p in tmp ) {
  27073. merged[ p ] = tmp[ p ];
  27074. }
  27075. }
  27076. return merged;
  27077. }
  27078. function cloneUniformsGroups( src ) {
  27079. const dst = [];
  27080. for ( let u = 0; u < src.length; u ++ ) {
  27081. dst.push( src[ u ].clone() );
  27082. }
  27083. return dst;
  27084. }
  27085. function getUnlitUniformColorSpace( renderer ) {
  27086. const currentRenderTarget = renderer.getRenderTarget();
  27087. if ( currentRenderTarget === null ) {
  27088. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27089. return renderer.outputColorSpace;
  27090. }
  27091. // https://github.com/mrdoob/three.js/issues/27868
  27092. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27093. return currentRenderTarget.texture.colorSpace;
  27094. }
  27095. return ColorManagement.workingColorSpace;
  27096. }
  27097. // Legacy
  27098. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27099. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27100. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27101. /**
  27102. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27103. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27104. * effect not included with any of the built-in materials.
  27105. *
  27106. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27107. *
  27108. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27109. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27110. * you don't want that, use {@link RawShaderMaterial} instead.
  27111. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27112. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27113. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27114. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27115. * - The loop variable has to be *i*.
  27116. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27117. * value of *i* for the given iteration and can be used in preprocessor
  27118. * statements.
  27119. *
  27120. * ```js
  27121. * const material = new THREE.ShaderMaterial( {
  27122. * uniforms: {
  27123. * time: { value: 1.0 },
  27124. * resolution: { value: new THREE.Vector2() }
  27125. * },
  27126. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27127. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27128. * } );
  27129. * ```
  27130. *
  27131. * @augments Material
  27132. */
  27133. class ShaderMaterial extends Material {
  27134. /**
  27135. * Constructs a new shader material.
  27136. *
  27137. * @param {Object} [parameters] - An object with one or more properties
  27138. * defining the material's appearance. Any property of the material
  27139. * (including any property from inherited materials) can be passed
  27140. * in here. Color values can be passed any type of value accepted
  27141. * by {@link Color#set}.
  27142. */
  27143. constructor( parameters ) {
  27144. super();
  27145. /**
  27146. * This flag can be used for type testing.
  27147. *
  27148. * @type {boolean}
  27149. * @readonly
  27150. * @default true
  27151. */
  27152. this.isShaderMaterial = true;
  27153. this.type = 'ShaderMaterial';
  27154. /**
  27155. * Defines custom constants using `#define` directives within the GLSL code
  27156. * for both the vertex shader and the fragment shader; each key/value pair
  27157. * yields another directive.
  27158. * ```js
  27159. * defines: {
  27160. * FOO: 15,
  27161. * BAR: true
  27162. * }
  27163. * ```
  27164. * Yields the lines:
  27165. * ```
  27166. * #define FOO 15
  27167. * #define BAR true
  27168. * ```
  27169. *
  27170. * @type {Object}
  27171. */
  27172. this.defines = {};
  27173. /**
  27174. * An object of the form:
  27175. * ```js
  27176. * {
  27177. * "uniform1": { value: 1.0 },
  27178. * "uniform2": { value: 2 }
  27179. * }
  27180. * ```
  27181. * specifying the uniforms to be passed to the shader code; keys are uniform
  27182. * names, values are definitions of the form
  27183. * ```
  27184. * {
  27185. * value: 1.0
  27186. * }
  27187. * ```
  27188. * where `value` is the value of the uniform. Names must match the name of
  27189. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27190. * on every frame, so updating the value of the uniform will immediately
  27191. * update the value available to the GLSL code.
  27192. *
  27193. * @type {Object}
  27194. */
  27195. this.uniforms = {};
  27196. /**
  27197. * An array holding uniforms groups for configuring UBOs.
  27198. *
  27199. * @type {Array<UniformsGroup>}
  27200. */
  27201. this.uniformsGroups = [];
  27202. /**
  27203. * Vertex shader GLSL code. This is the actual code for the shader.
  27204. *
  27205. * @type {string}
  27206. */
  27207. this.vertexShader = default_vertex;
  27208. /**
  27209. * Fragment shader GLSL code. This is the actual code for the shader.
  27210. *
  27211. * @type {string}
  27212. */
  27213. this.fragmentShader = default_fragment;
  27214. /**
  27215. * Controls line thickness or lines.
  27216. *
  27217. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27218. * width of one pixel.
  27219. *
  27220. * @type {number}
  27221. * @default 1
  27222. */
  27223. this.linewidth = 1;
  27224. /**
  27225. * Renders the geometry as a wireframe.
  27226. *
  27227. * @type {boolean}
  27228. * @default false
  27229. */
  27230. this.wireframe = false;
  27231. /**
  27232. * Controls the thickness of the wireframe.
  27233. *
  27234. * WebGL and WebGPU ignore this property and always render
  27235. * 1 pixel wide lines.
  27236. *
  27237. * @type {number}
  27238. * @default 1
  27239. */
  27240. this.wireframeLinewidth = 1;
  27241. /**
  27242. * Defines whether the material color is affected by global fog settings; `true`
  27243. * to pass fog uniforms to the shader.
  27244. *
  27245. * Setting this property to `true` requires the definition of fog uniforms. It is
  27246. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27247. * with predefined fog uniforms.
  27248. *
  27249. * ```js
  27250. * const material = new ShaderMaterial( {
  27251. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27252. * vertexShader: vertexShader,
  27253. * fragmentShader: fragmentShader,
  27254. * fog: true
  27255. * } );
  27256. * ```
  27257. *
  27258. * @type {boolean}
  27259. * @default false
  27260. */
  27261. this.fog = false;
  27262. /**
  27263. * Defines whether this material uses lighting; `true` to pass uniform data
  27264. * related to lighting to this shader.
  27265. *
  27266. * @type {boolean}
  27267. * @default false
  27268. */
  27269. this.lights = false;
  27270. /**
  27271. * Defines whether this material supports clipping; `true` to let the renderer
  27272. * pass the clippingPlanes uniform.
  27273. *
  27274. * @type {boolean}
  27275. * @default false
  27276. */
  27277. this.clipping = false;
  27278. /**
  27279. * Overwritten and set to `true` by default.
  27280. *
  27281. * @type {boolean}
  27282. * @default true
  27283. */
  27284. this.forceSinglePass = true;
  27285. /**
  27286. * This object allows to enable certain WebGL 2 extensions.
  27287. *
  27288. * - clipCullDistance: set to `true` to use vertex shader clipping
  27289. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27290. *
  27291. * @type {{clipCullDistance:false,multiDraw:false}}
  27292. */
  27293. this.extensions = {
  27294. clipCullDistance: false, // set to use vertex shader clipping
  27295. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27296. };
  27297. /**
  27298. * When the rendered geometry doesn't include these attributes but the
  27299. * material does, these default values will be passed to the shaders. This
  27300. * avoids errors when buffer data is missing.
  27301. *
  27302. * - color: [ 1, 1, 1 ]
  27303. * - uv: [ 0, 0 ]
  27304. * - uv1: [ 0, 0 ]
  27305. *
  27306. * @type {Object}
  27307. */
  27308. this.defaultAttributeValues = {
  27309. 'color': [ 1, 1, 1 ],
  27310. 'uv': [ 0, 0 ],
  27311. 'uv1': [ 0, 0 ]
  27312. };
  27313. /**
  27314. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27315. * to bind a generic vertex index to an attribute variable.
  27316. *
  27317. * @type {string|undefined}
  27318. * @default undefined
  27319. */
  27320. this.index0AttributeName = undefined;
  27321. /**
  27322. * Can be used to force a uniform update while changing uniforms in
  27323. * {@link Object3D#onBeforeRender}.
  27324. *
  27325. * @type {boolean}
  27326. * @default false
  27327. */
  27328. this.uniformsNeedUpdate = false;
  27329. /**
  27330. * Defines the GLSL version of custom shader code.
  27331. *
  27332. * @type {?(GLSL1|GLSL3)}
  27333. * @default null
  27334. */
  27335. this.glslVersion = null;
  27336. if ( parameters !== undefined ) {
  27337. this.setValues( parameters );
  27338. }
  27339. }
  27340. copy( source ) {
  27341. super.copy( source );
  27342. this.fragmentShader = source.fragmentShader;
  27343. this.vertexShader = source.vertexShader;
  27344. this.uniforms = cloneUniforms( source.uniforms );
  27345. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27346. this.defines = Object.assign( {}, source.defines );
  27347. this.wireframe = source.wireframe;
  27348. this.wireframeLinewidth = source.wireframeLinewidth;
  27349. this.fog = source.fog;
  27350. this.lights = source.lights;
  27351. this.clipping = source.clipping;
  27352. this.extensions = Object.assign( {}, source.extensions );
  27353. this.glslVersion = source.glslVersion;
  27354. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27355. this.index0AttributeName = source.index0AttributeName;
  27356. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27357. return this;
  27358. }
  27359. toJSON( meta ) {
  27360. const data = super.toJSON( meta );
  27361. data.glslVersion = this.glslVersion;
  27362. data.uniforms = {};
  27363. for ( const name in this.uniforms ) {
  27364. const uniform = this.uniforms[ name ];
  27365. const value = uniform.value;
  27366. if ( value && value.isTexture ) {
  27367. data.uniforms[ name ] = {
  27368. type: 't',
  27369. value: value.toJSON( meta ).uuid
  27370. };
  27371. } else if ( value && value.isColor ) {
  27372. data.uniforms[ name ] = {
  27373. type: 'c',
  27374. value: value.getHex()
  27375. };
  27376. } else if ( value && value.isVector2 ) {
  27377. data.uniforms[ name ] = {
  27378. type: 'v2',
  27379. value: value.toArray()
  27380. };
  27381. } else if ( value && value.isVector3 ) {
  27382. data.uniforms[ name ] = {
  27383. type: 'v3',
  27384. value: value.toArray()
  27385. };
  27386. } else if ( value && value.isVector4 ) {
  27387. data.uniforms[ name ] = {
  27388. type: 'v4',
  27389. value: value.toArray()
  27390. };
  27391. } else if ( value && value.isMatrix3 ) {
  27392. data.uniforms[ name ] = {
  27393. type: 'm3',
  27394. value: value.toArray()
  27395. };
  27396. } else if ( value && value.isMatrix4 ) {
  27397. data.uniforms[ name ] = {
  27398. type: 'm4',
  27399. value: value.toArray()
  27400. };
  27401. } else {
  27402. data.uniforms[ name ] = {
  27403. value: value
  27404. };
  27405. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27406. }
  27407. }
  27408. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27409. data.vertexShader = this.vertexShader;
  27410. data.fragmentShader = this.fragmentShader;
  27411. data.lights = this.lights;
  27412. data.clipping = this.clipping;
  27413. const extensions = {};
  27414. for ( const key in this.extensions ) {
  27415. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27416. }
  27417. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27418. return data;
  27419. }
  27420. }
  27421. /**
  27422. * This class works just like {@link ShaderMaterial}, except that definitions
  27423. * of built-in uniforms and attributes are not automatically prepended to the
  27424. * GLSL shader code.
  27425. *
  27426. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27427. *
  27428. * @augments ShaderMaterial
  27429. */
  27430. class RawShaderMaterial extends ShaderMaterial {
  27431. /**
  27432. * Constructs a new raw shader material.
  27433. *
  27434. * @param {Object} [parameters] - An object with one or more properties
  27435. * defining the material's appearance. Any property of the material
  27436. * (including any property from inherited materials) can be passed
  27437. * in here. Color values can be passed any type of value accepted
  27438. * by {@link Color#set}.
  27439. */
  27440. constructor( parameters ) {
  27441. super( parameters );
  27442. /**
  27443. * This flag can be used for type testing.
  27444. *
  27445. * @type {boolean}
  27446. * @readonly
  27447. * @default true
  27448. */
  27449. this.isRawShaderMaterial = true;
  27450. this.type = 'RawShaderMaterial';
  27451. }
  27452. }
  27453. /**
  27454. * A standard physically based material, using Metallic-Roughness workflow.
  27455. *
  27456. * Physically based rendering (PBR) has recently become the standard in many
  27457. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27458. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27459. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27460. *
  27461. * This approach differs from older approaches in that instead of using
  27462. * approximations for the way in which light interacts with a surface, a
  27463. * physically correct model is used. The idea is that, instead of tweaking
  27464. * materials to look good under specific lighting, a material can be created
  27465. * that will react 'correctly' under all lighting scenarios.
  27466. *
  27467. * In practice this gives a more accurate and realistic looking result than
  27468. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27469. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27470. * shading.
  27471. *
  27472. * Note that for best results you should always specify an environment map when using this material.
  27473. *
  27474. * For a non-technical introduction to the concept of PBR and how to set up a
  27475. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27476. *
  27477. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27478. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27479. *
  27480. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27481. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27482. * (pdf), by Brent Burley.
  27483. *
  27484. * @augments Material
  27485. * @demo scenes/material-browser.html#MeshStandardMaterial
  27486. */
  27487. class MeshStandardMaterial extends Material {
  27488. /**
  27489. * Constructs a new mesh standard material.
  27490. *
  27491. * @param {Object} [parameters] - An object with one or more properties
  27492. * defining the material's appearance. Any property of the material
  27493. * (including any property from inherited materials) can be passed
  27494. * in here. Color values can be passed any type of value accepted
  27495. * by {@link Color#set}.
  27496. */
  27497. constructor( parameters ) {
  27498. super();
  27499. /**
  27500. * This flag can be used for type testing.
  27501. *
  27502. * @type {boolean}
  27503. * @readonly
  27504. * @default true
  27505. */
  27506. this.isMeshStandardMaterial = true;
  27507. this.type = 'MeshStandardMaterial';
  27508. this.defines = { 'STANDARD': '' };
  27509. /**
  27510. * Color of the material.
  27511. *
  27512. * @type {Color}
  27513. * @default (1,1,1)
  27514. */
  27515. this.color = new Color( 0xffffff ); // diffuse
  27516. /**
  27517. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27518. * means fully diffuse. If `roughnessMap` is also provided,
  27519. * both values are multiplied.
  27520. *
  27521. * @type {number}
  27522. * @default 1
  27523. */
  27524. this.roughness = 1.0;
  27525. /**
  27526. * How much the material is like a metal. Non-metallic materials such as wood
  27527. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27528. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27529. * If `metalnessMap` is also provided, both values are multiplied.
  27530. *
  27531. * @type {number}
  27532. * @default 0
  27533. */
  27534. this.metalness = 0.0;
  27535. /**
  27536. * The color map. May optionally include an alpha channel, typically combined
  27537. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27538. * color is modulated by the diffuse `color`.
  27539. *
  27540. * @type {?Texture}
  27541. * @default null
  27542. */
  27543. this.map = null;
  27544. /**
  27545. * The light map. Requires a second set of UVs.
  27546. *
  27547. * @type {?Texture}
  27548. * @default null
  27549. */
  27550. this.lightMap = null;
  27551. /**
  27552. * Intensity of the baked light.
  27553. *
  27554. * @type {number}
  27555. * @default 1
  27556. */
  27557. this.lightMapIntensity = 1.0;
  27558. /**
  27559. * The red channel of this texture is used as the ambient occlusion map.
  27560. * Requires a second set of UVs.
  27561. *
  27562. * @type {?Texture}
  27563. * @default null
  27564. */
  27565. this.aoMap = null;
  27566. /**
  27567. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27568. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27569. * red channel is also `1`, ambient light is fully occluded on a surface.
  27570. *
  27571. * @type {number}
  27572. * @default 1
  27573. */
  27574. this.aoMapIntensity = 1.0;
  27575. /**
  27576. * Emissive (light) color of the material, essentially a solid color
  27577. * unaffected by other lighting.
  27578. *
  27579. * @type {Color}
  27580. * @default (0,0,0)
  27581. */
  27582. this.emissive = new Color( 0x000000 );
  27583. /**
  27584. * Intensity of the emissive light. Modulates the emissive color.
  27585. *
  27586. * @type {number}
  27587. * @default 1
  27588. */
  27589. this.emissiveIntensity = 1.0;
  27590. /**
  27591. * Set emissive (glow) map. The emissive map color is modulated by the
  27592. * emissive color and the emissive intensity. If you have an emissive map,
  27593. * be sure to set the emissive color to something other than black.
  27594. *
  27595. * @type {?Texture}
  27596. * @default null
  27597. */
  27598. this.emissiveMap = null;
  27599. /**
  27600. * The texture to create a bump map. The black and white values map to the
  27601. * perceived depth in relation to the lights. Bump doesn't actually affect
  27602. * the geometry of the object, only the lighting. If a normal map is defined
  27603. * this will be ignored.
  27604. *
  27605. * @type {?Texture}
  27606. * @default null
  27607. */
  27608. this.bumpMap = null;
  27609. /**
  27610. * How much the bump map affects the material. Typical range is `[0,1]`.
  27611. *
  27612. * @type {number}
  27613. * @default 1
  27614. */
  27615. this.bumpScale = 1;
  27616. /**
  27617. * The texture to create a normal map. The RGB values affect the surface
  27618. * normal for each pixel fragment and change the way the color is lit. Normal
  27619. * maps do not change the actual shape of the surface, only the lighting. In
  27620. * case the material has a normal map authored using the left handed
  27621. * convention, the `y` component of `normalScale` should be negated to compensate
  27622. * for the different handedness.
  27623. *
  27624. * @type {?Texture}
  27625. * @default null
  27626. */
  27627. this.normalMap = null;
  27628. /**
  27629. * The type of normal map.
  27630. *
  27631. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27632. * @default TangentSpaceNormalMap
  27633. */
  27634. this.normalMapType = TangentSpaceNormalMap;
  27635. /**
  27636. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27637. *
  27638. * @type {Vector2}
  27639. * @default (1,1)
  27640. */
  27641. this.normalScale = new Vector2( 1, 1 );
  27642. /**
  27643. * The displacement map affects the position of the mesh's vertices. Unlike
  27644. * other maps which only affect the light and shade of the material the
  27645. * displaced vertices can cast shadows, block other objects, and otherwise
  27646. * act as real geometry. The displacement texture is an image where the value
  27647. * of each pixel (white being the highest) is mapped against, and
  27648. * repositions, the vertices of the mesh.
  27649. *
  27650. * @type {?Texture}
  27651. * @default null
  27652. */
  27653. this.displacementMap = null;
  27654. /**
  27655. * How much the displacement map affects the mesh (where black is no
  27656. * displacement, and white is maximum displacement). Without a displacement
  27657. * map set, this value is not applied.
  27658. *
  27659. * @type {number}
  27660. * @default 0
  27661. */
  27662. this.displacementScale = 1;
  27663. /**
  27664. * The offset of the displacement map's values on the mesh's vertices.
  27665. * The bias is added to the scaled sample of the displacement map.
  27666. * Without a displacement map set, this value is not applied.
  27667. *
  27668. * @type {number}
  27669. * @default 0
  27670. */
  27671. this.displacementBias = 0;
  27672. /**
  27673. * The green channel of this texture is used to alter the roughness of the
  27674. * material.
  27675. *
  27676. * @type {?Texture}
  27677. * @default null
  27678. */
  27679. this.roughnessMap = null;
  27680. /**
  27681. * The blue channel of this texture is used to alter the metalness of the
  27682. * material.
  27683. *
  27684. * @type {?Texture}
  27685. * @default null
  27686. */
  27687. this.metalnessMap = null;
  27688. /**
  27689. * The alpha map is a grayscale texture that controls the opacity across the
  27690. * surface (black: fully transparent; white: fully opaque).
  27691. *
  27692. * Only the color of the texture is used, ignoring the alpha channel if one
  27693. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27694. * when sampling this texture due to the extra bit of precision provided for
  27695. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27696. * luminance/alpha textures will also still work as expected.
  27697. *
  27698. * @type {?Texture}
  27699. * @default null
  27700. */
  27701. this.alphaMap = null;
  27702. /**
  27703. * The environment map. To ensure a physically correct rendering, environment maps
  27704. * are internally pre-processed with {@link PMREMGenerator}.
  27705. *
  27706. * @type {?Texture}
  27707. * @default null
  27708. */
  27709. this.envMap = null;
  27710. /**
  27711. * The rotation of the environment map in radians.
  27712. *
  27713. * @type {Euler}
  27714. * @default (0,0,0)
  27715. */
  27716. this.envMapRotation = new Euler();
  27717. /**
  27718. * Scales the effect of the environment map by multiplying its color.
  27719. *
  27720. * @type {number}
  27721. * @default 1
  27722. */
  27723. this.envMapIntensity = 1.0;
  27724. /**
  27725. * Renders the geometry as a wireframe.
  27726. *
  27727. * @type {boolean}
  27728. * @default false
  27729. */
  27730. this.wireframe = false;
  27731. /**
  27732. * Controls the thickness of the wireframe.
  27733. *
  27734. * Can only be used with {@link SVGRenderer}.
  27735. *
  27736. * @type {number}
  27737. * @default 1
  27738. */
  27739. this.wireframeLinewidth = 1;
  27740. /**
  27741. * Defines appearance of wireframe ends.
  27742. *
  27743. * Can only be used with {@link SVGRenderer}.
  27744. *
  27745. * @type {('round'|'bevel'|'miter')}
  27746. * @default 'round'
  27747. */
  27748. this.wireframeLinecap = 'round';
  27749. /**
  27750. * Defines appearance of wireframe joints.
  27751. *
  27752. * Can only be used with {@link SVGRenderer}.
  27753. *
  27754. * @type {('round'|'bevel'|'miter')}
  27755. * @default 'round'
  27756. */
  27757. this.wireframeLinejoin = 'round';
  27758. /**
  27759. * Whether the material is rendered with flat shading or not.
  27760. *
  27761. * @type {boolean}
  27762. * @default false
  27763. */
  27764. this.flatShading = false;
  27765. /**
  27766. * Whether the material is affected by fog or not.
  27767. *
  27768. * @type {boolean}
  27769. * @default true
  27770. */
  27771. this.fog = true;
  27772. this.setValues( parameters );
  27773. }
  27774. copy( source ) {
  27775. super.copy( source );
  27776. this.defines = { 'STANDARD': '' };
  27777. this.color.copy( source.color );
  27778. this.roughness = source.roughness;
  27779. this.metalness = source.metalness;
  27780. this.map = source.map;
  27781. this.lightMap = source.lightMap;
  27782. this.lightMapIntensity = source.lightMapIntensity;
  27783. this.aoMap = source.aoMap;
  27784. this.aoMapIntensity = source.aoMapIntensity;
  27785. this.emissive.copy( source.emissive );
  27786. this.emissiveMap = source.emissiveMap;
  27787. this.emissiveIntensity = source.emissiveIntensity;
  27788. this.bumpMap = source.bumpMap;
  27789. this.bumpScale = source.bumpScale;
  27790. this.normalMap = source.normalMap;
  27791. this.normalMapType = source.normalMapType;
  27792. this.normalScale.copy( source.normalScale );
  27793. this.displacementMap = source.displacementMap;
  27794. this.displacementScale = source.displacementScale;
  27795. this.displacementBias = source.displacementBias;
  27796. this.roughnessMap = source.roughnessMap;
  27797. this.metalnessMap = source.metalnessMap;
  27798. this.alphaMap = source.alphaMap;
  27799. this.envMap = source.envMap;
  27800. this.envMapRotation.copy( source.envMapRotation );
  27801. this.envMapIntensity = source.envMapIntensity;
  27802. this.wireframe = source.wireframe;
  27803. this.wireframeLinewidth = source.wireframeLinewidth;
  27804. this.wireframeLinecap = source.wireframeLinecap;
  27805. this.wireframeLinejoin = source.wireframeLinejoin;
  27806. this.flatShading = source.flatShading;
  27807. this.fog = source.fog;
  27808. return this;
  27809. }
  27810. }
  27811. /**
  27812. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27813. * physically-based rendering properties:
  27814. *
  27815. * - Anisotropy: Ability to represent the anisotropic property of materials
  27816. * as observable with brushed metals.
  27817. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27818. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27819. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27820. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27821. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27822. * wings of many insects.
  27823. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27824. * transparent materials are less reflective. Physically-based transmission provides a more
  27825. * realistic option for thin, transparent surfaces like glass.
  27826. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27827. * - Sheen: Can be used for representing cloth and fabric materials.
  27828. *
  27829. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27830. * higher performance cost, per pixel, than other three.js materials. Most
  27831. * effects are disabled by default, and add cost as they are enabled. For
  27832. * best results, always specify an environment map when using this material.
  27833. *
  27834. * @augments MeshStandardMaterial
  27835. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  27836. */
  27837. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27838. /**
  27839. * Constructs a new mesh physical material.
  27840. *
  27841. * @param {Object} [parameters] - An object with one or more properties
  27842. * defining the material's appearance. Any property of the material
  27843. * (including any property from inherited materials) can be passed
  27844. * in here. Color values can be passed any type of value accepted
  27845. * by {@link Color#set}.
  27846. */
  27847. constructor( parameters ) {
  27848. super();
  27849. /**
  27850. * This flag can be used for type testing.
  27851. *
  27852. * @type {boolean}
  27853. * @readonly
  27854. * @default true
  27855. */
  27856. this.isMeshPhysicalMaterial = true;
  27857. this.defines = {
  27858. 'STANDARD': '',
  27859. 'PHYSICAL': ''
  27860. };
  27861. this.type = 'MeshPhysicalMaterial';
  27862. /**
  27863. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27864. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27865. * property provides additional rotation to the vectors in the texture.
  27866. *
  27867. * @type {number}
  27868. * @default 1
  27869. */
  27870. this.anisotropyRotation = 0;
  27871. /**
  27872. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  27873. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  27874. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  27875. *
  27876. * @type {?Texture}
  27877. * @default null
  27878. */
  27879. this.anisotropyMap = null;
  27880. /**
  27881. * The red channel of this texture is multiplied against `clearcoat`,
  27882. * for per-pixel control over a coating's intensity.
  27883. *
  27884. * @type {?Texture}
  27885. * @default null
  27886. */
  27887. this.clearcoatMap = null;
  27888. /**
  27889. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  27890. *
  27891. * @type {number}
  27892. * @default 0
  27893. */
  27894. this.clearcoatRoughness = 0.0;
  27895. /**
  27896. * The green channel of this texture is multiplied against
  27897. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  27898. *
  27899. * @type {?Texture}
  27900. * @default null
  27901. */
  27902. this.clearcoatRoughnessMap = null;
  27903. /**
  27904. * How much `clearcoatNormalMap` affects the clear coat layer, from
  27905. * `(0,0)` to `(1,1)`.
  27906. *
  27907. * @type {Vector2}
  27908. * @default (1,1)
  27909. */
  27910. this.clearcoatNormalScale = new Vector2( 1, 1 );
  27911. /**
  27912. * Can be used to enable independent normals for the clear coat layer.
  27913. *
  27914. * @type {?Texture}
  27915. * @default null
  27916. */
  27917. this.clearcoatNormalMap = null;
  27918. /**
  27919. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  27920. *
  27921. * @type {number}
  27922. * @default 1.5
  27923. */
  27924. this.ior = 1.5;
  27925. /**
  27926. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  27927. * corresponds to an index-of-refraction of `1.5`.
  27928. *
  27929. * This models the reflectivity of non-metallic materials. It has no effect
  27930. * when `metalness` is `1.0`
  27931. *
  27932. * @name MeshPhysicalMaterial#reflectivity
  27933. * @type {number}
  27934. * @default 0.5
  27935. */
  27936. Object.defineProperty( this, 'reflectivity', {
  27937. get: function () {
  27938. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  27939. },
  27940. set: function ( reflectivity ) {
  27941. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  27942. }
  27943. } );
  27944. /**
  27945. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  27946. * control over iridescence.
  27947. *
  27948. * @type {?Texture}
  27949. * @default null
  27950. */
  27951. this.iridescenceMap = null;
  27952. /**
  27953. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  27954. * Between `1.0` to `2.333`.
  27955. *
  27956. * @type {number}
  27957. * @default 1.3
  27958. */
  27959. this.iridescenceIOR = 1.3;
  27960. /**
  27961. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  27962. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  27963. *
  27964. * @type {Array<number,number>}
  27965. * @default [100,400]
  27966. */
  27967. this.iridescenceThicknessRange = [ 100, 400 ];
  27968. /**
  27969. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  27970. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  27971. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  27972. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  27973. * - Values in-between will linearly interpolate between the elements of the array.
  27974. *
  27975. * @type {?Texture}
  27976. * @default null
  27977. */
  27978. this.iridescenceThicknessMap = null;
  27979. /**
  27980. * The sheen tint.
  27981. *
  27982. * @type {Color}
  27983. * @default (0,0,0)
  27984. */
  27985. this.sheenColor = new Color( 0x000000 );
  27986. /**
  27987. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  27988. * over sheen tint.
  27989. *
  27990. * @type {?Texture}
  27991. * @default null
  27992. */
  27993. this.sheenColorMap = null;
  27994. /**
  27995. * Roughness of the sheen layer, from `0.0` to `1.0`.
  27996. *
  27997. * @type {number}
  27998. * @default 1
  27999. */
  28000. this.sheenRoughness = 1.0;
  28001. /**
  28002. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28003. * over sheen roughness.
  28004. *
  28005. * @type {?Texture}
  28006. * @default null
  28007. */
  28008. this.sheenRoughnessMap = null;
  28009. /**
  28010. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28011. * optical transparency.
  28012. *
  28013. * @type {?Texture}
  28014. * @default null
  28015. */
  28016. this.transmissionMap = null;
  28017. /**
  28018. * The thickness of the volume beneath the surface. The value is given in the
  28019. * coordinate space of the mesh. If the value is `0` the material is
  28020. * thin-walled. Otherwise the material is a volume boundary.
  28021. *
  28022. * @type {number}
  28023. * @default 0
  28024. */
  28025. this.thickness = 0;
  28026. /**
  28027. * A texture that defines the thickness, stored in the green channel. This will
  28028. * be multiplied by `thickness`.
  28029. *
  28030. * @type {?Texture}
  28031. * @default null
  28032. */
  28033. this.thicknessMap = null;
  28034. /**
  28035. * Density of the medium given as the average distance that light travels in
  28036. * the medium before interacting with a particle. The value is given in world
  28037. * space units, and must be greater than zero.
  28038. *
  28039. * @type {number}
  28040. * @default Infinity
  28041. */
  28042. this.attenuationDistance = Infinity;
  28043. /**
  28044. * The color that white light turns into due to absorption when reaching the
  28045. * attenuation distance.
  28046. *
  28047. * @type {Color}
  28048. * @default (1,1,1)
  28049. */
  28050. this.attenuationColor = new Color( 1, 1, 1 );
  28051. /**
  28052. * A float that scales the amount of specular reflection for non-metals only.
  28053. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28054. *
  28055. * @type {number}
  28056. * @default 1
  28057. */
  28058. this.specularIntensity = 1.0;
  28059. /**
  28060. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28061. * for per-pixel control over specular intensity.
  28062. *
  28063. * @type {?Texture}
  28064. * @default null
  28065. */
  28066. this.specularIntensityMap = null;
  28067. /**
  28068. * Tints the specular reflection at normal incidence for non-metals only.
  28069. *
  28070. * @type {Color}
  28071. * @default (1,1,1)
  28072. */
  28073. this.specularColor = new Color( 1, 1, 1 );
  28074. /**
  28075. * The RGB channels of this texture are multiplied against `specularColor`,
  28076. * for per-pixel control over specular color.
  28077. *
  28078. * @type {?Texture}
  28079. * @default null
  28080. */
  28081. this.specularColorMap = null;
  28082. this._anisotropy = 0;
  28083. this._clearcoat = 0;
  28084. this._dispersion = 0;
  28085. this._iridescence = 0;
  28086. this._sheen = 0.0;
  28087. this._transmission = 0;
  28088. this.setValues( parameters );
  28089. }
  28090. /**
  28091. * The anisotropy strength, from `0.0` to `1.0`.
  28092. *
  28093. * @type {number}
  28094. * @default 0
  28095. */
  28096. get anisotropy() {
  28097. return this._anisotropy;
  28098. }
  28099. set anisotropy( value ) {
  28100. if ( this._anisotropy > 0 !== value > 0 ) {
  28101. this.version ++;
  28102. }
  28103. this._anisotropy = value;
  28104. }
  28105. /**
  28106. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28107. * clear coat related properties to enable multilayer materials that have a
  28108. * thin translucent layer over the base layer.
  28109. *
  28110. * @type {number}
  28111. * @default 0
  28112. */
  28113. get clearcoat() {
  28114. return this._clearcoat;
  28115. }
  28116. set clearcoat( value ) {
  28117. if ( this._clearcoat > 0 !== value > 0 ) {
  28118. this.version ++;
  28119. }
  28120. this._clearcoat = value;
  28121. }
  28122. /**
  28123. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28124. * the surface and the viewer, from `0.0` to `1.0`.
  28125. *
  28126. * @type {number}
  28127. * @default 0
  28128. */
  28129. get iridescence() {
  28130. return this._iridescence;
  28131. }
  28132. set iridescence( value ) {
  28133. if ( this._iridescence > 0 !== value > 0 ) {
  28134. this.version ++;
  28135. }
  28136. this._iridescence = value;
  28137. }
  28138. /**
  28139. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28140. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28141. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28142. *
  28143. * @type {number}
  28144. * @default 0
  28145. */
  28146. get dispersion() {
  28147. return this._dispersion;
  28148. }
  28149. set dispersion( value ) {
  28150. if ( this._dispersion > 0 !== value > 0 ) {
  28151. this.version ++;
  28152. }
  28153. this._dispersion = value;
  28154. }
  28155. /**
  28156. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28157. *
  28158. * @type {number}
  28159. * @default 0
  28160. */
  28161. get sheen() {
  28162. return this._sheen;
  28163. }
  28164. set sheen( value ) {
  28165. if ( this._sheen > 0 !== value > 0 ) {
  28166. this.version ++;
  28167. }
  28168. this._sheen = value;
  28169. }
  28170. /**
  28171. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28172. *
  28173. * Thin, transparent or semitransparent, plastic or glass materials remain
  28174. * largely reflective even if they are fully transmissive. The transmission
  28175. * property can be used to model these materials.
  28176. *
  28177. * When transmission is non-zero, `opacity` should be set to `1`.
  28178. *
  28179. * @type {number}
  28180. * @default 0
  28181. */
  28182. get transmission() {
  28183. return this._transmission;
  28184. }
  28185. set transmission( value ) {
  28186. if ( this._transmission > 0 !== value > 0 ) {
  28187. this.version ++;
  28188. }
  28189. this._transmission = value;
  28190. }
  28191. copy( source ) {
  28192. super.copy( source );
  28193. this.defines = {
  28194. 'STANDARD': '',
  28195. 'PHYSICAL': ''
  28196. };
  28197. this.anisotropy = source.anisotropy;
  28198. this.anisotropyRotation = source.anisotropyRotation;
  28199. this.anisotropyMap = source.anisotropyMap;
  28200. this.clearcoat = source.clearcoat;
  28201. this.clearcoatMap = source.clearcoatMap;
  28202. this.clearcoatRoughness = source.clearcoatRoughness;
  28203. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28204. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28205. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28206. this.dispersion = source.dispersion;
  28207. this.ior = source.ior;
  28208. this.iridescence = source.iridescence;
  28209. this.iridescenceMap = source.iridescenceMap;
  28210. this.iridescenceIOR = source.iridescenceIOR;
  28211. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28212. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28213. this.sheen = source.sheen;
  28214. this.sheenColor.copy( source.sheenColor );
  28215. this.sheenColorMap = source.sheenColorMap;
  28216. this.sheenRoughness = source.sheenRoughness;
  28217. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28218. this.transmission = source.transmission;
  28219. this.transmissionMap = source.transmissionMap;
  28220. this.thickness = source.thickness;
  28221. this.thicknessMap = source.thicknessMap;
  28222. this.attenuationDistance = source.attenuationDistance;
  28223. this.attenuationColor.copy( source.attenuationColor );
  28224. this.specularIntensity = source.specularIntensity;
  28225. this.specularIntensityMap = source.specularIntensityMap;
  28226. this.specularColor.copy( source.specularColor );
  28227. this.specularColorMap = source.specularColorMap;
  28228. return this;
  28229. }
  28230. }
  28231. /**
  28232. * A material for shiny surfaces with specular highlights.
  28233. *
  28234. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28235. * model for calculating reflectance. Unlike the Lambertian model used in the
  28236. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28237. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28238. *
  28239. * Performance will generally be greater when using this material over the
  28240. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28241. * some graphical accuracy.
  28242. *
  28243. * @augments Material
  28244. * @demo scenes/material-browser.html#MeshPhongMaterial
  28245. */
  28246. class MeshPhongMaterial extends Material {
  28247. /**
  28248. * Constructs a new mesh phong material.
  28249. *
  28250. * @param {Object} [parameters] - An object with one or more properties
  28251. * defining the material's appearance. Any property of the material
  28252. * (including any property from inherited materials) can be passed
  28253. * in here. Color values can be passed any type of value accepted
  28254. * by {@link Color#set}.
  28255. */
  28256. constructor( parameters ) {
  28257. super();
  28258. /**
  28259. * This flag can be used for type testing.
  28260. *
  28261. * @type {boolean}
  28262. * @readonly
  28263. * @default true
  28264. */
  28265. this.isMeshPhongMaterial = true;
  28266. this.type = 'MeshPhongMaterial';
  28267. /**
  28268. * Color of the material.
  28269. *
  28270. * @type {Color}
  28271. * @default (1,1,1)
  28272. */
  28273. this.color = new Color( 0xffffff ); // diffuse
  28274. /**
  28275. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28276. *
  28277. * This defines how shiny the material is and the color of its shine.
  28278. *
  28279. * @type {Color}
  28280. */
  28281. this.specular = new Color( 0x111111 );
  28282. /**
  28283. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28284. *
  28285. * @type {number}
  28286. * @default 30
  28287. */
  28288. this.shininess = 30;
  28289. /**
  28290. * The color map. May optionally include an alpha channel, typically combined
  28291. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28292. * color is modulated by the diffuse `color`.
  28293. *
  28294. * @type {?Texture}
  28295. * @default null
  28296. */
  28297. this.map = null;
  28298. /**
  28299. * The light map. Requires a second set of UVs.
  28300. *
  28301. * @type {?Texture}
  28302. * @default null
  28303. */
  28304. this.lightMap = null;
  28305. /**
  28306. * Intensity of the baked light.
  28307. *
  28308. * @type {number}
  28309. * @default 1
  28310. */
  28311. this.lightMapIntensity = 1.0;
  28312. /**
  28313. * The red channel of this texture is used as the ambient occlusion map.
  28314. * Requires a second set of UVs.
  28315. *
  28316. * @type {?Texture}
  28317. * @default null
  28318. */
  28319. this.aoMap = null;
  28320. /**
  28321. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28322. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28323. * red channel is also `1`, ambient light is fully occluded on a surface.
  28324. *
  28325. * @type {number}
  28326. * @default 1
  28327. */
  28328. this.aoMapIntensity = 1.0;
  28329. /**
  28330. * Emissive (light) color of the material, essentially a solid color
  28331. * unaffected by other lighting.
  28332. *
  28333. * @type {Color}
  28334. * @default (0,0,0)
  28335. */
  28336. this.emissive = new Color( 0x000000 );
  28337. /**
  28338. * Intensity of the emissive light. Modulates the emissive color.
  28339. *
  28340. * @type {number}
  28341. * @default 1
  28342. */
  28343. this.emissiveIntensity = 1.0;
  28344. /**
  28345. * Set emissive (glow) map. The emissive map color is modulated by the
  28346. * emissive color and the emissive intensity. If you have an emissive map,
  28347. * be sure to set the emissive color to something other than black.
  28348. *
  28349. * @type {?Texture}
  28350. * @default null
  28351. */
  28352. this.emissiveMap = null;
  28353. /**
  28354. * The texture to create a bump map. The black and white values map to the
  28355. * perceived depth in relation to the lights. Bump doesn't actually affect
  28356. * the geometry of the object, only the lighting. If a normal map is defined
  28357. * this will be ignored.
  28358. *
  28359. * @type {?Texture}
  28360. * @default null
  28361. */
  28362. this.bumpMap = null;
  28363. /**
  28364. * How much the bump map affects the material. Typical range is `[0,1]`.
  28365. *
  28366. * @type {number}
  28367. * @default 1
  28368. */
  28369. this.bumpScale = 1;
  28370. /**
  28371. * The texture to create a normal map. The RGB values affect the surface
  28372. * normal for each pixel fragment and change the way the color is lit. Normal
  28373. * maps do not change the actual shape of the surface, only the lighting. In
  28374. * case the material has a normal map authored using the left handed
  28375. * convention, the `y` component of `normalScale` should be negated to compensate
  28376. * for the different handedness.
  28377. *
  28378. * @type {?Texture}
  28379. * @default null
  28380. */
  28381. this.normalMap = null;
  28382. /**
  28383. * The type of normal map.
  28384. *
  28385. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28386. * @default TangentSpaceNormalMap
  28387. */
  28388. this.normalMapType = TangentSpaceNormalMap;
  28389. /**
  28390. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28391. *
  28392. * @type {Vector2}
  28393. * @default (1,1)
  28394. */
  28395. this.normalScale = new Vector2( 1, 1 );
  28396. /**
  28397. * The displacement map affects the position of the mesh's vertices. Unlike
  28398. * other maps which only affect the light and shade of the material the
  28399. * displaced vertices can cast shadows, block other objects, and otherwise
  28400. * act as real geometry. The displacement texture is an image where the value
  28401. * of each pixel (white being the highest) is mapped against, and
  28402. * repositions, the vertices of the mesh.
  28403. *
  28404. * @type {?Texture}
  28405. * @default null
  28406. */
  28407. this.displacementMap = null;
  28408. /**
  28409. * How much the displacement map affects the mesh (where black is no
  28410. * displacement, and white is maximum displacement). Without a displacement
  28411. * map set, this value is not applied.
  28412. *
  28413. * @type {number}
  28414. * @default 0
  28415. */
  28416. this.displacementScale = 1;
  28417. /**
  28418. * The offset of the displacement map's values on the mesh's vertices.
  28419. * The bias is added to the scaled sample of the displacement map.
  28420. * Without a displacement map set, this value is not applied.
  28421. *
  28422. * @type {number}
  28423. * @default 0
  28424. */
  28425. this.displacementBias = 0;
  28426. /**
  28427. * The specular map value affects both how much the specular surface
  28428. * highlight contributes and how much of the environment map affects the
  28429. * surface.
  28430. *
  28431. * @type {?Texture}
  28432. * @default null
  28433. */
  28434. this.specularMap = null;
  28435. /**
  28436. * The alpha map is a grayscale texture that controls the opacity across the
  28437. * surface (black: fully transparent; white: fully opaque).
  28438. *
  28439. * Only the color of the texture is used, ignoring the alpha channel if one
  28440. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28441. * when sampling this texture due to the extra bit of precision provided for
  28442. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28443. * luminance/alpha textures will also still work as expected.
  28444. *
  28445. * @type {?Texture}
  28446. * @default null
  28447. */
  28448. this.alphaMap = null;
  28449. /**
  28450. * The environment map.
  28451. *
  28452. * @type {?Texture}
  28453. * @default null
  28454. */
  28455. this.envMap = null;
  28456. /**
  28457. * The rotation of the environment map in radians.
  28458. *
  28459. * @type {Euler}
  28460. * @default (0,0,0)
  28461. */
  28462. this.envMapRotation = new Euler();
  28463. /**
  28464. * How to combine the result of the surface's color with the environment map, if any.
  28465. *
  28466. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28467. * blend between the two colors.
  28468. *
  28469. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28470. * @default MultiplyOperation
  28471. */
  28472. this.combine = MultiplyOperation;
  28473. /**
  28474. * How much the environment map affects the surface.
  28475. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28476. *
  28477. * @type {number}
  28478. * @default 1
  28479. */
  28480. this.reflectivity = 1;
  28481. /**
  28482. * Scales the effect of the environment map by multiplying its color.
  28483. *
  28484. * @type {number}
  28485. * @default 1
  28486. */
  28487. this.envMapIntensity = 1.0;
  28488. /**
  28489. * The index of refraction (IOR) of air (approximately 1) divided by the
  28490. * index of refraction of the material. It is used with environment mapping
  28491. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28492. * The refraction ratio should not exceed `1`.
  28493. *
  28494. * @type {number}
  28495. * @default 0.98
  28496. */
  28497. this.refractionRatio = 0.98;
  28498. /**
  28499. * Renders the geometry as a wireframe.
  28500. *
  28501. * @type {boolean}
  28502. * @default false
  28503. */
  28504. this.wireframe = false;
  28505. /**
  28506. * Controls the thickness of the wireframe.
  28507. *
  28508. * Can only be used with {@link SVGRenderer}.
  28509. *
  28510. * @type {number}
  28511. * @default 1
  28512. */
  28513. this.wireframeLinewidth = 1;
  28514. /**
  28515. * Defines appearance of wireframe ends.
  28516. *
  28517. * Can only be used with {@link SVGRenderer}.
  28518. *
  28519. * @type {('round'|'bevel'|'miter')}
  28520. * @default 'round'
  28521. */
  28522. this.wireframeLinecap = 'round';
  28523. /**
  28524. * Defines appearance of wireframe joints.
  28525. *
  28526. * Can only be used with {@link SVGRenderer}.
  28527. *
  28528. * @type {('round'|'bevel'|'miter')}
  28529. * @default 'round'
  28530. */
  28531. this.wireframeLinejoin = 'round';
  28532. /**
  28533. * Whether the material is rendered with flat shading or not.
  28534. *
  28535. * @type {boolean}
  28536. * @default false
  28537. */
  28538. this.flatShading = false;
  28539. /**
  28540. * Whether the material is affected by fog or not.
  28541. *
  28542. * @type {boolean}
  28543. * @default true
  28544. */
  28545. this.fog = true;
  28546. this.setValues( parameters );
  28547. }
  28548. copy( source ) {
  28549. super.copy( source );
  28550. this.color.copy( source.color );
  28551. this.specular.copy( source.specular );
  28552. this.shininess = source.shininess;
  28553. this.map = source.map;
  28554. this.lightMap = source.lightMap;
  28555. this.lightMapIntensity = source.lightMapIntensity;
  28556. this.aoMap = source.aoMap;
  28557. this.aoMapIntensity = source.aoMapIntensity;
  28558. this.emissive.copy( source.emissive );
  28559. this.emissiveMap = source.emissiveMap;
  28560. this.emissiveIntensity = source.emissiveIntensity;
  28561. this.bumpMap = source.bumpMap;
  28562. this.bumpScale = source.bumpScale;
  28563. this.normalMap = source.normalMap;
  28564. this.normalMapType = source.normalMapType;
  28565. this.normalScale.copy( source.normalScale );
  28566. this.displacementMap = source.displacementMap;
  28567. this.displacementScale = source.displacementScale;
  28568. this.displacementBias = source.displacementBias;
  28569. this.specularMap = source.specularMap;
  28570. this.alphaMap = source.alphaMap;
  28571. this.envMap = source.envMap;
  28572. this.envMapRotation.copy( source.envMapRotation );
  28573. this.combine = source.combine;
  28574. this.reflectivity = source.reflectivity;
  28575. this.envMapIntensity = source.envMapIntensity;
  28576. this.refractionRatio = source.refractionRatio;
  28577. this.wireframe = source.wireframe;
  28578. this.wireframeLinewidth = source.wireframeLinewidth;
  28579. this.wireframeLinecap = source.wireframeLinecap;
  28580. this.wireframeLinejoin = source.wireframeLinejoin;
  28581. this.flatShading = source.flatShading;
  28582. this.fog = source.fog;
  28583. return this;
  28584. }
  28585. }
  28586. /**
  28587. * A material implementing toon shading.
  28588. *
  28589. * @augments Material
  28590. * @demo scenes/material-browser.html#MeshToonMaterial
  28591. */
  28592. class MeshToonMaterial extends Material {
  28593. /**
  28594. * Constructs a new mesh toon material.
  28595. *
  28596. * @param {Object} [parameters] - An object with one or more properties
  28597. * defining the material's appearance. Any property of the material
  28598. * (including any property from inherited materials) can be passed
  28599. * in here. Color values can be passed any type of value accepted
  28600. * by {@link Color#set}.
  28601. */
  28602. constructor( parameters ) {
  28603. super();
  28604. /**
  28605. * This flag can be used for type testing.
  28606. *
  28607. * @type {boolean}
  28608. * @readonly
  28609. * @default true
  28610. */
  28611. this.isMeshToonMaterial = true;
  28612. this.defines = { 'TOON': '' };
  28613. this.type = 'MeshToonMaterial';
  28614. /**
  28615. * Color of the material.
  28616. *
  28617. * @type {Color}
  28618. * @default (1,1,1)
  28619. */
  28620. this.color = new Color( 0xffffff );
  28621. /**
  28622. * The color map. May optionally include an alpha channel, typically combined
  28623. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28624. * color is modulated by the diffuse `color`.
  28625. *
  28626. * @type {?Texture}
  28627. * @default null
  28628. */
  28629. this.map = null;
  28630. /**
  28631. * Gradient map for toon shading. It's required to set
  28632. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28633. * when using this type of texture.
  28634. *
  28635. * @type {?Texture}
  28636. * @default null
  28637. */
  28638. this.gradientMap = null;
  28639. /**
  28640. * The light map. Requires a second set of UVs.
  28641. *
  28642. * @type {?Texture}
  28643. * @default null
  28644. */
  28645. this.lightMap = null;
  28646. /**
  28647. * Intensity of the baked light.
  28648. *
  28649. * @type {number}
  28650. * @default 1
  28651. */
  28652. this.lightMapIntensity = 1.0;
  28653. /**
  28654. * The red channel of this texture is used as the ambient occlusion map.
  28655. * Requires a second set of UVs.
  28656. *
  28657. * @type {?Texture}
  28658. * @default null
  28659. */
  28660. this.aoMap = null;
  28661. /**
  28662. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28663. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28664. * red channel is also `1`, ambient light is fully occluded on a surface.
  28665. *
  28666. * @type {number}
  28667. * @default 1
  28668. */
  28669. this.aoMapIntensity = 1.0;
  28670. /**
  28671. * Emissive (light) color of the material, essentially a solid color
  28672. * unaffected by other lighting.
  28673. *
  28674. * @type {Color}
  28675. * @default (0,0,0)
  28676. */
  28677. this.emissive = new Color( 0x000000 );
  28678. /**
  28679. * Intensity of the emissive light. Modulates the emissive color.
  28680. *
  28681. * @type {number}
  28682. * @default 1
  28683. */
  28684. this.emissiveIntensity = 1.0;
  28685. /**
  28686. * Set emissive (glow) map. The emissive map color is modulated by the
  28687. * emissive color and the emissive intensity. If you have an emissive map,
  28688. * be sure to set the emissive color to something other than black.
  28689. *
  28690. * @type {?Texture}
  28691. * @default null
  28692. */
  28693. this.emissiveMap = null;
  28694. /**
  28695. * The texture to create a bump map. The black and white values map to the
  28696. * perceived depth in relation to the lights. Bump doesn't actually affect
  28697. * the geometry of the object, only the lighting. If a normal map is defined
  28698. * this will be ignored.
  28699. *
  28700. * @type {?Texture}
  28701. * @default null
  28702. */
  28703. this.bumpMap = null;
  28704. /**
  28705. * How much the bump map affects the material. Typical range is `[0,1]`.
  28706. *
  28707. * @type {number}
  28708. * @default 1
  28709. */
  28710. this.bumpScale = 1;
  28711. /**
  28712. * The texture to create a normal map. The RGB values affect the surface
  28713. * normal for each pixel fragment and change the way the color is lit. Normal
  28714. * maps do not change the actual shape of the surface, only the lighting. In
  28715. * case the material has a normal map authored using the left handed
  28716. * convention, the `y` component of `normalScale` should be negated to compensate
  28717. * for the different handedness.
  28718. *
  28719. * @type {?Texture}
  28720. * @default null
  28721. */
  28722. this.normalMap = null;
  28723. /**
  28724. * The type of normal map.
  28725. *
  28726. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28727. * @default TangentSpaceNormalMap
  28728. */
  28729. this.normalMapType = TangentSpaceNormalMap;
  28730. /**
  28731. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28732. *
  28733. * @type {Vector2}
  28734. * @default (1,1)
  28735. */
  28736. this.normalScale = new Vector2( 1, 1 );
  28737. /**
  28738. * The displacement map affects the position of the mesh's vertices. Unlike
  28739. * other maps which only affect the light and shade of the material the
  28740. * displaced vertices can cast shadows, block other objects, and otherwise
  28741. * act as real geometry. The displacement texture is an image where the value
  28742. * of each pixel (white being the highest) is mapped against, and
  28743. * repositions, the vertices of the mesh.
  28744. *
  28745. * @type {?Texture}
  28746. * @default null
  28747. */
  28748. this.displacementMap = null;
  28749. /**
  28750. * How much the displacement map affects the mesh (where black is no
  28751. * displacement, and white is maximum displacement). Without a displacement
  28752. * map set, this value is not applied.
  28753. *
  28754. * @type {number}
  28755. * @default 0
  28756. */
  28757. this.displacementScale = 1;
  28758. /**
  28759. * The offset of the displacement map's values on the mesh's vertices.
  28760. * The bias is added to the scaled sample of the displacement map.
  28761. * Without a displacement map set, this value is not applied.
  28762. *
  28763. * @type {number}
  28764. * @default 0
  28765. */
  28766. this.displacementBias = 0;
  28767. /**
  28768. * The alpha map is a grayscale texture that controls the opacity across the
  28769. * surface (black: fully transparent; white: fully opaque).
  28770. *
  28771. * Only the color of the texture is used, ignoring the alpha channel if one
  28772. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28773. * when sampling this texture due to the extra bit of precision provided for
  28774. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28775. * luminance/alpha textures will also still work as expected.
  28776. *
  28777. * @type {?Texture}
  28778. * @default null
  28779. */
  28780. this.alphaMap = null;
  28781. /**
  28782. * Renders the geometry as a wireframe.
  28783. *
  28784. * @type {boolean}
  28785. * @default false
  28786. */
  28787. this.wireframe = false;
  28788. /**
  28789. * Controls the thickness of the wireframe.
  28790. *
  28791. * Can only be used with {@link SVGRenderer}.
  28792. *
  28793. * @type {number}
  28794. * @default 1
  28795. */
  28796. this.wireframeLinewidth = 1;
  28797. /**
  28798. * Defines appearance of wireframe ends.
  28799. *
  28800. * Can only be used with {@link SVGRenderer}.
  28801. *
  28802. * @type {('round'|'bevel'|'miter')}
  28803. * @default 'round'
  28804. */
  28805. this.wireframeLinecap = 'round';
  28806. /**
  28807. * Defines appearance of wireframe joints.
  28808. *
  28809. * Can only be used with {@link SVGRenderer}.
  28810. *
  28811. * @type {('round'|'bevel'|'miter')}
  28812. * @default 'round'
  28813. */
  28814. this.wireframeLinejoin = 'round';
  28815. /**
  28816. * Whether the material is affected by fog or not.
  28817. *
  28818. * @type {boolean}
  28819. * @default true
  28820. */
  28821. this.fog = true;
  28822. this.setValues( parameters );
  28823. }
  28824. copy( source ) {
  28825. super.copy( source );
  28826. this.color.copy( source.color );
  28827. this.map = source.map;
  28828. this.gradientMap = source.gradientMap;
  28829. this.lightMap = source.lightMap;
  28830. this.lightMapIntensity = source.lightMapIntensity;
  28831. this.aoMap = source.aoMap;
  28832. this.aoMapIntensity = source.aoMapIntensity;
  28833. this.emissive.copy( source.emissive );
  28834. this.emissiveMap = source.emissiveMap;
  28835. this.emissiveIntensity = source.emissiveIntensity;
  28836. this.bumpMap = source.bumpMap;
  28837. this.bumpScale = source.bumpScale;
  28838. this.normalMap = source.normalMap;
  28839. this.normalMapType = source.normalMapType;
  28840. this.normalScale.copy( source.normalScale );
  28841. this.displacementMap = source.displacementMap;
  28842. this.displacementScale = source.displacementScale;
  28843. this.displacementBias = source.displacementBias;
  28844. this.alphaMap = source.alphaMap;
  28845. this.wireframe = source.wireframe;
  28846. this.wireframeLinewidth = source.wireframeLinewidth;
  28847. this.wireframeLinecap = source.wireframeLinecap;
  28848. this.wireframeLinejoin = source.wireframeLinejoin;
  28849. this.fog = source.fog;
  28850. return this;
  28851. }
  28852. }
  28853. /**
  28854. * A material that maps the normal vectors to RGB colors.
  28855. *
  28856. * @augments Material
  28857. * @demo scenes/material-browser.html#MeshNormalMaterial
  28858. */
  28859. class MeshNormalMaterial extends Material {
  28860. /**
  28861. * Constructs a new mesh normal material.
  28862. *
  28863. * @param {Object} [parameters] - An object with one or more properties
  28864. * defining the material's appearance. Any property of the material
  28865. * (including any property from inherited materials) can be passed
  28866. * in here. Color values can be passed any type of value accepted
  28867. * by {@link Color#set}.
  28868. */
  28869. constructor( parameters ) {
  28870. super();
  28871. /**
  28872. * This flag can be used for type testing.
  28873. *
  28874. * @type {boolean}
  28875. * @readonly
  28876. * @default true
  28877. */
  28878. this.isMeshNormalMaterial = true;
  28879. this.type = 'MeshNormalMaterial';
  28880. /**
  28881. * The texture to create a bump map. The black and white values map to the
  28882. * perceived depth in relation to the lights. Bump doesn't actually affect
  28883. * the geometry of the object, only the lighting. If a normal map is defined
  28884. * this will be ignored.
  28885. *
  28886. * @type {?Texture}
  28887. * @default null
  28888. */
  28889. this.bumpMap = null;
  28890. /**
  28891. * How much the bump map affects the material. Typical range is `[0,1]`.
  28892. *
  28893. * @type {number}
  28894. * @default 1
  28895. */
  28896. this.bumpScale = 1;
  28897. /**
  28898. * The texture to create a normal map. The RGB values affect the surface
  28899. * normal for each pixel fragment and change the way the color is lit. Normal
  28900. * maps do not change the actual shape of the surface, only the lighting. In
  28901. * case the material has a normal map authored using the left handed
  28902. * convention, the `y` component of `normalScale` should be negated to compensate
  28903. * for the different handedness.
  28904. *
  28905. * @type {?Texture}
  28906. * @default null
  28907. */
  28908. this.normalMap = null;
  28909. /**
  28910. * The type of normal map.
  28911. *
  28912. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28913. * @default TangentSpaceNormalMap
  28914. */
  28915. this.normalMapType = TangentSpaceNormalMap;
  28916. /**
  28917. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28918. *
  28919. * @type {Vector2}
  28920. * @default (1,1)
  28921. */
  28922. this.normalScale = new Vector2( 1, 1 );
  28923. /**
  28924. * The displacement map affects the position of the mesh's vertices. Unlike
  28925. * other maps which only affect the light and shade of the material the
  28926. * displaced vertices can cast shadows, block other objects, and otherwise
  28927. * act as real geometry. The displacement texture is an image where the value
  28928. * of each pixel (white being the highest) is mapped against, and
  28929. * repositions, the vertices of the mesh.
  28930. *
  28931. * @type {?Texture}
  28932. * @default null
  28933. */
  28934. this.displacementMap = null;
  28935. /**
  28936. * How much the displacement map affects the mesh (where black is no
  28937. * displacement, and white is maximum displacement). Without a displacement
  28938. * map set, this value is not applied.
  28939. *
  28940. * @type {number}
  28941. * @default 0
  28942. */
  28943. this.displacementScale = 1;
  28944. /**
  28945. * The offset of the displacement map's values on the mesh's vertices.
  28946. * The bias is added to the scaled sample of the displacement map.
  28947. * Without a displacement map set, this value is not applied.
  28948. *
  28949. * @type {number}
  28950. * @default 0
  28951. */
  28952. this.displacementBias = 0;
  28953. /**
  28954. * Renders the geometry as a wireframe.
  28955. *
  28956. * @type {boolean}
  28957. * @default false
  28958. */
  28959. this.wireframe = false;
  28960. /**
  28961. * Controls the thickness of the wireframe.
  28962. *
  28963. * WebGL and WebGPU ignore this property and always render
  28964. * 1 pixel wide lines.
  28965. *
  28966. * @type {number}
  28967. * @default 1
  28968. */
  28969. this.wireframeLinewidth = 1;
  28970. /**
  28971. * Whether the material is rendered with flat shading or not.
  28972. *
  28973. * @type {boolean}
  28974. * @default false
  28975. */
  28976. this.flatShading = false;
  28977. this.setValues( parameters );
  28978. }
  28979. copy( source ) {
  28980. super.copy( source );
  28981. this.bumpMap = source.bumpMap;
  28982. this.bumpScale = source.bumpScale;
  28983. this.normalMap = source.normalMap;
  28984. this.normalMapType = source.normalMapType;
  28985. this.normalScale.copy( source.normalScale );
  28986. this.displacementMap = source.displacementMap;
  28987. this.displacementScale = source.displacementScale;
  28988. this.displacementBias = source.displacementBias;
  28989. this.wireframe = source.wireframe;
  28990. this.wireframeLinewidth = source.wireframeLinewidth;
  28991. this.flatShading = source.flatShading;
  28992. return this;
  28993. }
  28994. }
  28995. /**
  28996. * A material for non-shiny surfaces, without specular highlights.
  28997. *
  28998. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  28999. * model for calculating reflectance. This can simulate some surfaces (such
  29000. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29001. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29002. * shading.
  29003. *
  29004. * Due to the simplicity of the reflectance and illumination models,
  29005. * performance will be greater when using this material over the
  29006. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29007. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29008. *
  29009. * @augments Material
  29010. * @demo scenes/material-browser.html#MeshLambertMaterial
  29011. */
  29012. class MeshLambertMaterial extends Material {
  29013. /**
  29014. * Constructs a new mesh lambert material.
  29015. *
  29016. * @param {Object} [parameters] - An object with one or more properties
  29017. * defining the material's appearance. Any property of the material
  29018. * (including any property from inherited materials) can be passed
  29019. * in here. Color values can be passed any type of value accepted
  29020. * by {@link Color#set}.
  29021. */
  29022. constructor( parameters ) {
  29023. super();
  29024. /**
  29025. * This flag can be used for type testing.
  29026. *
  29027. * @type {boolean}
  29028. * @readonly
  29029. * @default true
  29030. */
  29031. this.isMeshLambertMaterial = true;
  29032. this.type = 'MeshLambertMaterial';
  29033. /**
  29034. * Color of the material.
  29035. *
  29036. * @type {Color}
  29037. * @default (1,1,1)
  29038. */
  29039. this.color = new Color( 0xffffff ); // diffuse
  29040. /**
  29041. * The color map. May optionally include an alpha channel, typically combined
  29042. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29043. * color is modulated by the diffuse `color`.
  29044. *
  29045. * @type {?Texture}
  29046. * @default null
  29047. */
  29048. this.map = null;
  29049. /**
  29050. * The light map. Requires a second set of UVs.
  29051. *
  29052. * @type {?Texture}
  29053. * @default null
  29054. */
  29055. this.lightMap = null;
  29056. /**
  29057. * Intensity of the baked light.
  29058. *
  29059. * @type {number}
  29060. * @default 1
  29061. */
  29062. this.lightMapIntensity = 1.0;
  29063. /**
  29064. * The red channel of this texture is used as the ambient occlusion map.
  29065. * Requires a second set of UVs.
  29066. *
  29067. * @type {?Texture}
  29068. * @default null
  29069. */
  29070. this.aoMap = null;
  29071. /**
  29072. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29073. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29074. * red channel is also `1`, ambient light is fully occluded on a surface.
  29075. *
  29076. * @type {number}
  29077. * @default 1
  29078. */
  29079. this.aoMapIntensity = 1.0;
  29080. /**
  29081. * Emissive (light) color of the material, essentially a solid color
  29082. * unaffected by other lighting.
  29083. *
  29084. * @type {Color}
  29085. * @default (0,0,0)
  29086. */
  29087. this.emissive = new Color( 0x000000 );
  29088. /**
  29089. * Intensity of the emissive light. Modulates the emissive color.
  29090. *
  29091. * @type {number}
  29092. * @default 1
  29093. */
  29094. this.emissiveIntensity = 1.0;
  29095. /**
  29096. * Set emissive (glow) map. The emissive map color is modulated by the
  29097. * emissive color and the emissive intensity. If you have an emissive map,
  29098. * be sure to set the emissive color to something other than black.
  29099. *
  29100. * @type {?Texture}
  29101. * @default null
  29102. */
  29103. this.emissiveMap = null;
  29104. /**
  29105. * The texture to create a bump map. The black and white values map to the
  29106. * perceived depth in relation to the lights. Bump doesn't actually affect
  29107. * the geometry of the object, only the lighting. If a normal map is defined
  29108. * this will be ignored.
  29109. *
  29110. * @type {?Texture}
  29111. * @default null
  29112. */
  29113. this.bumpMap = null;
  29114. /**
  29115. * How much the bump map affects the material. Typical range is `[0,1]`.
  29116. *
  29117. * @type {number}
  29118. * @default 1
  29119. */
  29120. this.bumpScale = 1;
  29121. /**
  29122. * The texture to create a normal map. The RGB values affect the surface
  29123. * normal for each pixel fragment and change the way the color is lit. Normal
  29124. * maps do not change the actual shape of the surface, only the lighting. In
  29125. * case the material has a normal map authored using the left handed
  29126. * convention, the `y` component of `normalScale` should be negated to compensate
  29127. * for the different handedness.
  29128. *
  29129. * @type {?Texture}
  29130. * @default null
  29131. */
  29132. this.normalMap = null;
  29133. /**
  29134. * The type of normal map.
  29135. *
  29136. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29137. * @default TangentSpaceNormalMap
  29138. */
  29139. this.normalMapType = TangentSpaceNormalMap;
  29140. /**
  29141. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29142. *
  29143. * @type {Vector2}
  29144. * @default (1,1)
  29145. */
  29146. this.normalScale = new Vector2( 1, 1 );
  29147. /**
  29148. * The displacement map affects the position of the mesh's vertices. Unlike
  29149. * other maps which only affect the light and shade of the material the
  29150. * displaced vertices can cast shadows, block other objects, and otherwise
  29151. * act as real geometry. The displacement texture is an image where the value
  29152. * of each pixel (white being the highest) is mapped against, and
  29153. * repositions, the vertices of the mesh.
  29154. *
  29155. * @type {?Texture}
  29156. * @default null
  29157. */
  29158. this.displacementMap = null;
  29159. /**
  29160. * How much the displacement map affects the mesh (where black is no
  29161. * displacement, and white is maximum displacement). Without a displacement
  29162. * map set, this value is not applied.
  29163. *
  29164. * @type {number}
  29165. * @default 0
  29166. */
  29167. this.displacementScale = 1;
  29168. /**
  29169. * The offset of the displacement map's values on the mesh's vertices.
  29170. * The bias is added to the scaled sample of the displacement map.
  29171. * Without a displacement map set, this value is not applied.
  29172. *
  29173. * @type {number}
  29174. * @default 0
  29175. */
  29176. this.displacementBias = 0;
  29177. /**
  29178. * Specular map used by the material.
  29179. *
  29180. * @type {?Texture}
  29181. * @default null
  29182. */
  29183. this.specularMap = null;
  29184. /**
  29185. * The alpha map is a grayscale texture that controls the opacity across the
  29186. * surface (black: fully transparent; white: fully opaque).
  29187. *
  29188. * Only the color of the texture is used, ignoring the alpha channel if one
  29189. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29190. * when sampling this texture due to the extra bit of precision provided for
  29191. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29192. * luminance/alpha textures will also still work as expected.
  29193. *
  29194. * @type {?Texture}
  29195. * @default null
  29196. */
  29197. this.alphaMap = null;
  29198. /**
  29199. * The environment map.
  29200. *
  29201. * @type {?Texture}
  29202. * @default null
  29203. */
  29204. this.envMap = null;
  29205. /**
  29206. * The rotation of the environment map in radians.
  29207. *
  29208. * @type {Euler}
  29209. * @default (0,0,0)
  29210. */
  29211. this.envMapRotation = new Euler();
  29212. /**
  29213. * How to combine the result of the surface's color with the environment map, if any.
  29214. *
  29215. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29216. * blend between the two colors.
  29217. *
  29218. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29219. * @default MultiplyOperation
  29220. */
  29221. this.combine = MultiplyOperation;
  29222. /**
  29223. * How much the environment map affects the surface.
  29224. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29225. *
  29226. * @type {number}
  29227. * @default 1
  29228. */
  29229. this.reflectivity = 1;
  29230. /**
  29231. * Scales the effect of the environment map by multiplying its color.
  29232. *
  29233. * @type {number}
  29234. * @default 1
  29235. */
  29236. this.envMapIntensity = 1.0;
  29237. /**
  29238. * The index of refraction (IOR) of air (approximately 1) divided by the
  29239. * index of refraction of the material. It is used with environment mapping
  29240. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29241. * The refraction ratio should not exceed `1`.
  29242. *
  29243. * @type {number}
  29244. * @default 0.98
  29245. */
  29246. this.refractionRatio = 0.98;
  29247. /**
  29248. * Renders the geometry as a wireframe.
  29249. *
  29250. * @type {boolean}
  29251. * @default false
  29252. */
  29253. this.wireframe = false;
  29254. /**
  29255. * Controls the thickness of the wireframe.
  29256. *
  29257. * Can only be used with {@link SVGRenderer}.
  29258. *
  29259. * @type {number}
  29260. * @default 1
  29261. */
  29262. this.wireframeLinewidth = 1;
  29263. /**
  29264. * Defines appearance of wireframe ends.
  29265. *
  29266. * Can only be used with {@link SVGRenderer}.
  29267. *
  29268. * @type {('round'|'bevel'|'miter')}
  29269. * @default 'round'
  29270. */
  29271. this.wireframeLinecap = 'round';
  29272. /**
  29273. * Defines appearance of wireframe joints.
  29274. *
  29275. * Can only be used with {@link SVGRenderer}.
  29276. *
  29277. * @type {('round'|'bevel'|'miter')}
  29278. * @default 'round'
  29279. */
  29280. this.wireframeLinejoin = 'round';
  29281. /**
  29282. * Whether the material is rendered with flat shading or not.
  29283. *
  29284. * @type {boolean}
  29285. * @default false
  29286. */
  29287. this.flatShading = false;
  29288. /**
  29289. * Whether the material is affected by fog or not.
  29290. *
  29291. * @type {boolean}
  29292. * @default true
  29293. */
  29294. this.fog = true;
  29295. this.setValues( parameters );
  29296. }
  29297. copy( source ) {
  29298. super.copy( source );
  29299. this.color.copy( source.color );
  29300. this.map = source.map;
  29301. this.lightMap = source.lightMap;
  29302. this.lightMapIntensity = source.lightMapIntensity;
  29303. this.aoMap = source.aoMap;
  29304. this.aoMapIntensity = source.aoMapIntensity;
  29305. this.emissive.copy( source.emissive );
  29306. this.emissiveMap = source.emissiveMap;
  29307. this.emissiveIntensity = source.emissiveIntensity;
  29308. this.bumpMap = source.bumpMap;
  29309. this.bumpScale = source.bumpScale;
  29310. this.normalMap = source.normalMap;
  29311. this.normalMapType = source.normalMapType;
  29312. this.normalScale.copy( source.normalScale );
  29313. this.displacementMap = source.displacementMap;
  29314. this.displacementScale = source.displacementScale;
  29315. this.displacementBias = source.displacementBias;
  29316. this.specularMap = source.specularMap;
  29317. this.alphaMap = source.alphaMap;
  29318. this.envMap = source.envMap;
  29319. this.envMapRotation.copy( source.envMapRotation );
  29320. this.combine = source.combine;
  29321. this.reflectivity = source.reflectivity;
  29322. this.envMapIntensity = source.envMapIntensity;
  29323. this.refractionRatio = source.refractionRatio;
  29324. this.wireframe = source.wireframe;
  29325. this.wireframeLinewidth = source.wireframeLinewidth;
  29326. this.wireframeLinecap = source.wireframeLinecap;
  29327. this.wireframeLinejoin = source.wireframeLinejoin;
  29328. this.flatShading = source.flatShading;
  29329. this.fog = source.fog;
  29330. return this;
  29331. }
  29332. }
  29333. /**
  29334. * A material for drawing geometry by depth. Depth is based off of the camera
  29335. * near and far plane. White is nearest, black is farthest.
  29336. *
  29337. * @augments Material
  29338. * @demo scenes/material-browser.html#MeshDepthMaterial
  29339. */
  29340. class MeshDepthMaterial extends Material {
  29341. /**
  29342. * Constructs a new mesh depth material.
  29343. *
  29344. * @param {Object} [parameters] - An object with one or more properties
  29345. * defining the material's appearance. Any property of the material
  29346. * (including any property from inherited materials) can be passed
  29347. * in here. Color values can be passed any type of value accepted
  29348. * by {@link Color#set}.
  29349. */
  29350. constructor( parameters ) {
  29351. super();
  29352. /**
  29353. * This flag can be used for type testing.
  29354. *
  29355. * @type {boolean}
  29356. * @readonly
  29357. * @default true
  29358. */
  29359. this.isMeshDepthMaterial = true;
  29360. this.type = 'MeshDepthMaterial';
  29361. /**
  29362. * Type for depth packing.
  29363. *
  29364. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29365. * @default BasicDepthPacking
  29366. */
  29367. this.depthPacking = BasicDepthPacking;
  29368. /**
  29369. * The color map. May optionally include an alpha channel, typically combined
  29370. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29371. *
  29372. * @type {?Texture}
  29373. * @default null
  29374. */
  29375. this.map = null;
  29376. /**
  29377. * The alpha map is a grayscale texture that controls the opacity across the
  29378. * surface (black: fully transparent; white: fully opaque).
  29379. *
  29380. * Only the color of the texture is used, ignoring the alpha channel if one
  29381. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29382. * when sampling this texture due to the extra bit of precision provided for
  29383. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29384. * luminance/alpha textures will also still work as expected.
  29385. *
  29386. * @type {?Texture}
  29387. * @default null
  29388. */
  29389. this.alphaMap = null;
  29390. /**
  29391. * The displacement map affects the position of the mesh's vertices. Unlike
  29392. * other maps which only affect the light and shade of the material the
  29393. * displaced vertices can cast shadows, block other objects, and otherwise
  29394. * act as real geometry. The displacement texture is an image where the value
  29395. * of each pixel (white being the highest) is mapped against, and
  29396. * repositions, the vertices of the mesh.
  29397. *
  29398. * @type {?Texture}
  29399. * @default null
  29400. */
  29401. this.displacementMap = null;
  29402. /**
  29403. * How much the displacement map affects the mesh (where black is no
  29404. * displacement, and white is maximum displacement). Without a displacement
  29405. * map set, this value is not applied.
  29406. *
  29407. * @type {number}
  29408. * @default 0
  29409. */
  29410. this.displacementScale = 1;
  29411. /**
  29412. * The offset of the displacement map's values on the mesh's vertices.
  29413. * The bias is added to the scaled sample of the displacement map.
  29414. * Without a displacement map set, this value is not applied.
  29415. *
  29416. * @type {number}
  29417. * @default 0
  29418. */
  29419. this.displacementBias = 0;
  29420. /**
  29421. * Renders the geometry as a wireframe.
  29422. *
  29423. * @type {boolean}
  29424. * @default false
  29425. */
  29426. this.wireframe = false;
  29427. /**
  29428. * Controls the thickness of the wireframe.
  29429. *
  29430. * WebGL and WebGPU ignore this property and always render
  29431. * 1 pixel wide lines.
  29432. *
  29433. * @type {number}
  29434. * @default 1
  29435. */
  29436. this.wireframeLinewidth = 1;
  29437. this.setValues( parameters );
  29438. }
  29439. copy( source ) {
  29440. super.copy( source );
  29441. this.depthPacking = source.depthPacking;
  29442. this.map = source.map;
  29443. this.alphaMap = source.alphaMap;
  29444. this.displacementMap = source.displacementMap;
  29445. this.displacementScale = source.displacementScale;
  29446. this.displacementBias = source.displacementBias;
  29447. this.wireframe = source.wireframe;
  29448. this.wireframeLinewidth = source.wireframeLinewidth;
  29449. return this;
  29450. }
  29451. }
  29452. /**
  29453. * A material used internally for implementing shadow mapping with
  29454. * point lights.
  29455. *
  29456. * Can also be used to customize the shadow casting of an object by assigning
  29457. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29458. * The following examples demonstrates this approach in order to ensure
  29459. * transparent parts of objects do not cast shadows.
  29460. *
  29461. * @augments Material
  29462. */
  29463. class MeshDistanceMaterial extends Material {
  29464. /**
  29465. * Constructs a new mesh distance material.
  29466. *
  29467. * @param {Object} [parameters] - An object with one or more properties
  29468. * defining the material's appearance. Any property of the material
  29469. * (including any property from inherited materials) can be passed
  29470. * in here. Color values can be passed any type of value accepted
  29471. * by {@link Color#set}.
  29472. */
  29473. constructor( parameters ) {
  29474. super();
  29475. /**
  29476. * This flag can be used for type testing.
  29477. *
  29478. * @type {boolean}
  29479. * @readonly
  29480. * @default true
  29481. */
  29482. this.isMeshDistanceMaterial = true;
  29483. this.type = 'MeshDistanceMaterial';
  29484. /**
  29485. * The color map. May optionally include an alpha channel, typically combined
  29486. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29487. *
  29488. * @type {?Texture}
  29489. * @default null
  29490. */
  29491. this.map = null;
  29492. /**
  29493. * The alpha map is a grayscale texture that controls the opacity across the
  29494. * surface (black: fully transparent; white: fully opaque).
  29495. *
  29496. * Only the color of the texture is used, ignoring the alpha channel if one
  29497. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29498. * when sampling this texture due to the extra bit of precision provided for
  29499. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29500. * luminance/alpha textures will also still work as expected.
  29501. *
  29502. * @type {?Texture}
  29503. * @default null
  29504. */
  29505. this.alphaMap = null;
  29506. /**
  29507. * The displacement map affects the position of the mesh's vertices. Unlike
  29508. * other maps which only affect the light and shade of the material the
  29509. * displaced vertices can cast shadows, block other objects, and otherwise
  29510. * act as real geometry. The displacement texture is an image where the value
  29511. * of each pixel (white being the highest) is mapped against, and
  29512. * repositions, the vertices of the mesh.
  29513. *
  29514. * @type {?Texture}
  29515. * @default null
  29516. */
  29517. this.displacementMap = null;
  29518. /**
  29519. * How much the displacement map affects the mesh (where black is no
  29520. * displacement, and white is maximum displacement). Without a displacement
  29521. * map set, this value is not applied.
  29522. *
  29523. * @type {number}
  29524. * @default 0
  29525. */
  29526. this.displacementScale = 1;
  29527. /**
  29528. * The offset of the displacement map's values on the mesh's vertices.
  29529. * The bias is added to the scaled sample of the displacement map.
  29530. * Without a displacement map set, this value is not applied.
  29531. *
  29532. * @type {number}
  29533. * @default 0
  29534. */
  29535. this.displacementBias = 0;
  29536. this.setValues( parameters );
  29537. }
  29538. copy( source ) {
  29539. super.copy( source );
  29540. this.map = source.map;
  29541. this.alphaMap = source.alphaMap;
  29542. this.displacementMap = source.displacementMap;
  29543. this.displacementScale = source.displacementScale;
  29544. this.displacementBias = source.displacementBias;
  29545. return this;
  29546. }
  29547. }
  29548. /**
  29549. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29550. * material color and shading.
  29551. *
  29552. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29553. * baked lighting. It will cast a shadow onto an object that receives shadows
  29554. * (and shadow clipping works), but it will not self-shadow or receive
  29555. * shadows.
  29556. *
  29557. * @augments Material
  29558. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29559. */
  29560. class MeshMatcapMaterial extends Material {
  29561. /**
  29562. * Constructs a new mesh matcap material.
  29563. *
  29564. * @param {Object} [parameters] - An object with one or more properties
  29565. * defining the material's appearance. Any property of the material
  29566. * (including any property from inherited materials) can be passed
  29567. * in here. Color values can be passed any type of value accepted
  29568. * by {@link Color#set}.
  29569. */
  29570. constructor( parameters ) {
  29571. super();
  29572. /**
  29573. * This flag can be used for type testing.
  29574. *
  29575. * @type {boolean}
  29576. * @readonly
  29577. * @default true
  29578. */
  29579. this.isMeshMatcapMaterial = true;
  29580. this.defines = { 'MATCAP': '' };
  29581. this.type = 'MeshMatcapMaterial';
  29582. /**
  29583. * Color of the material.
  29584. *
  29585. * @type {Color}
  29586. * @default (1,1,1)
  29587. */
  29588. this.color = new Color( 0xffffff ); // diffuse
  29589. /**
  29590. * The matcap map.
  29591. *
  29592. * @type {?Texture}
  29593. * @default null
  29594. */
  29595. this.matcap = null;
  29596. /**
  29597. * The color map. May optionally include an alpha channel, typically combined
  29598. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29599. * color is modulated by the diffuse `color`.
  29600. *
  29601. * @type {?Texture}
  29602. * @default null
  29603. */
  29604. this.map = null;
  29605. /**
  29606. * The texture to create a bump map. The black and white values map to the
  29607. * perceived depth in relation to the lights. Bump doesn't actually affect
  29608. * the geometry of the object, only the lighting. If a normal map is defined
  29609. * this will be ignored.
  29610. *
  29611. * @type {?Texture}
  29612. * @default null
  29613. */
  29614. this.bumpMap = null;
  29615. /**
  29616. * How much the bump map affects the material. Typical range is `[0,1]`.
  29617. *
  29618. * @type {number}
  29619. * @default 1
  29620. */
  29621. this.bumpScale = 1;
  29622. /**
  29623. * The texture to create a normal map. The RGB values affect the surface
  29624. * normal for each pixel fragment and change the way the color is lit. Normal
  29625. * maps do not change the actual shape of the surface, only the lighting. In
  29626. * case the material has a normal map authored using the left handed
  29627. * convention, the `y` component of `normalScale` should be negated to compensate
  29628. * for the different handedness.
  29629. *
  29630. * @type {?Texture}
  29631. * @default null
  29632. */
  29633. this.normalMap = null;
  29634. /**
  29635. * The type of normal map.
  29636. *
  29637. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29638. * @default TangentSpaceNormalMap
  29639. */
  29640. this.normalMapType = TangentSpaceNormalMap;
  29641. /**
  29642. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29643. *
  29644. * @type {Vector2}
  29645. * @default (1,1)
  29646. */
  29647. this.normalScale = new Vector2( 1, 1 );
  29648. /**
  29649. * The displacement map affects the position of the mesh's vertices. Unlike
  29650. * other maps which only affect the light and shade of the material the
  29651. * displaced vertices can cast shadows, block other objects, and otherwise
  29652. * act as real geometry. The displacement texture is an image where the value
  29653. * of each pixel (white being the highest) is mapped against, and
  29654. * repositions, the vertices of the mesh.
  29655. *
  29656. * @type {?Texture}
  29657. * @default null
  29658. */
  29659. this.displacementMap = null;
  29660. /**
  29661. * How much the displacement map affects the mesh (where black is no
  29662. * displacement, and white is maximum displacement). Without a displacement
  29663. * map set, this value is not applied.
  29664. *
  29665. * @type {number}
  29666. * @default 0
  29667. */
  29668. this.displacementScale = 1;
  29669. /**
  29670. * The offset of the displacement map's values on the mesh's vertices.
  29671. * The bias is added to the scaled sample of the displacement map.
  29672. * Without a displacement map set, this value is not applied.
  29673. *
  29674. * @type {number}
  29675. * @default 0
  29676. */
  29677. this.displacementBias = 0;
  29678. /**
  29679. * The alpha map is a grayscale texture that controls the opacity across the
  29680. * surface (black: fully transparent; white: fully opaque).
  29681. *
  29682. * Only the color of the texture is used, ignoring the alpha channel if one
  29683. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29684. * when sampling this texture due to the extra bit of precision provided for
  29685. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29686. * luminance/alpha textures will also still work as expected.
  29687. *
  29688. * @type {?Texture}
  29689. * @default null
  29690. */
  29691. this.alphaMap = null;
  29692. /**
  29693. * Renders the geometry as a wireframe.
  29694. *
  29695. * @type {boolean}
  29696. * @default false
  29697. */
  29698. this.wireframe = false;
  29699. /**
  29700. * Controls the thickness of the wireframe.
  29701. *
  29702. * Can only be used with {@link SVGRenderer}.
  29703. *
  29704. * @type {number}
  29705. * @default 1
  29706. */
  29707. this.wireframeLinewidth = 1;
  29708. /**
  29709. * Whether the material is rendered with flat shading or not.
  29710. *
  29711. * @type {boolean}
  29712. * @default false
  29713. */
  29714. this.flatShading = false;
  29715. /**
  29716. * Whether the material is affected by fog or not.
  29717. *
  29718. * @type {boolean}
  29719. * @default true
  29720. */
  29721. this.fog = true;
  29722. this.setValues( parameters );
  29723. }
  29724. copy( source ) {
  29725. super.copy( source );
  29726. this.defines = { 'MATCAP': '' };
  29727. this.color.copy( source.color );
  29728. this.matcap = source.matcap;
  29729. this.map = source.map;
  29730. this.bumpMap = source.bumpMap;
  29731. this.bumpScale = source.bumpScale;
  29732. this.normalMap = source.normalMap;
  29733. this.normalMapType = source.normalMapType;
  29734. this.normalScale.copy( source.normalScale );
  29735. this.displacementMap = source.displacementMap;
  29736. this.displacementScale = source.displacementScale;
  29737. this.displacementBias = source.displacementBias;
  29738. this.alphaMap = source.alphaMap;
  29739. this.wireframe = source.wireframe;
  29740. this.wireframeLinewidth = source.wireframeLinewidth;
  29741. this.flatShading = source.flatShading;
  29742. this.fog = source.fog;
  29743. return this;
  29744. }
  29745. }
  29746. /**
  29747. * A material for rendering line primitives.
  29748. *
  29749. * Materials define the appearance of renderable 3D objects.
  29750. *
  29751. * ```js
  29752. * const material = new THREE.LineDashedMaterial( {
  29753. * color: 0xffffff,
  29754. * scale: 1,
  29755. * dashSize: 3,
  29756. * gapSize: 1,
  29757. * } );
  29758. * ```
  29759. *
  29760. * @augments LineBasicMaterial
  29761. */
  29762. class LineDashedMaterial extends LineBasicMaterial {
  29763. /**
  29764. * Constructs a new line dashed material.
  29765. *
  29766. * @param {Object} [parameters] - An object with one or more properties
  29767. * defining the material's appearance. Any property of the material
  29768. * (including any property from inherited materials) can be passed
  29769. * in here. Color values can be passed any type of value accepted
  29770. * by {@link Color#set}.
  29771. */
  29772. constructor( parameters ) {
  29773. super();
  29774. /**
  29775. * This flag can be used for type testing.
  29776. *
  29777. * @type {boolean}
  29778. * @readonly
  29779. * @default true
  29780. */
  29781. this.isLineDashedMaterial = true;
  29782. this.type = 'LineDashedMaterial';
  29783. /**
  29784. * The scale of the dashed part of a line.
  29785. *
  29786. * @type {number}
  29787. * @default 1
  29788. */
  29789. this.scale = 1;
  29790. /**
  29791. * The size of the dash. This is both the gap with the stroke.
  29792. *
  29793. * @type {number}
  29794. * @default 3
  29795. */
  29796. this.dashSize = 3;
  29797. /**
  29798. * The size of the gap.
  29799. *
  29800. * @type {number}
  29801. * @default 1
  29802. */
  29803. this.gapSize = 1;
  29804. this.setValues( parameters );
  29805. }
  29806. copy( source ) {
  29807. super.copy( source );
  29808. this.scale = source.scale;
  29809. this.dashSize = source.dashSize;
  29810. this.gapSize = source.gapSize;
  29811. return this;
  29812. }
  29813. }
  29814. /**
  29815. * Converts an array to a specific type.
  29816. *
  29817. * @param {TypedArray|Array} array - The array to convert.
  29818. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29819. * @return {TypedArray} The converted array.
  29820. */
  29821. function convertArray( array, type ) {
  29822. if ( ! array || array.constructor === type ) return array;
  29823. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29824. return new type( array ); // create typed array
  29825. }
  29826. return Array.prototype.slice.call( array ); // create Array
  29827. }
  29828. /**
  29829. * Returns an array by which times and values can be sorted.
  29830. *
  29831. * @param {Array<number>} times - The keyframe time values.
  29832. * @return {Array<number>} The array.
  29833. */
  29834. function getKeyframeOrder( times ) {
  29835. function compareTime( i, j ) {
  29836. return times[ i ] - times[ j ];
  29837. }
  29838. const n = times.length;
  29839. const result = new Array( n );
  29840. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29841. result.sort( compareTime );
  29842. return result;
  29843. }
  29844. /**
  29845. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29846. *
  29847. * @param {Array<number>} values - The values to sort.
  29848. * @param {number} stride - The stride.
  29849. * @param {Array<number>} order - The sort order.
  29850. * @return {Array<number>} The sorted values.
  29851. */
  29852. function sortedArray( values, stride, order ) {
  29853. const nValues = values.length;
  29854. const result = new values.constructor( nValues );
  29855. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29856. const srcOffset = order[ i ] * stride;
  29857. for ( let j = 0; j !== stride; ++ j ) {
  29858. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29859. }
  29860. }
  29861. return result;
  29862. }
  29863. /**
  29864. * Used for parsing AOS keyframe formats.
  29865. *
  29866. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29867. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29868. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29869. * @param {string} valuePropertyName - The name of the property to use.
  29870. */
  29871. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29872. let i = 1, key = jsonKeys[ 0 ];
  29873. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29874. key = jsonKeys[ i ++ ];
  29875. }
  29876. if ( key === undefined ) return; // no data
  29877. let value = key[ valuePropertyName ];
  29878. if ( value === undefined ) return; // no data
  29879. if ( Array.isArray( value ) ) {
  29880. do {
  29881. value = key[ valuePropertyName ];
  29882. if ( value !== undefined ) {
  29883. times.push( key.time );
  29884. values.push( ...value ); // push all elements
  29885. }
  29886. key = jsonKeys[ i ++ ];
  29887. } while ( key !== undefined );
  29888. } else if ( value.toArray !== undefined ) {
  29889. // ...assume THREE.Math-ish
  29890. do {
  29891. value = key[ valuePropertyName ];
  29892. if ( value !== undefined ) {
  29893. times.push( key.time );
  29894. value.toArray( values, values.length );
  29895. }
  29896. key = jsonKeys[ i ++ ];
  29897. } while ( key !== undefined );
  29898. } else {
  29899. // otherwise push as-is
  29900. do {
  29901. value = key[ valuePropertyName ];
  29902. if ( value !== undefined ) {
  29903. times.push( key.time );
  29904. values.push( value );
  29905. }
  29906. key = jsonKeys[ i ++ ];
  29907. } while ( key !== undefined );
  29908. }
  29909. }
  29910. /**
  29911. * Creates a new clip, containing only the segment of the original clip between the given frames.
  29912. *
  29913. * @param {AnimationClip} sourceClip - The values to sort.
  29914. * @param {string} name - The name of the clip.
  29915. * @param {number} startFrame - The start frame.
  29916. * @param {number} endFrame - The end frame.
  29917. * @param {number} [fps=30] - The FPS.
  29918. * @return {AnimationClip} The new sub clip.
  29919. */
  29920. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  29921. const clip = sourceClip.clone();
  29922. clip.name = name;
  29923. const tracks = [];
  29924. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29925. const track = clip.tracks[ i ];
  29926. const valueSize = track.getValueSize();
  29927. const times = [];
  29928. const values = [];
  29929. for ( let j = 0; j < track.times.length; ++ j ) {
  29930. const frame = track.times[ j ] * fps;
  29931. if ( frame < startFrame || frame >= endFrame ) continue;
  29932. times.push( track.times[ j ] );
  29933. for ( let k = 0; k < valueSize; ++ k ) {
  29934. values.push( track.values[ j * valueSize + k ] );
  29935. }
  29936. }
  29937. if ( times.length === 0 ) continue;
  29938. track.times = convertArray( times, track.times.constructor );
  29939. track.values = convertArray( values, track.values.constructor );
  29940. tracks.push( track );
  29941. }
  29942. clip.tracks = tracks;
  29943. // find minimum .times value across all tracks in the trimmed clip
  29944. let minStartTime = Infinity;
  29945. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29946. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  29947. minStartTime = clip.tracks[ i ].times[ 0 ];
  29948. }
  29949. }
  29950. // shift all tracks such that clip begins at t=0
  29951. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  29952. clip.tracks[ i ].shift( -1 * minStartTime );
  29953. }
  29954. clip.resetDuration();
  29955. return clip;
  29956. }
  29957. /**
  29958. * Converts the keyframes of the given animation clip to an additive format.
  29959. *
  29960. * @param {AnimationClip} targetClip - The clip to make additive.
  29961. * @param {number} [referenceFrame=0] - The reference frame.
  29962. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  29963. * @param {number} [fps=30] - The FPS.
  29964. * @return {AnimationClip} The updated clip which is now additive.
  29965. */
  29966. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  29967. if ( fps <= 0 ) fps = 30;
  29968. const numTracks = referenceClip.tracks.length;
  29969. const referenceTime = referenceFrame / fps;
  29970. // Make each track's values relative to the values at the reference frame
  29971. for ( let i = 0; i < numTracks; ++ i ) {
  29972. const referenceTrack = referenceClip.tracks[ i ];
  29973. const referenceTrackType = referenceTrack.ValueTypeName;
  29974. // Skip this track if it's non-numeric
  29975. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  29976. // Find the track in the target clip whose name and type matches the reference track
  29977. const targetTrack = targetClip.tracks.find( function ( track ) {
  29978. return track.name === referenceTrack.name
  29979. && track.ValueTypeName === referenceTrackType;
  29980. } );
  29981. if ( targetTrack === undefined ) continue;
  29982. let referenceOffset = 0;
  29983. const referenceValueSize = referenceTrack.getValueSize();
  29984. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29985. referenceOffset = referenceValueSize / 3;
  29986. }
  29987. let targetOffset = 0;
  29988. const targetValueSize = targetTrack.getValueSize();
  29989. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  29990. targetOffset = targetValueSize / 3;
  29991. }
  29992. const lastIndex = referenceTrack.times.length - 1;
  29993. let referenceValue;
  29994. // Find the value to subtract out of the track
  29995. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  29996. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  29997. const startIndex = referenceOffset;
  29998. const endIndex = referenceValueSize - referenceOffset;
  29999. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30000. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30001. // Reference frame is after the last keyframe, so just use the last keyframe
  30002. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30003. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30004. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30005. } else {
  30006. // Interpolate to the reference value
  30007. const interpolant = referenceTrack.createInterpolant();
  30008. const startIndex = referenceOffset;
  30009. const endIndex = referenceValueSize - referenceOffset;
  30010. interpolant.evaluate( referenceTime );
  30011. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30012. }
  30013. // Conjugate the quaternion
  30014. if ( referenceTrackType === 'quaternion' ) {
  30015. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30016. referenceQuat.toArray( referenceValue );
  30017. }
  30018. // Subtract the reference value from all of the track values
  30019. const numTimes = targetTrack.times.length;
  30020. for ( let j = 0; j < numTimes; ++ j ) {
  30021. const valueStart = j * targetValueSize + targetOffset;
  30022. if ( referenceTrackType === 'quaternion' ) {
  30023. // Multiply the conjugate for quaternion track types
  30024. Quaternion.multiplyQuaternionsFlat(
  30025. targetTrack.values,
  30026. valueStart,
  30027. referenceValue,
  30028. 0,
  30029. targetTrack.values,
  30030. valueStart
  30031. );
  30032. } else {
  30033. const valueEnd = targetValueSize - targetOffset * 2;
  30034. // Subtract each value for all other numeric track types
  30035. for ( let k = 0; k < valueEnd; ++ k ) {
  30036. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30037. }
  30038. }
  30039. }
  30040. }
  30041. targetClip.blendMode = AdditiveAnimationBlendMode;
  30042. return targetClip;
  30043. }
  30044. /**
  30045. * A class with various methods to assist with animations.
  30046. *
  30047. * @hideconstructor
  30048. */
  30049. class AnimationUtils {
  30050. /**
  30051. * Converts an array to a specific type
  30052. *
  30053. * @static
  30054. * @param {TypedArray|Array} array - The array to convert.
  30055. * @param {TypedArray.constructor} type - The constructor of a type array.
  30056. * @return {TypedArray} The converted array
  30057. */
  30058. static convertArray( array, type ) {
  30059. return convertArray( array, type );
  30060. }
  30061. /**
  30062. * Returns `true` if the given object is a typed array.
  30063. *
  30064. * @static
  30065. * @param {any} object - The object to check.
  30066. * @return {boolean} Whether the given object is a typed array.
  30067. */
  30068. static isTypedArray( object ) {
  30069. return isTypedArray( object );
  30070. }
  30071. /**
  30072. * Returns an array by which times and values can be sorted.
  30073. *
  30074. * @static
  30075. * @param {Array<number>} times - The keyframe time values.
  30076. * @return {Array<number>} The array.
  30077. */
  30078. static getKeyframeOrder( times ) {
  30079. return getKeyframeOrder( times );
  30080. }
  30081. /**
  30082. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30083. *
  30084. * @static
  30085. * @param {Array<number>} values - The values to sort.
  30086. * @param {number} stride - The stride.
  30087. * @param {Array<number>} order - The sort order.
  30088. * @return {Array<number>} The sorted values.
  30089. */
  30090. static sortedArray( values, stride, order ) {
  30091. return sortedArray( values, stride, order );
  30092. }
  30093. /**
  30094. * Used for parsing AOS keyframe formats.
  30095. *
  30096. * @static
  30097. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30098. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30099. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30100. * @param {string} valuePropertyName - The name of the property to use.
  30101. */
  30102. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30103. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30104. }
  30105. /**
  30106. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30107. *
  30108. * @static
  30109. * @param {AnimationClip} sourceClip - The values to sort.
  30110. * @param {string} name - The name of the clip.
  30111. * @param {number} startFrame - The start frame.
  30112. * @param {number} endFrame - The end frame.
  30113. * @param {number} [fps=30] - The FPS.
  30114. * @return {AnimationClip} The new sub clip.
  30115. */
  30116. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30117. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30118. }
  30119. /**
  30120. * Converts the keyframes of the given animation clip to an additive format.
  30121. *
  30122. * @static
  30123. * @param {AnimationClip} targetClip - The clip to make additive.
  30124. * @param {number} [referenceFrame=0] - The reference frame.
  30125. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30126. * @param {number} [fps=30] - The FPS.
  30127. * @return {AnimationClip} The updated clip which is now additive.
  30128. */
  30129. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30130. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30131. }
  30132. }
  30133. /**
  30134. * Abstract base class of interpolants over parametric samples.
  30135. *
  30136. * The parameter domain is one dimensional, typically the time or a path
  30137. * along a curve defined by the data.
  30138. *
  30139. * The sample values can have any dimensionality and derived classes may
  30140. * apply special interpretations to the data.
  30141. *
  30142. * This class provides the interval seek in a Template Method, deferring
  30143. * the actual interpolation to derived classes.
  30144. *
  30145. * Time complexity is O(1) for linear access crossing at most two points
  30146. * and O(log N) for random access, where N is the number of positions.
  30147. *
  30148. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30149. *
  30150. * @abstract
  30151. */
  30152. class Interpolant {
  30153. /**
  30154. * Constructs a new interpolant.
  30155. *
  30156. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30157. * @param {TypedArray} sampleValues - The sample values.
  30158. * @param {number} sampleSize - The sample size
  30159. * @param {TypedArray} [resultBuffer] - The result buffer.
  30160. */
  30161. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30162. /**
  30163. * The parameter positions.
  30164. *
  30165. * @type {TypedArray}
  30166. */
  30167. this.parameterPositions = parameterPositions;
  30168. /**
  30169. * A cache index.
  30170. *
  30171. * @private
  30172. * @type {number}
  30173. * @default 0
  30174. */
  30175. this._cachedIndex = 0;
  30176. /**
  30177. * The result buffer.
  30178. *
  30179. * @type {TypedArray}
  30180. */
  30181. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30182. /**
  30183. * The sample values.
  30184. *
  30185. * @type {TypedArray}
  30186. */
  30187. this.sampleValues = sampleValues;
  30188. /**
  30189. * The value size.
  30190. *
  30191. * @type {TypedArray}
  30192. */
  30193. this.valueSize = sampleSize;
  30194. /**
  30195. * The interpolation settings.
  30196. *
  30197. * @type {?Object}
  30198. * @default null
  30199. */
  30200. this.settings = null;
  30201. /**
  30202. * The default settings object.
  30203. *
  30204. * @type {Object}
  30205. */
  30206. this.DefaultSettings_ = {};
  30207. }
  30208. /**
  30209. * Evaluate the interpolant at position `t`.
  30210. *
  30211. * @param {number} t - The interpolation factor.
  30212. * @return {TypedArray} The result buffer.
  30213. */
  30214. evaluate( t ) {
  30215. const pp = this.parameterPositions;
  30216. let i1 = this._cachedIndex,
  30217. t1 = pp[ i1 ],
  30218. t0 = pp[ i1 - 1 ];
  30219. validate_interval: {
  30220. seek: {
  30221. let right;
  30222. linear_scan: {
  30223. //- See http://jsperf.com/comparison-to-undefined/3
  30224. //- slower code:
  30225. //-
  30226. //- if ( t >= t1 || t1 === undefined ) {
  30227. forward_scan: if ( ! ( t < t1 ) ) {
  30228. for ( let giveUpAt = i1 + 2; ; ) {
  30229. if ( t1 === undefined ) {
  30230. if ( t < t0 ) break forward_scan;
  30231. // after end
  30232. i1 = pp.length;
  30233. this._cachedIndex = i1;
  30234. return this.copySampleValue_( i1 - 1 );
  30235. }
  30236. if ( i1 === giveUpAt ) break; // this loop
  30237. t0 = t1;
  30238. t1 = pp[ ++ i1 ];
  30239. if ( t < t1 ) {
  30240. // we have arrived at the sought interval
  30241. break seek;
  30242. }
  30243. }
  30244. // prepare binary search on the right side of the index
  30245. right = pp.length;
  30246. break linear_scan;
  30247. }
  30248. //- slower code:
  30249. //- if ( t < t0 || t0 === undefined ) {
  30250. if ( ! ( t >= t0 ) ) {
  30251. // looping?
  30252. const t1global = pp[ 1 ];
  30253. if ( t < t1global ) {
  30254. i1 = 2; // + 1, using the scan for the details
  30255. t0 = t1global;
  30256. }
  30257. // linear reverse scan
  30258. for ( let giveUpAt = i1 - 2; ; ) {
  30259. if ( t0 === undefined ) {
  30260. // before start
  30261. this._cachedIndex = 0;
  30262. return this.copySampleValue_( 0 );
  30263. }
  30264. if ( i1 === giveUpAt ) break; // this loop
  30265. t1 = t0;
  30266. t0 = pp[ -- i1 - 1 ];
  30267. if ( t >= t0 ) {
  30268. // we have arrived at the sought interval
  30269. break seek;
  30270. }
  30271. }
  30272. // prepare binary search on the left side of the index
  30273. right = i1;
  30274. i1 = 0;
  30275. break linear_scan;
  30276. }
  30277. // the interval is valid
  30278. break validate_interval;
  30279. } // linear scan
  30280. // binary search
  30281. while ( i1 < right ) {
  30282. const mid = ( i1 + right ) >>> 1;
  30283. if ( t < pp[ mid ] ) {
  30284. right = mid;
  30285. } else {
  30286. i1 = mid + 1;
  30287. }
  30288. }
  30289. t1 = pp[ i1 ];
  30290. t0 = pp[ i1 - 1 ];
  30291. // check boundary cases, again
  30292. if ( t0 === undefined ) {
  30293. this._cachedIndex = 0;
  30294. return this.copySampleValue_( 0 );
  30295. }
  30296. if ( t1 === undefined ) {
  30297. i1 = pp.length;
  30298. this._cachedIndex = i1;
  30299. return this.copySampleValue_( i1 - 1 );
  30300. }
  30301. } // seek
  30302. this._cachedIndex = i1;
  30303. this.intervalChanged_( i1, t0, t1 );
  30304. } // validate_interval
  30305. return this.interpolate_( i1, t0, t, t1 );
  30306. }
  30307. /**
  30308. * Returns the interpolation settings.
  30309. *
  30310. * @return {Object} The interpolation settings.
  30311. */
  30312. getSettings_() {
  30313. return this.settings || this.DefaultSettings_;
  30314. }
  30315. /**
  30316. * Copies a sample value to the result buffer.
  30317. *
  30318. * @param {number} index - An index into the sample value buffer.
  30319. * @return {TypedArray} The result buffer.
  30320. */
  30321. copySampleValue_( index ) {
  30322. // copies a sample value to the result buffer
  30323. const result = this.resultBuffer,
  30324. values = this.sampleValues,
  30325. stride = this.valueSize,
  30326. offset = index * stride;
  30327. for ( let i = 0; i !== stride; ++ i ) {
  30328. result[ i ] = values[ offset + i ];
  30329. }
  30330. return result;
  30331. }
  30332. /**
  30333. * Copies a sample value to the result buffer.
  30334. *
  30335. * @abstract
  30336. * @param {number} i1 - An index into the sample value buffer.
  30337. * @param {number} t0 - The previous interpolation factor.
  30338. * @param {number} t - The current interpolation factor.
  30339. * @param {number} t1 - The next interpolation factor.
  30340. * @return {TypedArray} The result buffer.
  30341. */
  30342. interpolate_( /* i1, t0, t, t1 */ ) {
  30343. throw new Error( 'call to abstract method' );
  30344. // implementations shall return this.resultBuffer
  30345. }
  30346. /**
  30347. * Optional method that is executed when the interval has changed.
  30348. *
  30349. * @param {number} i1 - An index into the sample value buffer.
  30350. * @param {number} t0 - The previous interpolation factor.
  30351. * @param {number} t - The current interpolation factor.
  30352. */
  30353. intervalChanged_( /* i1, t0, t1 */ ) {
  30354. // empty
  30355. }
  30356. }
  30357. /**
  30358. * Fast and simple cubic spline interpolant.
  30359. *
  30360. * It was derived from a Hermitian construction setting the first derivative
  30361. * at each sample position to the linear slope between neighboring positions
  30362. * over their parameter interval.
  30363. *
  30364. * @augments Interpolant
  30365. */
  30366. class CubicInterpolant extends Interpolant {
  30367. /**
  30368. * Constructs a new cubic interpolant.
  30369. *
  30370. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30371. * @param {TypedArray} sampleValues - The sample values.
  30372. * @param {number} sampleSize - The sample size
  30373. * @param {TypedArray} [resultBuffer] - The result buffer.
  30374. */
  30375. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30376. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30377. this._weightPrev = -0;
  30378. this._offsetPrev = -0;
  30379. this._weightNext = -0;
  30380. this._offsetNext = -0;
  30381. this.DefaultSettings_ = {
  30382. endingStart: ZeroCurvatureEnding,
  30383. endingEnd: ZeroCurvatureEnding
  30384. };
  30385. }
  30386. intervalChanged_( i1, t0, t1 ) {
  30387. const pp = this.parameterPositions;
  30388. let iPrev = i1 - 2,
  30389. iNext = i1 + 1,
  30390. tPrev = pp[ iPrev ],
  30391. tNext = pp[ iNext ];
  30392. if ( tPrev === undefined ) {
  30393. switch ( this.getSettings_().endingStart ) {
  30394. case ZeroSlopeEnding:
  30395. // f'(t0) = 0
  30396. iPrev = i1;
  30397. tPrev = 2 * t0 - t1;
  30398. break;
  30399. case WrapAroundEnding:
  30400. // use the other end of the curve
  30401. iPrev = pp.length - 2;
  30402. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30403. break;
  30404. default: // ZeroCurvatureEnding
  30405. // f''(t0) = 0 a.k.a. Natural Spline
  30406. iPrev = i1;
  30407. tPrev = t1;
  30408. }
  30409. }
  30410. if ( tNext === undefined ) {
  30411. switch ( this.getSettings_().endingEnd ) {
  30412. case ZeroSlopeEnding:
  30413. // f'(tN) = 0
  30414. iNext = i1;
  30415. tNext = 2 * t1 - t0;
  30416. break;
  30417. case WrapAroundEnding:
  30418. // use the other end of the curve
  30419. iNext = 1;
  30420. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30421. break;
  30422. default: // ZeroCurvatureEnding
  30423. // f''(tN) = 0, a.k.a. Natural Spline
  30424. iNext = i1 - 1;
  30425. tNext = t0;
  30426. }
  30427. }
  30428. const halfDt = ( t1 - t0 ) * 0.5,
  30429. stride = this.valueSize;
  30430. this._weightPrev = halfDt / ( t0 - tPrev );
  30431. this._weightNext = halfDt / ( tNext - t1 );
  30432. this._offsetPrev = iPrev * stride;
  30433. this._offsetNext = iNext * stride;
  30434. }
  30435. interpolate_( i1, t0, t, t1 ) {
  30436. const result = this.resultBuffer,
  30437. values = this.sampleValues,
  30438. stride = this.valueSize,
  30439. o1 = i1 * stride, o0 = o1 - stride,
  30440. oP = this._offsetPrev, oN = this._offsetNext,
  30441. wP = this._weightPrev, wN = this._weightNext,
  30442. p = ( t - t0 ) / ( t1 - t0 ),
  30443. pp = p * p,
  30444. ppp = pp * p;
  30445. // evaluate polynomials
  30446. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30447. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30448. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30449. const sN = wN * ppp - wN * pp;
  30450. // combine data linearly
  30451. for ( let i = 0; i !== stride; ++ i ) {
  30452. result[ i ] =
  30453. sP * values[ oP + i ] +
  30454. s0 * values[ o0 + i ] +
  30455. s1 * values[ o1 + i ] +
  30456. sN * values[ oN + i ];
  30457. }
  30458. return result;
  30459. }
  30460. }
  30461. /**
  30462. * A basic linear interpolant.
  30463. *
  30464. * @augments Interpolant
  30465. */
  30466. class LinearInterpolant extends Interpolant {
  30467. /**
  30468. * Constructs a new linear interpolant.
  30469. *
  30470. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30471. * @param {TypedArray} sampleValues - The sample values.
  30472. * @param {number} sampleSize - The sample size
  30473. * @param {TypedArray} [resultBuffer] - The result buffer.
  30474. */
  30475. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30476. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30477. }
  30478. interpolate_( i1, t0, t, t1 ) {
  30479. const result = this.resultBuffer,
  30480. values = this.sampleValues,
  30481. stride = this.valueSize,
  30482. offset1 = i1 * stride,
  30483. offset0 = offset1 - stride,
  30484. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30485. weight0 = 1 - weight1;
  30486. for ( let i = 0; i !== stride; ++ i ) {
  30487. result[ i ] =
  30488. values[ offset0 + i ] * weight0 +
  30489. values[ offset1 + i ] * weight1;
  30490. }
  30491. return result;
  30492. }
  30493. }
  30494. /**
  30495. * Interpolant that evaluates to the sample value at the position preceding
  30496. * the parameter.
  30497. *
  30498. * @augments Interpolant
  30499. */
  30500. class DiscreteInterpolant extends Interpolant {
  30501. /**
  30502. * Constructs a new discrete interpolant.
  30503. *
  30504. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30505. * @param {TypedArray} sampleValues - The sample values.
  30506. * @param {number} sampleSize - The sample size
  30507. * @param {TypedArray} [resultBuffer] - The result buffer.
  30508. */
  30509. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30510. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30511. }
  30512. interpolate_( i1 /*, t0, t, t1 */ ) {
  30513. return this.copySampleValue_( i1 - 1 );
  30514. }
  30515. }
  30516. /**
  30517. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  30518. *
  30519. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  30520. * each keyframe has explicit in/out tangent control points specified as
  30521. * 2D coordinates (time, value).
  30522. *
  30523. * The tangent data must be provided via the `settings` object:
  30524. * - `settings.inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30525. * - `settings.outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30526. *
  30527. * For a track with N keyframes and stride S:
  30528. * - Each tangent array has N * S * 2 values
  30529. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  30530. * k1_c0_time, k1_c0_value, ...]
  30531. *
  30532. * @augments Interpolant
  30533. */
  30534. class BezierInterpolant extends Interpolant {
  30535. interpolate_( i1, t0, t, t1 ) {
  30536. const result = this.resultBuffer;
  30537. const values = this.sampleValues;
  30538. const stride = this.valueSize;
  30539. const offset1 = i1 * stride;
  30540. const offset0 = offset1 - stride;
  30541. const settings = this.settings || this.DefaultSettings_;
  30542. const inTangents = settings.inTangents;
  30543. const outTangents = settings.outTangents;
  30544. // If no tangent data, fall back to linear interpolation
  30545. if ( ! inTangents || ! outTangents ) {
  30546. const weight1 = ( t - t0 ) / ( t1 - t0 );
  30547. const weight0 = 1 - weight1;
  30548. for ( let i = 0; i !== stride; ++ i ) {
  30549. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  30550. }
  30551. return result;
  30552. }
  30553. const tangentStride = stride * 2;
  30554. const i0 = i1 - 1;
  30555. for ( let i = 0; i !== stride; ++ i ) {
  30556. const v0 = values[ offset0 + i ];
  30557. const v1 = values[ offset1 + i ];
  30558. // outTangent of previous keyframe (C0)
  30559. const outTangentOffset = i0 * tangentStride + i * 2;
  30560. const c0x = outTangents[ outTangentOffset ];
  30561. const c0y = outTangents[ outTangentOffset + 1 ];
  30562. // inTangent of current keyframe (C1)
  30563. const inTangentOffset = i1 * tangentStride + i * 2;
  30564. const c1x = inTangents[ inTangentOffset ];
  30565. const c1y = inTangents[ inTangentOffset + 1 ];
  30566. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  30567. let s = ( t - t0 ) / ( t1 - t0 );
  30568. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  30569. for ( let iter = 0; iter < 8; iter ++ ) {
  30570. s2 = s * s;
  30571. s3 = s2 * s;
  30572. oneMinusS = 1 - s;
  30573. oneMinusS2 = oneMinusS * oneMinusS;
  30574. oneMinusS3 = oneMinusS2 * oneMinusS;
  30575. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  30576. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  30577. const error = bx - t;
  30578. if ( Math.abs( error ) < 1e-10 ) break;
  30579. // Derivative dX/ds
  30580. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  30581. if ( Math.abs( dbx ) < 1e-10 ) break;
  30582. s = s - error / dbx;
  30583. s = Math.max( 0, Math.min( 1, s ) );
  30584. }
  30585. // Evaluate Bezier Y(s)
  30586. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  30587. }
  30588. return result;
  30589. }
  30590. }
  30591. /**
  30592. * Represents a timed sequence of keyframes, which are composed of lists of
  30593. * times and related values, and which are used to animate a specific property
  30594. * of an object.
  30595. */
  30596. class KeyframeTrack {
  30597. /**
  30598. * Constructs a new keyframe track.
  30599. *
  30600. * @param {string} name - The keyframe track's name.
  30601. * @param {Array<number>} times - A list of keyframe times.
  30602. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30603. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  30604. */
  30605. constructor( name, times, values, interpolation ) {
  30606. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30607. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30608. /**
  30609. * The track's name can refer to morph targets or bones or
  30610. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30611. * for the forms of strings that can be parsed for property binding.
  30612. *
  30613. * @type {string}
  30614. */
  30615. this.name = name;
  30616. /**
  30617. * The keyframe times.
  30618. *
  30619. * @type {Float32Array}
  30620. */
  30621. this.times = convertArray( times, this.TimeBufferType );
  30622. /**
  30623. * The keyframe values.
  30624. *
  30625. * @type {Float32Array}
  30626. */
  30627. this.values = convertArray( values, this.ValueBufferType );
  30628. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30629. }
  30630. /**
  30631. * Converts the keyframe track to JSON.
  30632. *
  30633. * @static
  30634. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30635. * @return {Object} The serialized keyframe track as JSON.
  30636. */
  30637. static toJSON( track ) {
  30638. const trackType = track.constructor;
  30639. let json;
  30640. // derived classes can define a static toJSON method
  30641. if ( trackType.toJSON !== this.toJSON ) {
  30642. json = trackType.toJSON( track );
  30643. } else {
  30644. // by default, we assume the data can be serialized as-is
  30645. json = {
  30646. 'name': track.name,
  30647. 'times': convertArray( track.times, Array ),
  30648. 'values': convertArray( track.values, Array )
  30649. };
  30650. const interpolation = track.getInterpolation();
  30651. if ( interpolation !== track.DefaultInterpolation ) {
  30652. json.interpolation = interpolation;
  30653. }
  30654. }
  30655. json.type = track.ValueTypeName; // mandatory
  30656. return json;
  30657. }
  30658. /**
  30659. * Factory method for creating a new discrete interpolant.
  30660. *
  30661. * @static
  30662. * @param {TypedArray} [result] - The result buffer.
  30663. * @return {DiscreteInterpolant} The new interpolant.
  30664. */
  30665. InterpolantFactoryMethodDiscrete( result ) {
  30666. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30667. }
  30668. /**
  30669. * Factory method for creating a new linear interpolant.
  30670. *
  30671. * @static
  30672. * @param {TypedArray} [result] - The result buffer.
  30673. * @return {LinearInterpolant} The new interpolant.
  30674. */
  30675. InterpolantFactoryMethodLinear( result ) {
  30676. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30677. }
  30678. /**
  30679. * Factory method for creating a new smooth interpolant.
  30680. *
  30681. * @static
  30682. * @param {TypedArray} [result] - The result buffer.
  30683. * @return {CubicInterpolant} The new interpolant.
  30684. */
  30685. InterpolantFactoryMethodSmooth( result ) {
  30686. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30687. }
  30688. /**
  30689. * Factory method for creating a new Bezier interpolant.
  30690. *
  30691. * The Bezier interpolant requires tangent data to be set via the `settings` property
  30692. * on the track before creating the interpolant. The settings should contain:
  30693. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  30694. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  30695. *
  30696. * @static
  30697. * @param {TypedArray} [result] - The result buffer.
  30698. * @return {BezierInterpolant} The new interpolant.
  30699. */
  30700. InterpolantFactoryMethodBezier( result ) {
  30701. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  30702. // Pass tangent data from track settings to interpolant
  30703. if ( this.settings ) {
  30704. interpolant.settings = this.settings;
  30705. }
  30706. return interpolant;
  30707. }
  30708. /**
  30709. * Defines the interpolation factor method for this keyframe track.
  30710. *
  30711. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  30712. * @return {KeyframeTrack} A reference to this keyframe track.
  30713. */
  30714. setInterpolation( interpolation ) {
  30715. let factoryMethod;
  30716. switch ( interpolation ) {
  30717. case InterpolateDiscrete:
  30718. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30719. break;
  30720. case InterpolateLinear:
  30721. factoryMethod = this.InterpolantFactoryMethodLinear;
  30722. break;
  30723. case InterpolateSmooth:
  30724. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30725. break;
  30726. case InterpolateBezier:
  30727. factoryMethod = this.InterpolantFactoryMethodBezier;
  30728. break;
  30729. }
  30730. if ( factoryMethod === undefined ) {
  30731. const message = 'unsupported interpolation for ' +
  30732. this.ValueTypeName + ' keyframe track named ' + this.name;
  30733. if ( this.createInterpolant === undefined ) {
  30734. // fall back to default, unless the default itself is messed up
  30735. if ( interpolation !== this.DefaultInterpolation ) {
  30736. this.setInterpolation( this.DefaultInterpolation );
  30737. } else {
  30738. throw new Error( message ); // fatal, in this case
  30739. }
  30740. }
  30741. warn( 'KeyframeTrack:', message );
  30742. return this;
  30743. }
  30744. this.createInterpolant = factoryMethod;
  30745. return this;
  30746. }
  30747. /**
  30748. * Returns the current interpolation type.
  30749. *
  30750. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  30751. */
  30752. getInterpolation() {
  30753. switch ( this.createInterpolant ) {
  30754. case this.InterpolantFactoryMethodDiscrete:
  30755. return InterpolateDiscrete;
  30756. case this.InterpolantFactoryMethodLinear:
  30757. return InterpolateLinear;
  30758. case this.InterpolantFactoryMethodSmooth:
  30759. return InterpolateSmooth;
  30760. case this.InterpolantFactoryMethodBezier:
  30761. return InterpolateBezier;
  30762. }
  30763. }
  30764. /**
  30765. * Returns the value size.
  30766. *
  30767. * @return {number} The value size.
  30768. */
  30769. getValueSize() {
  30770. return this.values.length / this.times.length;
  30771. }
  30772. /**
  30773. * Moves all keyframes either forward or backward in time.
  30774. *
  30775. * @param {number} timeOffset - The offset to move the time values.
  30776. * @return {KeyframeTrack} A reference to this keyframe track.
  30777. */
  30778. shift( timeOffset ) {
  30779. if ( timeOffset !== 0.0 ) {
  30780. const times = this.times;
  30781. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30782. times[ i ] += timeOffset;
  30783. }
  30784. }
  30785. return this;
  30786. }
  30787. /**
  30788. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30789. *
  30790. * @param {number} timeScale - The time scale.
  30791. * @return {KeyframeTrack} A reference to this keyframe track.
  30792. */
  30793. scale( timeScale ) {
  30794. if ( timeScale !== 1.0 ) {
  30795. const times = this.times;
  30796. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30797. times[ i ] *= timeScale;
  30798. }
  30799. }
  30800. return this;
  30801. }
  30802. /**
  30803. * Removes keyframes before and after animation without changing any values within the defined time range.
  30804. *
  30805. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30806. * keys this will change their values
  30807. *
  30808. * @param {number} startTime - The start time.
  30809. * @param {number} endTime - The end time.
  30810. * @return {KeyframeTrack} A reference to this keyframe track.
  30811. */
  30812. trim( startTime, endTime ) {
  30813. const times = this.times,
  30814. nKeys = times.length;
  30815. let from = 0,
  30816. to = nKeys - 1;
  30817. while ( from !== nKeys && times[ from ] < startTime ) {
  30818. ++ from;
  30819. }
  30820. while ( to !== -1 && times[ to ] > endTime ) {
  30821. -- to;
  30822. }
  30823. ++ to; // inclusive -> exclusive bound
  30824. if ( from !== 0 || to !== nKeys ) {
  30825. // empty tracks are forbidden, so keep at least one keyframe
  30826. if ( from >= to ) {
  30827. to = Math.max( to, 1 );
  30828. from = to - 1;
  30829. }
  30830. const stride = this.getValueSize();
  30831. this.times = times.slice( from, to );
  30832. this.values = this.values.slice( from * stride, to * stride );
  30833. }
  30834. return this;
  30835. }
  30836. /**
  30837. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30838. * are valid.
  30839. *
  30840. * @return {boolean} Whether the keyframes are valid or not.
  30841. */
  30842. validate() {
  30843. let valid = true;
  30844. const valueSize = this.getValueSize();
  30845. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30846. error( 'KeyframeTrack: Invalid value size in track.', this );
  30847. valid = false;
  30848. }
  30849. const times = this.times,
  30850. values = this.values,
  30851. nKeys = times.length;
  30852. if ( nKeys === 0 ) {
  30853. error( 'KeyframeTrack: Track is empty.', this );
  30854. valid = false;
  30855. }
  30856. let prevTime = null;
  30857. for ( let i = 0; i !== nKeys; i ++ ) {
  30858. const currTime = times[ i ];
  30859. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30860. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30861. valid = false;
  30862. break;
  30863. }
  30864. if ( prevTime !== null && prevTime > currTime ) {
  30865. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30866. valid = false;
  30867. break;
  30868. }
  30869. prevTime = currTime;
  30870. }
  30871. if ( values !== undefined ) {
  30872. if ( isTypedArray( values ) ) {
  30873. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30874. const value = values[ i ];
  30875. if ( isNaN( value ) ) {
  30876. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  30877. valid = false;
  30878. break;
  30879. }
  30880. }
  30881. }
  30882. }
  30883. return valid;
  30884. }
  30885. /**
  30886. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30887. * common in morph target sequences).
  30888. *
  30889. * @return {KeyframeTrack} A reference to this keyframe track.
  30890. */
  30891. optimize() {
  30892. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30893. // times or values may be shared with other tracks, so overwriting is unsafe
  30894. const times = this.times.slice(),
  30895. values = this.values.slice(),
  30896. stride = this.getValueSize(),
  30897. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30898. lastIndex = times.length - 1;
  30899. let writeIndex = 1;
  30900. for ( let i = 1; i < lastIndex; ++ i ) {
  30901. let keep = false;
  30902. const time = times[ i ];
  30903. const timeNext = times[ i + 1 ];
  30904. // remove adjacent keyframes scheduled at the same time
  30905. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30906. if ( ! smoothInterpolation ) {
  30907. // remove unnecessary keyframes same as their neighbors
  30908. const offset = i * stride,
  30909. offsetP = offset - stride,
  30910. offsetN = offset + stride;
  30911. for ( let j = 0; j !== stride; ++ j ) {
  30912. const value = values[ offset + j ];
  30913. if ( value !== values[ offsetP + j ] ||
  30914. value !== values[ offsetN + j ] ) {
  30915. keep = true;
  30916. break;
  30917. }
  30918. }
  30919. } else {
  30920. keep = true;
  30921. }
  30922. }
  30923. // in-place compaction
  30924. if ( keep ) {
  30925. if ( i !== writeIndex ) {
  30926. times[ writeIndex ] = times[ i ];
  30927. const readOffset = i * stride,
  30928. writeOffset = writeIndex * stride;
  30929. for ( let j = 0; j !== stride; ++ j ) {
  30930. values[ writeOffset + j ] = values[ readOffset + j ];
  30931. }
  30932. }
  30933. ++ writeIndex;
  30934. }
  30935. }
  30936. // flush last keyframe (compaction looks ahead)
  30937. if ( lastIndex > 0 ) {
  30938. times[ writeIndex ] = times[ lastIndex ];
  30939. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30940. values[ writeOffset + j ] = values[ readOffset + j ];
  30941. }
  30942. ++ writeIndex;
  30943. }
  30944. if ( writeIndex !== times.length ) {
  30945. this.times = times.slice( 0, writeIndex );
  30946. this.values = values.slice( 0, writeIndex * stride );
  30947. } else {
  30948. this.times = times;
  30949. this.values = values;
  30950. }
  30951. return this;
  30952. }
  30953. /**
  30954. * Returns a new keyframe track with copied values from this instance.
  30955. *
  30956. * @return {KeyframeTrack} A clone of this instance.
  30957. */
  30958. clone() {
  30959. const times = this.times.slice();
  30960. const values = this.values.slice();
  30961. const TypedKeyframeTrack = this.constructor;
  30962. const track = new TypedKeyframeTrack( this.name, times, values );
  30963. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30964. track.createInterpolant = this.createInterpolant;
  30965. return track;
  30966. }
  30967. }
  30968. /**
  30969. * The value type name.
  30970. *
  30971. * @type {string}
  30972. * @default ''
  30973. */
  30974. KeyframeTrack.prototype.ValueTypeName = '';
  30975. /**
  30976. * The time buffer type of this keyframe track.
  30977. *
  30978. * @type {TypedArray|Array}
  30979. * @default Float32Array.constructor
  30980. */
  30981. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30982. /**
  30983. * The value buffer type of this keyframe track.
  30984. *
  30985. * @type {TypedArray|Array}
  30986. * @default Float32Array.constructor
  30987. */
  30988. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30989. /**
  30990. * The default interpolation type of this keyframe track.
  30991. *
  30992. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  30993. * @default InterpolateLinear
  30994. */
  30995. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30996. /**
  30997. * A track for boolean keyframe values.
  30998. *
  30999. * @augments KeyframeTrack
  31000. */
  31001. class BooleanKeyframeTrack extends KeyframeTrack {
  31002. /**
  31003. * Constructs a new boolean keyframe track.
  31004. *
  31005. * This keyframe track type has no `interpolation` parameter because the
  31006. * interpolation is always discrete.
  31007. *
  31008. * @param {string} name - The keyframe track's name.
  31009. * @param {Array<number>} times - A list of keyframe times.
  31010. * @param {Array<boolean>} values - A list of keyframe values.
  31011. */
  31012. constructor( name, times, values ) {
  31013. super( name, times, values );
  31014. }
  31015. }
  31016. /**
  31017. * The value type name.
  31018. *
  31019. * @type {string}
  31020. * @default 'bool'
  31021. */
  31022. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31023. /**
  31024. * The value buffer type of this keyframe track.
  31025. *
  31026. * @type {TypedArray|Array}
  31027. * @default Array.constructor
  31028. */
  31029. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31030. /**
  31031. * The default interpolation type of this keyframe track.
  31032. *
  31033. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31034. * @default InterpolateDiscrete
  31035. */
  31036. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31037. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31038. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31039. /**
  31040. * A track for color keyframe values.
  31041. *
  31042. * @augments KeyframeTrack
  31043. */
  31044. class ColorKeyframeTrack extends KeyframeTrack {
  31045. /**
  31046. * Constructs a new color keyframe track.
  31047. *
  31048. * @param {string} name - The keyframe track's name.
  31049. * @param {Array<number>} times - A list of keyframe times.
  31050. * @param {Array<number>} values - A list of keyframe values.
  31051. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31052. */
  31053. constructor( name, times, values, interpolation ) {
  31054. super( name, times, values, interpolation );
  31055. }
  31056. }
  31057. /**
  31058. * The value type name.
  31059. *
  31060. * @type {string}
  31061. * @default 'color'
  31062. */
  31063. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31064. /**
  31065. * A track for numeric keyframe values.
  31066. *
  31067. * @augments KeyframeTrack
  31068. */
  31069. class NumberKeyframeTrack extends KeyframeTrack {
  31070. /**
  31071. * Constructs a new number keyframe track.
  31072. *
  31073. * @param {string} name - The keyframe track's name.
  31074. * @param {Array<number>} times - A list of keyframe times.
  31075. * @param {Array<number>} values - A list of keyframe values.
  31076. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31077. */
  31078. constructor( name, times, values, interpolation ) {
  31079. super( name, times, values, interpolation );
  31080. }
  31081. }
  31082. /**
  31083. * The value type name.
  31084. *
  31085. * @type {string}
  31086. * @default 'number'
  31087. */
  31088. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31089. /**
  31090. * Spherical linear unit quaternion interpolant.
  31091. *
  31092. * @augments Interpolant
  31093. */
  31094. class QuaternionLinearInterpolant extends Interpolant {
  31095. /**
  31096. * Constructs a new SLERP interpolant.
  31097. *
  31098. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31099. * @param {TypedArray} sampleValues - The sample values.
  31100. * @param {number} sampleSize - The sample size
  31101. * @param {TypedArray} [resultBuffer] - The result buffer.
  31102. */
  31103. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31104. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31105. }
  31106. interpolate_( i1, t0, t, t1 ) {
  31107. const result = this.resultBuffer,
  31108. values = this.sampleValues,
  31109. stride = this.valueSize,
  31110. alpha = ( t - t0 ) / ( t1 - t0 );
  31111. let offset = i1 * stride;
  31112. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31113. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31114. }
  31115. return result;
  31116. }
  31117. }
  31118. /**
  31119. * A track for Quaternion keyframe values.
  31120. *
  31121. * @augments KeyframeTrack
  31122. */
  31123. class QuaternionKeyframeTrack extends KeyframeTrack {
  31124. /**
  31125. * Constructs a new Quaternion keyframe track.
  31126. *
  31127. * @param {string} name - The keyframe track's name.
  31128. * @param {Array<number>} times - A list of keyframe times.
  31129. * @param {Array<number>} values - A list of keyframe values.
  31130. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31131. */
  31132. constructor( name, times, values, interpolation ) {
  31133. super( name, times, values, interpolation );
  31134. }
  31135. /**
  31136. * Overwritten so the method returns Quaternion based interpolant.
  31137. *
  31138. * @static
  31139. * @param {TypedArray} [result] - The result buffer.
  31140. * @return {QuaternionLinearInterpolant} The new interpolant.
  31141. */
  31142. InterpolantFactoryMethodLinear( result ) {
  31143. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31144. }
  31145. }
  31146. /**
  31147. * The value type name.
  31148. *
  31149. * @type {string}
  31150. * @default 'quaternion'
  31151. */
  31152. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31153. // ValueBufferType is inherited
  31154. // DefaultInterpolation is inherited;
  31155. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31156. /**
  31157. * A track for string keyframe values.
  31158. *
  31159. * @augments KeyframeTrack
  31160. */
  31161. class StringKeyframeTrack extends KeyframeTrack {
  31162. /**
  31163. * Constructs a new string keyframe track.
  31164. *
  31165. * This keyframe track type has no `interpolation` parameter because the
  31166. * interpolation is always discrete.
  31167. *
  31168. * @param {string} name - The keyframe track's name.
  31169. * @param {Array<number>} times - A list of keyframe times.
  31170. * @param {Array<string>} values - A list of keyframe values.
  31171. */
  31172. constructor( name, times, values ) {
  31173. super( name, times, values );
  31174. }
  31175. }
  31176. /**
  31177. * The value type name.
  31178. *
  31179. * @type {string}
  31180. * @default 'string'
  31181. */
  31182. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31183. /**
  31184. * The value buffer type of this keyframe track.
  31185. *
  31186. * @type {TypedArray|Array}
  31187. * @default Array.constructor
  31188. */
  31189. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31190. /**
  31191. * The default interpolation type of this keyframe track.
  31192. *
  31193. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31194. * @default InterpolateDiscrete
  31195. */
  31196. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31197. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31198. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31199. /**
  31200. * A track for vector keyframe values.
  31201. *
  31202. * @augments KeyframeTrack
  31203. */
  31204. class VectorKeyframeTrack extends KeyframeTrack {
  31205. /**
  31206. * Constructs a new vector keyframe track.
  31207. *
  31208. * @param {string} name - The keyframe track's name.
  31209. * @param {Array<number>} times - A list of keyframe times.
  31210. * @param {Array<number>} values - A list of keyframe values.
  31211. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31212. */
  31213. constructor( name, times, values, interpolation ) {
  31214. super( name, times, values, interpolation );
  31215. }
  31216. }
  31217. /**
  31218. * The value type name.
  31219. *
  31220. * @type {string}
  31221. * @default 'vector'
  31222. */
  31223. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31224. /**
  31225. * A reusable set of keyframe tracks which represent an animation.
  31226. */
  31227. class AnimationClip {
  31228. /**
  31229. * Constructs a new animation clip.
  31230. *
  31231. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31232. * use the static interface of this class for creating clips. In most cases though, animation clips
  31233. * will automatically be created by loaders when importing animated 3D assets.
  31234. *
  31235. * @param {string} [name=''] - The clip's name.
  31236. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31237. * the duration will be calculated from the passed keyframes.
  31238. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31239. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31240. * is blended/combined when two or more animations are simultaneously played.
  31241. */
  31242. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31243. /**
  31244. * The clip's name.
  31245. *
  31246. * @type {string}
  31247. */
  31248. this.name = name;
  31249. /**
  31250. * An array of keyframe tracks.
  31251. *
  31252. * @type {Array<KeyframeTrack>}
  31253. */
  31254. this.tracks = tracks;
  31255. /**
  31256. * The clip's duration in seconds.
  31257. *
  31258. * @type {number}
  31259. */
  31260. this.duration = duration;
  31261. /**
  31262. * Defines how the animation is blended/combined when two or more animations
  31263. * are simultaneously played.
  31264. *
  31265. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31266. */
  31267. this.blendMode = blendMode;
  31268. /**
  31269. * The UUID of the animation clip.
  31270. *
  31271. * @type {string}
  31272. * @readonly
  31273. */
  31274. this.uuid = generateUUID();
  31275. /**
  31276. * An object that can be used to store custom data about the animation clip.
  31277. * It should not hold references to functions as these will not be cloned.
  31278. *
  31279. * @type {Object}
  31280. */
  31281. this.userData = {};
  31282. // this means it should figure out its duration by scanning the tracks
  31283. if ( this.duration < 0 ) {
  31284. this.resetDuration();
  31285. }
  31286. }
  31287. /**
  31288. * Factory method for creating an animation clip from the given JSON.
  31289. *
  31290. * @static
  31291. * @param {Object} json - The serialized animation clip.
  31292. * @return {AnimationClip} The new animation clip.
  31293. */
  31294. static parse( json ) {
  31295. const tracks = [],
  31296. jsonTracks = json.tracks,
  31297. frameTime = 1.0 / ( json.fps || 1.0 );
  31298. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31299. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31300. }
  31301. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31302. clip.uuid = json.uuid;
  31303. clip.userData = JSON.parse( json.userData || '{}' );
  31304. return clip;
  31305. }
  31306. /**
  31307. * Serializes the given animation clip into JSON.
  31308. *
  31309. * @static
  31310. * @param {AnimationClip} clip - The animation clip to serialize.
  31311. * @return {Object} The JSON object.
  31312. */
  31313. static toJSON( clip ) {
  31314. const tracks = [],
  31315. clipTracks = clip.tracks;
  31316. const json = {
  31317. 'name': clip.name,
  31318. 'duration': clip.duration,
  31319. 'tracks': tracks,
  31320. 'uuid': clip.uuid,
  31321. 'blendMode': clip.blendMode,
  31322. 'userData': JSON.stringify( clip.userData ),
  31323. };
  31324. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31325. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31326. }
  31327. return json;
  31328. }
  31329. /**
  31330. * Returns a new animation clip from the passed morph targets array of a
  31331. * geometry, taking a name and the number of frames per second.
  31332. *
  31333. * Note: The fps parameter is required, but the animation speed can be
  31334. * overridden via {@link AnimationAction#setDuration}.
  31335. *
  31336. * @static
  31337. * @param {string} name - The name of the animation clip.
  31338. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31339. * @param {number} fps - The Frames-Per-Second value.
  31340. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31341. * @return {AnimationClip} The new animation clip.
  31342. */
  31343. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31344. const numMorphTargets = morphTargetSequence.length;
  31345. const tracks = [];
  31346. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31347. let times = [];
  31348. let values = [];
  31349. times.push(
  31350. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31351. i,
  31352. ( i + 1 ) % numMorphTargets );
  31353. values.push( 0, 1, 0 );
  31354. const order = getKeyframeOrder( times );
  31355. times = sortedArray( times, 1, order );
  31356. values = sortedArray( values, 1, order );
  31357. // if there is a key at the first frame, duplicate it as the
  31358. // last frame as well for perfect loop.
  31359. if ( ! noLoop && times[ 0 ] === 0 ) {
  31360. times.push( numMorphTargets );
  31361. values.push( values[ 0 ] );
  31362. }
  31363. tracks.push(
  31364. new NumberKeyframeTrack(
  31365. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31366. times, values
  31367. ).scale( 1.0 / fps ) );
  31368. }
  31369. return new this( name, -1, tracks );
  31370. }
  31371. /**
  31372. * Searches for an animation clip by name, taking as its first parameter
  31373. * either an array of clips, or a mesh or geometry that contains an
  31374. * array named "animations" property.
  31375. *
  31376. * @static
  31377. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31378. * @param {string} name - The name to search for.
  31379. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31380. */
  31381. static findByName( objectOrClipArray, name ) {
  31382. let clipArray = objectOrClipArray;
  31383. if ( ! Array.isArray( objectOrClipArray ) ) {
  31384. const o = objectOrClipArray;
  31385. clipArray = o.geometry && o.geometry.animations || o.animations;
  31386. }
  31387. for ( let i = 0; i < clipArray.length; i ++ ) {
  31388. if ( clipArray[ i ].name === name ) {
  31389. return clipArray[ i ];
  31390. }
  31391. }
  31392. return null;
  31393. }
  31394. /**
  31395. * Returns an array of new AnimationClips created from the morph target
  31396. * sequences of a geometry, trying to sort morph target names into
  31397. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31398. *
  31399. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31400. *
  31401. * @static
  31402. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31403. * @param {number} fps - The Frames-Per-Second value.
  31404. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31405. * @return {Array<AnimationClip>} An array of new animation clips.
  31406. */
  31407. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31408. const animationToMorphTargets = {};
  31409. // tested with https://regex101.com/ on trick sequences
  31410. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31411. const pattern = /^([\w-]*?)([\d]+)$/;
  31412. // sort morph target names into animation groups based
  31413. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31414. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31415. const morphTarget = morphTargets[ i ];
  31416. const parts = morphTarget.name.match( pattern );
  31417. if ( parts && parts.length > 1 ) {
  31418. const name = parts[ 1 ];
  31419. let animationMorphTargets = animationToMorphTargets[ name ];
  31420. if ( ! animationMorphTargets ) {
  31421. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31422. }
  31423. animationMorphTargets.push( morphTarget );
  31424. }
  31425. }
  31426. const clips = [];
  31427. for ( const name in animationToMorphTargets ) {
  31428. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31429. }
  31430. return clips;
  31431. }
  31432. /**
  31433. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31434. *
  31435. * @static
  31436. * @deprecated since r175.
  31437. * @param {Object} animation - A serialized animation clip as JSON.
  31438. * @param {Array<Bone>} bones - An array of bones.
  31439. * @return {?AnimationClip} The new animation clip.
  31440. */
  31441. static parseAnimation( animation, bones ) {
  31442. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31443. if ( ! animation ) {
  31444. error( 'AnimationClip: No animation in JSONLoader data.' );
  31445. return null;
  31446. }
  31447. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31448. // only return track if there are actually keys.
  31449. if ( animationKeys.length !== 0 ) {
  31450. const times = [];
  31451. const values = [];
  31452. flattenJSON( animationKeys, times, values, propertyName );
  31453. // empty keys are filtered out, so check again
  31454. if ( times.length !== 0 ) {
  31455. destTracks.push( new trackType( trackName, times, values ) );
  31456. }
  31457. }
  31458. };
  31459. const tracks = [];
  31460. const clipName = animation.name || 'default';
  31461. const fps = animation.fps || 30;
  31462. const blendMode = animation.blendMode;
  31463. // automatic length determination in AnimationClip.
  31464. let duration = animation.length || -1;
  31465. const hierarchyTracks = animation.hierarchy || [];
  31466. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31467. const animationKeys = hierarchyTracks[ h ].keys;
  31468. // skip empty tracks
  31469. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31470. // process morph targets
  31471. if ( animationKeys[ 0 ].morphTargets ) {
  31472. // figure out all morph targets used in this track
  31473. const morphTargetNames = {};
  31474. let k;
  31475. for ( k = 0; k < animationKeys.length; k ++ ) {
  31476. if ( animationKeys[ k ].morphTargets ) {
  31477. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31478. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31479. }
  31480. }
  31481. }
  31482. // create a track for each morph target with all zero
  31483. // morphTargetInfluences except for the keys in which
  31484. // the morphTarget is named.
  31485. for ( const morphTargetName in morphTargetNames ) {
  31486. const times = [];
  31487. const values = [];
  31488. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31489. const animationKey = animationKeys[ k ];
  31490. times.push( animationKey.time );
  31491. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31492. }
  31493. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31494. }
  31495. duration = morphTargetNames.length * fps;
  31496. } else {
  31497. // ...assume skeletal animation
  31498. const boneName = '.bones[' + bones[ h ].name + ']';
  31499. addNonemptyTrack(
  31500. VectorKeyframeTrack, boneName + '.position',
  31501. animationKeys, 'pos', tracks );
  31502. addNonemptyTrack(
  31503. QuaternionKeyframeTrack, boneName + '.quaternion',
  31504. animationKeys, 'rot', tracks );
  31505. addNonemptyTrack(
  31506. VectorKeyframeTrack, boneName + '.scale',
  31507. animationKeys, 'scl', tracks );
  31508. }
  31509. }
  31510. if ( tracks.length === 0 ) {
  31511. return null;
  31512. }
  31513. const clip = new this( clipName, duration, tracks, blendMode );
  31514. return clip;
  31515. }
  31516. /**
  31517. * Sets the duration of this clip to the duration of its longest keyframe track.
  31518. *
  31519. * @return {AnimationClip} A reference to this animation clip.
  31520. */
  31521. resetDuration() {
  31522. const tracks = this.tracks;
  31523. let duration = 0;
  31524. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31525. const track = this.tracks[ i ];
  31526. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31527. }
  31528. this.duration = duration;
  31529. return this;
  31530. }
  31531. /**
  31532. * Trims all tracks to the clip's duration.
  31533. *
  31534. * @return {AnimationClip} A reference to this animation clip.
  31535. */
  31536. trim() {
  31537. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31538. this.tracks[ i ].trim( 0, this.duration );
  31539. }
  31540. return this;
  31541. }
  31542. /**
  31543. * Performs minimal validation on each track in the clip. Returns `true` if all
  31544. * tracks are valid.
  31545. *
  31546. * @return {boolean} Whether the clip's keyframes are valid or not.
  31547. */
  31548. validate() {
  31549. let valid = true;
  31550. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31551. valid = valid && this.tracks[ i ].validate();
  31552. }
  31553. return valid;
  31554. }
  31555. /**
  31556. * Optimizes each track by removing equivalent sequential keys (which are
  31557. * common in morph target sequences).
  31558. *
  31559. * @return {AnimationClip} A reference to this animation clip.
  31560. */
  31561. optimize() {
  31562. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31563. this.tracks[ i ].optimize();
  31564. }
  31565. return this;
  31566. }
  31567. /**
  31568. * Returns a new animation clip with copied values from this instance.
  31569. *
  31570. * @return {AnimationClip} A clone of this instance.
  31571. */
  31572. clone() {
  31573. const tracks = [];
  31574. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31575. tracks.push( this.tracks[ i ].clone() );
  31576. }
  31577. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31578. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31579. return clip;
  31580. }
  31581. /**
  31582. * Serializes this animation clip into JSON.
  31583. *
  31584. * @return {Object} The JSON object.
  31585. */
  31586. toJSON() {
  31587. return this.constructor.toJSON( this );
  31588. }
  31589. }
  31590. function getTrackTypeForValueTypeName( typeName ) {
  31591. switch ( typeName.toLowerCase() ) {
  31592. case 'scalar':
  31593. case 'double':
  31594. case 'float':
  31595. case 'number':
  31596. case 'integer':
  31597. return NumberKeyframeTrack;
  31598. case 'vector':
  31599. case 'vector2':
  31600. case 'vector3':
  31601. case 'vector4':
  31602. return VectorKeyframeTrack;
  31603. case 'color':
  31604. return ColorKeyframeTrack;
  31605. case 'quaternion':
  31606. return QuaternionKeyframeTrack;
  31607. case 'bool':
  31608. case 'boolean':
  31609. return BooleanKeyframeTrack;
  31610. case 'string':
  31611. return StringKeyframeTrack;
  31612. }
  31613. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31614. }
  31615. function parseKeyframeTrack( json ) {
  31616. if ( json.type === undefined ) {
  31617. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31618. }
  31619. const trackType = getTrackTypeForValueTypeName( json.type );
  31620. if ( json.times === undefined ) {
  31621. const times = [], values = [];
  31622. flattenJSON( json.keys, times, values, 'value' );
  31623. json.times = times;
  31624. json.values = values;
  31625. }
  31626. // derived classes can define a static parse method
  31627. if ( trackType.parse !== undefined ) {
  31628. return trackType.parse( json );
  31629. } else {
  31630. // by default, we assume a constructor compatible with the base
  31631. return new trackType( json.name, json.times, json.values, json.interpolation );
  31632. }
  31633. }
  31634. /**
  31635. * @class
  31636. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31637. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31638. * @hideconstructor
  31639. */
  31640. const Cache = {
  31641. /**
  31642. * Whether caching is enabled or not.
  31643. *
  31644. * @static
  31645. * @type {boolean}
  31646. * @default false
  31647. */
  31648. enabled: false,
  31649. /**
  31650. * A dictionary that holds cached files.
  31651. *
  31652. * @static
  31653. * @type {Object<string,Object>}
  31654. */
  31655. files: {},
  31656. /**
  31657. * Adds a cache entry with a key to reference the file. If this key already
  31658. * holds a file, it is overwritten.
  31659. *
  31660. * @static
  31661. * @param {string} key - The key to reference the cached file.
  31662. * @param {Object} file - The file to be cached.
  31663. */
  31664. add: function ( key, file ) {
  31665. if ( this.enabled === false ) return;
  31666. if ( isBlobURL( key ) ) return;
  31667. // log( 'Cache', 'Adding key:', key );
  31668. this.files[ key ] = file;
  31669. },
  31670. /**
  31671. * Gets the cached value for the given key.
  31672. *
  31673. * @static
  31674. * @param {string} key - The key to reference the cached file.
  31675. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31676. */
  31677. get: function ( key ) {
  31678. if ( this.enabled === false ) return;
  31679. if ( isBlobURL( key ) ) return;
  31680. // log( 'Cache', 'Checking key:', key );
  31681. return this.files[ key ];
  31682. },
  31683. /**
  31684. * Removes the cached file associated with the given key.
  31685. *
  31686. * @static
  31687. * @param {string} key - The key to reference the cached file.
  31688. */
  31689. remove: function ( key ) {
  31690. delete this.files[ key ];
  31691. },
  31692. /**
  31693. * Remove all values from the cache.
  31694. *
  31695. * @static
  31696. */
  31697. clear: function () {
  31698. this.files = {};
  31699. }
  31700. };
  31701. /**
  31702. * Returns true if the given cache key contains the blob: scheme.
  31703. *
  31704. * @private
  31705. * @param {string} key - The cache key.
  31706. * @return {boolean} Whether the given cache key contains the blob: scheme or not.
  31707. */
  31708. function isBlobURL( key ) {
  31709. try {
  31710. const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier
  31711. const url = new URL( urlString );
  31712. return url.protocol === 'blob:';
  31713. } catch ( e ) {
  31714. // If the string is not a valid URL, it throws an error
  31715. return false;
  31716. }
  31717. }
  31718. /**
  31719. * Handles and keeps track of loaded and pending data. A default global
  31720. * instance of this class is created and used by loaders if not supplied
  31721. * manually.
  31722. *
  31723. * In general that should be sufficient, however there are times when it can
  31724. * be useful to have separate loaders - for example if you want to show
  31725. * separate loading bars for objects and textures.
  31726. *
  31727. * ```js
  31728. * const manager = new THREE.LoadingManager();
  31729. * manager.onLoad = () => console.log( 'Loading complete!' );
  31730. *
  31731. * const loader1 = new OBJLoader( manager );
  31732. * const loader2 = new ColladaLoader( manager );
  31733. * ```
  31734. */
  31735. class LoadingManager {
  31736. /**
  31737. * Constructs a new loading manager.
  31738. *
  31739. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31740. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31741. * @param {Function} [onError] - Executes when an error occurs.
  31742. */
  31743. constructor( onLoad, onProgress, onError ) {
  31744. const scope = this;
  31745. let isLoading = false;
  31746. let itemsLoaded = 0;
  31747. let itemsTotal = 0;
  31748. let urlModifier = undefined;
  31749. const handlers = [];
  31750. // Refer to #5689 for the reason why we don't set .onStart
  31751. // in the constructor
  31752. /**
  31753. * Executes when an item starts loading.
  31754. *
  31755. * @type {Function|undefined}
  31756. * @default undefined
  31757. */
  31758. this.onStart = undefined;
  31759. /**
  31760. * Executes when all items have been loaded.
  31761. *
  31762. * @type {Function|undefined}
  31763. * @default undefined
  31764. */
  31765. this.onLoad = onLoad;
  31766. /**
  31767. * Executes when single items have been loaded.
  31768. *
  31769. * @type {Function|undefined}
  31770. * @default undefined
  31771. */
  31772. this.onProgress = onProgress;
  31773. /**
  31774. * Executes when an error occurs.
  31775. *
  31776. * @type {Function|undefined}
  31777. * @default undefined
  31778. */
  31779. this.onError = onError;
  31780. /**
  31781. * Used for aborting ongoing requests in loaders using this manager.
  31782. *
  31783. * @private
  31784. * @type {AbortController | null}
  31785. */
  31786. this._abortController = null;
  31787. /**
  31788. * This should be called by any loader using the manager when the loader
  31789. * starts loading an item.
  31790. *
  31791. * @param {string} url - The URL to load.
  31792. */
  31793. this.itemStart = function ( url ) {
  31794. itemsTotal ++;
  31795. if ( isLoading === false ) {
  31796. if ( scope.onStart !== undefined ) {
  31797. scope.onStart( url, itemsLoaded, itemsTotal );
  31798. }
  31799. }
  31800. isLoading = true;
  31801. };
  31802. /**
  31803. * This should be called by any loader using the manager when the loader
  31804. * ended loading an item.
  31805. *
  31806. * @param {string} url - The URL of the loaded item.
  31807. */
  31808. this.itemEnd = function ( url ) {
  31809. itemsLoaded ++;
  31810. if ( scope.onProgress !== undefined ) {
  31811. scope.onProgress( url, itemsLoaded, itemsTotal );
  31812. }
  31813. if ( itemsLoaded === itemsTotal ) {
  31814. isLoading = false;
  31815. if ( scope.onLoad !== undefined ) {
  31816. scope.onLoad();
  31817. }
  31818. }
  31819. };
  31820. /**
  31821. * This should be called by any loader using the manager when the loader
  31822. * encounters an error when loading an item.
  31823. *
  31824. * @param {string} url - The URL of the item that produces an error.
  31825. */
  31826. this.itemError = function ( url ) {
  31827. if ( scope.onError !== undefined ) {
  31828. scope.onError( url );
  31829. }
  31830. };
  31831. /**
  31832. * Given a URL, uses the URL modifier callback (if any) and returns a
  31833. * resolved URL. If no URL modifier is set, returns the original URL.
  31834. *
  31835. * @param {string} url - The URL to load.
  31836. * @return {string} The resolved URL.
  31837. */
  31838. this.resolveURL = function ( url ) {
  31839. if ( urlModifier ) {
  31840. return urlModifier( url );
  31841. }
  31842. return url;
  31843. };
  31844. /**
  31845. * If provided, the callback will be passed each resource URL before a
  31846. * request is sent. The callback may return the original URL, or a new URL to
  31847. * override loading behavior. This behavior can be used to load assets from
  31848. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31849. *
  31850. * ```js
  31851. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31852. *
  31853. * const manager = new THREE.LoadingManager();
  31854. *
  31855. * // Initialize loading manager with URL callback.
  31856. * const objectURLs = [];
  31857. * manager.setURLModifier( ( url ) => {
  31858. *
  31859. * url = URL.createObjectURL( blobs[ url ] );
  31860. * objectURLs.push( url );
  31861. * return url;
  31862. *
  31863. * } );
  31864. *
  31865. * // Load as usual, then revoke the blob URLs.
  31866. * const loader = new GLTFLoader( manager );
  31867. * loader.load( 'fish.gltf', (gltf) => {
  31868. *
  31869. * scene.add( gltf.scene );
  31870. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31871. *
  31872. * } );
  31873. * ```
  31874. *
  31875. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31876. * @return {LoadingManager} A reference to this loading manager.
  31877. */
  31878. this.setURLModifier = function ( transform ) {
  31879. urlModifier = transform;
  31880. return this;
  31881. };
  31882. /**
  31883. * Registers a loader with the given regular expression. Can be used to
  31884. * define what loader should be used in order to load specific files. A
  31885. * typical use case is to overwrite the default loader for textures.
  31886. *
  31887. * ```js
  31888. * // add handler for TGA textures
  31889. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31890. * ```
  31891. *
  31892. * @param {string} regex - A regular expression.
  31893. * @param {Loader} loader - A loader that should handle matched cases.
  31894. * @return {LoadingManager} A reference to this loading manager.
  31895. */
  31896. this.addHandler = function ( regex, loader ) {
  31897. handlers.push( regex, loader );
  31898. return this;
  31899. };
  31900. /**
  31901. * Removes the loader for the given regular expression.
  31902. *
  31903. * @param {string} regex - A regular expression.
  31904. * @return {LoadingManager} A reference to this loading manager.
  31905. */
  31906. this.removeHandler = function ( regex ) {
  31907. const index = handlers.indexOf( regex );
  31908. if ( index !== -1 ) {
  31909. handlers.splice( index, 2 );
  31910. }
  31911. return this;
  31912. };
  31913. /**
  31914. * Can be used to retrieve the registered loader for the given file path.
  31915. *
  31916. * @param {string} file - The file path.
  31917. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31918. */
  31919. this.getHandler = function ( file ) {
  31920. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31921. const regex = handlers[ i ];
  31922. const loader = handlers[ i + 1 ];
  31923. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31924. if ( regex.test( file ) ) {
  31925. return loader;
  31926. }
  31927. }
  31928. return null;
  31929. };
  31930. /**
  31931. * Can be used to abort ongoing loading requests in loaders using this manager.
  31932. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31933. * is supported in the browser.
  31934. *
  31935. * @return {LoadingManager} A reference to this loading manager.
  31936. */
  31937. this.abort = function () {
  31938. this.abortController.abort();
  31939. this._abortController = null;
  31940. return this;
  31941. };
  31942. }
  31943. // TODO: Revert this back to a single member variable once this issue has been fixed
  31944. // https://github.com/cloudflare/workerd/issues/3657
  31945. /**
  31946. * Used for aborting ongoing requests in loaders using this manager.
  31947. *
  31948. * @type {AbortController}
  31949. */
  31950. get abortController() {
  31951. if ( ! this._abortController ) {
  31952. this._abortController = new AbortController();
  31953. }
  31954. return this._abortController;
  31955. }
  31956. }
  31957. /**
  31958. * The global default loading manager.
  31959. *
  31960. * @constant
  31961. * @type {LoadingManager}
  31962. */
  31963. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31964. /**
  31965. * Abstract base class for loaders.
  31966. *
  31967. * @abstract
  31968. */
  31969. class Loader {
  31970. /**
  31971. * Constructs a new loader.
  31972. *
  31973. * @param {LoadingManager} [manager] - The loading manager.
  31974. */
  31975. constructor( manager ) {
  31976. /**
  31977. * The loading manager.
  31978. *
  31979. * @type {LoadingManager}
  31980. * @default DefaultLoadingManager
  31981. */
  31982. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31983. /**
  31984. * The crossOrigin string to implement CORS for loading the url from a
  31985. * different domain that allows CORS.
  31986. *
  31987. * @type {string}
  31988. * @default 'anonymous'
  31989. */
  31990. this.crossOrigin = 'anonymous';
  31991. /**
  31992. * Whether the XMLHttpRequest uses credentials.
  31993. *
  31994. * @type {boolean}
  31995. * @default false
  31996. */
  31997. this.withCredentials = false;
  31998. /**
  31999. * The base path from which the asset will be loaded.
  32000. *
  32001. * @type {string}
  32002. */
  32003. this.path = '';
  32004. /**
  32005. * The base path from which additional resources like textures will be loaded.
  32006. *
  32007. * @type {string}
  32008. */
  32009. this.resourcePath = '';
  32010. /**
  32011. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32012. * used in HTTP request.
  32013. *
  32014. * @type {Object<string, any>}
  32015. */
  32016. this.requestHeader = {};
  32017. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32018. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32019. }
  32020. }
  32021. /**
  32022. * This method needs to be implemented by all concrete loaders. It holds the
  32023. * logic for loading assets from the backend.
  32024. *
  32025. * @abstract
  32026. * @param {string} url - The path/URL of the file to be loaded.
  32027. * @param {Function} onLoad - Executed when the loading process has been finished.
  32028. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32029. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32030. */
  32031. load( /* url, onLoad, onProgress, onError */ ) {}
  32032. /**
  32033. * A async version of {@link Loader#load}.
  32034. *
  32035. * @param {string} url - The path/URL of the file to be loaded.
  32036. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32037. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32038. */
  32039. loadAsync( url, onProgress ) {
  32040. const scope = this;
  32041. return new Promise( function ( resolve, reject ) {
  32042. scope.load( url, resolve, onProgress, reject );
  32043. } );
  32044. }
  32045. /**
  32046. * This method needs to be implemented by all concrete loaders. It holds the
  32047. * logic for parsing the asset into three.js entities.
  32048. *
  32049. * @abstract
  32050. * @param {any} data - The data to parse.
  32051. */
  32052. parse( /* data */ ) {}
  32053. /**
  32054. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32055. * from a different domain that allows CORS.
  32056. *
  32057. * @param {string} crossOrigin - The `crossOrigin` value.
  32058. * @return {Loader} A reference to this instance.
  32059. */
  32060. setCrossOrigin( crossOrigin ) {
  32061. this.crossOrigin = crossOrigin;
  32062. return this;
  32063. }
  32064. /**
  32065. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32066. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32067. *
  32068. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32069. *
  32070. * @param {boolean} value - The `withCredentials` value.
  32071. * @return {Loader} A reference to this instance.
  32072. */
  32073. setWithCredentials( value ) {
  32074. this.withCredentials = value;
  32075. return this;
  32076. }
  32077. /**
  32078. * Sets the base path for the asset.
  32079. *
  32080. * @param {string} path - The base path.
  32081. * @return {Loader} A reference to this instance.
  32082. */
  32083. setPath( path ) {
  32084. this.path = path;
  32085. return this;
  32086. }
  32087. /**
  32088. * Sets the base path for dependent resources like textures.
  32089. *
  32090. * @param {string} resourcePath - The resource path.
  32091. * @return {Loader} A reference to this instance.
  32092. */
  32093. setResourcePath( resourcePath ) {
  32094. this.resourcePath = resourcePath;
  32095. return this;
  32096. }
  32097. /**
  32098. * Sets the given request header.
  32099. *
  32100. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32101. * for configuring the HTTP request.
  32102. * @return {Loader} A reference to this instance.
  32103. */
  32104. setRequestHeader( requestHeader ) {
  32105. this.requestHeader = requestHeader;
  32106. return this;
  32107. }
  32108. /**
  32109. * This method can be implemented in loaders for aborting ongoing requests.
  32110. *
  32111. * @abstract
  32112. * @return {Loader} A reference to this instance.
  32113. */
  32114. abort() {
  32115. return this;
  32116. }
  32117. }
  32118. /**
  32119. * Callback for onProgress in loaders.
  32120. *
  32121. * @callback onProgressCallback
  32122. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32123. */
  32124. /**
  32125. * Callback for onError in loaders.
  32126. *
  32127. * @callback onErrorCallback
  32128. * @param {Error} error - The error which occurred during the loading process.
  32129. */
  32130. /**
  32131. * The default material name that is used by loaders
  32132. * when creating materials for loaded 3D objects.
  32133. *
  32134. * Note: Not all loaders might honor this setting.
  32135. *
  32136. * @static
  32137. * @type {string}
  32138. * @default '__DEFAULT'
  32139. */
  32140. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32141. const loading = {};
  32142. class HttpError extends Error {
  32143. constructor( message, response ) {
  32144. super( message );
  32145. this.response = response;
  32146. }
  32147. }
  32148. /**
  32149. * A low level class for loading resources with the Fetch API, used internally by
  32150. * most loaders. It can also be used directly to load any file type that does
  32151. * not have a loader.
  32152. *
  32153. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32154. * once to your application.
  32155. *
  32156. * ```js
  32157. * const loader = new THREE.FileLoader();
  32158. * const data = await loader.loadAsync( 'example.txt' );
  32159. * ```
  32160. *
  32161. * @augments Loader
  32162. */
  32163. class FileLoader extends Loader {
  32164. /**
  32165. * Constructs a new file loader.
  32166. *
  32167. * @param {LoadingManager} [manager] - The loading manager.
  32168. */
  32169. constructor( manager ) {
  32170. super( manager );
  32171. /**
  32172. * The expected mime type. Valid values can be found
  32173. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32174. *
  32175. * @type {string}
  32176. */
  32177. this.mimeType = '';
  32178. /**
  32179. * The expected response type.
  32180. *
  32181. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32182. * @default ''
  32183. */
  32184. this.responseType = '';
  32185. /**
  32186. * Used for aborting requests.
  32187. *
  32188. * @private
  32189. * @type {AbortController}
  32190. */
  32191. this._abortController = new AbortController();
  32192. }
  32193. /**
  32194. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32195. *
  32196. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32197. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32198. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32199. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32200. * @return {any|undefined} The cached resource if available.
  32201. */
  32202. load( url, onLoad, onProgress, onError ) {
  32203. if ( url === undefined ) url = '';
  32204. if ( this.path !== undefined ) url = this.path + url;
  32205. url = this.manager.resolveURL( url );
  32206. const cached = Cache.get( `file:${url}` );
  32207. if ( cached !== undefined ) {
  32208. this.manager.itemStart( url );
  32209. setTimeout( () => {
  32210. if ( onLoad ) onLoad( cached );
  32211. this.manager.itemEnd( url );
  32212. }, 0 );
  32213. return cached;
  32214. }
  32215. // Check if request is duplicate
  32216. if ( loading[ url ] !== undefined ) {
  32217. loading[ url ].push( {
  32218. onLoad: onLoad,
  32219. onProgress: onProgress,
  32220. onError: onError
  32221. } );
  32222. return;
  32223. }
  32224. // Initialise array for duplicate requests
  32225. loading[ url ] = [];
  32226. loading[ url ].push( {
  32227. onLoad: onLoad,
  32228. onProgress: onProgress,
  32229. onError: onError,
  32230. } );
  32231. // create request
  32232. const req = new Request( url, {
  32233. headers: new Headers( this.requestHeader ),
  32234. credentials: this.withCredentials ? 'include' : 'same-origin',
  32235. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32236. } );
  32237. // record states ( avoid data race )
  32238. const mimeType = this.mimeType;
  32239. const responseType = this.responseType;
  32240. // start the fetch
  32241. fetch( req )
  32242. .then( response => {
  32243. if ( response.status === 200 || response.status === 0 ) {
  32244. // Some browsers return HTTP Status 0 when using non-http protocol
  32245. // e.g. 'file://' or 'data://'. Handle as success.
  32246. if ( response.status === 0 ) {
  32247. warn( 'FileLoader: HTTP Status 0 received.' );
  32248. }
  32249. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32250. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32251. return response;
  32252. }
  32253. const callbacks = loading[ url ];
  32254. const reader = response.body.getReader();
  32255. // Nginx needs X-File-Size check
  32256. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32257. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32258. const total = contentLength ? parseInt( contentLength ) : 0;
  32259. const lengthComputable = total !== 0;
  32260. let loaded = 0;
  32261. // periodically read data into the new stream tracking while download progress
  32262. const stream = new ReadableStream( {
  32263. start( controller ) {
  32264. readData();
  32265. function readData() {
  32266. reader.read().then( ( { done, value } ) => {
  32267. if ( done ) {
  32268. controller.close();
  32269. } else {
  32270. loaded += value.byteLength;
  32271. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32272. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32273. const callback = callbacks[ i ];
  32274. if ( callback.onProgress ) callback.onProgress( event );
  32275. }
  32276. controller.enqueue( value );
  32277. readData();
  32278. }
  32279. }, ( e ) => {
  32280. controller.error( e );
  32281. } );
  32282. }
  32283. }
  32284. } );
  32285. return new Response( stream );
  32286. } else {
  32287. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32288. }
  32289. } )
  32290. .then( response => {
  32291. switch ( responseType ) {
  32292. case 'arraybuffer':
  32293. return response.arrayBuffer();
  32294. case 'blob':
  32295. return response.blob();
  32296. case 'document':
  32297. return response.text()
  32298. .then( text => {
  32299. const parser = new DOMParser();
  32300. return parser.parseFromString( text, mimeType );
  32301. } );
  32302. case 'json':
  32303. return response.json();
  32304. default:
  32305. if ( mimeType === '' ) {
  32306. return response.text();
  32307. } else {
  32308. // sniff encoding
  32309. const re = /charset="?([^;"\s]*)"?/i;
  32310. const exec = re.exec( mimeType );
  32311. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32312. const decoder = new TextDecoder( label );
  32313. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32314. }
  32315. }
  32316. } )
  32317. .then( data => {
  32318. // Add to cache only on HTTP success, so that we do not cache
  32319. // error response bodies as proper responses to requests.
  32320. Cache.add( `file:${url}`, data );
  32321. const callbacks = loading[ url ];
  32322. delete loading[ url ];
  32323. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32324. const callback = callbacks[ i ];
  32325. if ( callback.onLoad ) callback.onLoad( data );
  32326. }
  32327. } )
  32328. .catch( err => {
  32329. // Abort errors and other errors are handled the same
  32330. const callbacks = loading[ url ];
  32331. if ( callbacks === undefined ) {
  32332. // When onLoad was called and url was deleted in `loading`
  32333. this.manager.itemError( url );
  32334. throw err;
  32335. }
  32336. delete loading[ url ];
  32337. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32338. const callback = callbacks[ i ];
  32339. if ( callback.onError ) callback.onError( err );
  32340. }
  32341. this.manager.itemError( url );
  32342. } )
  32343. .finally( () => {
  32344. this.manager.itemEnd( url );
  32345. } );
  32346. this.manager.itemStart( url );
  32347. }
  32348. /**
  32349. * Sets the expected response type.
  32350. *
  32351. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32352. * @return {FileLoader} A reference to this file loader.
  32353. */
  32354. setResponseType( value ) {
  32355. this.responseType = value;
  32356. return this;
  32357. }
  32358. /**
  32359. * Sets the expected mime type of the loaded file.
  32360. *
  32361. * @param {string} value - The mime type.
  32362. * @return {FileLoader} A reference to this file loader.
  32363. */
  32364. setMimeType( value ) {
  32365. this.mimeType = value;
  32366. return this;
  32367. }
  32368. /**
  32369. * Aborts ongoing fetch requests.
  32370. *
  32371. * @return {FileLoader} A reference to this instance.
  32372. */
  32373. abort() {
  32374. this._abortController.abort();
  32375. this._abortController = new AbortController();
  32376. return this;
  32377. }
  32378. }
  32379. /**
  32380. * Class for loading animation clips in the JSON format. The files are internally
  32381. * loaded via {@link FileLoader}.
  32382. *
  32383. * ```js
  32384. * const loader = new THREE.AnimationLoader();
  32385. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32386. * ```
  32387. *
  32388. * @augments Loader
  32389. */
  32390. class AnimationLoader extends Loader {
  32391. /**
  32392. * Constructs a new animation loader.
  32393. *
  32394. * @param {LoadingManager} [manager] - The loading manager.
  32395. */
  32396. constructor( manager ) {
  32397. super( manager );
  32398. }
  32399. /**
  32400. * Starts loading from the given URL and pass the loaded animations as an array
  32401. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32402. *
  32403. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32404. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32405. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32406. * @param {onErrorCallback} onError - Executed when errors occur.
  32407. */
  32408. load( url, onLoad, onProgress, onError ) {
  32409. const scope = this;
  32410. const loader = new FileLoader( this.manager );
  32411. loader.setPath( this.path );
  32412. loader.setRequestHeader( this.requestHeader );
  32413. loader.setWithCredentials( this.withCredentials );
  32414. loader.load( url, function ( text ) {
  32415. try {
  32416. onLoad( scope.parse( JSON.parse( text ) ) );
  32417. } catch ( e ) {
  32418. if ( onError ) {
  32419. onError( e );
  32420. } else {
  32421. error( e );
  32422. }
  32423. scope.manager.itemError( url );
  32424. }
  32425. }, onProgress, onError );
  32426. }
  32427. /**
  32428. * Parses the given JSON object and returns an array of animation clips.
  32429. *
  32430. * @param {Object} json - The serialized animation clips.
  32431. * @return {Array<AnimationClip>} The parsed animation clips.
  32432. */
  32433. parse( json ) {
  32434. const animations = [];
  32435. for ( let i = 0; i < json.length; i ++ ) {
  32436. const clip = AnimationClip.parse( json[ i ] );
  32437. animations.push( clip );
  32438. }
  32439. return animations;
  32440. }
  32441. }
  32442. /**
  32443. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32444. * Textures are internally loaded via {@link FileLoader}.
  32445. *
  32446. * Derived classes have to implement the `parse()` method which holds the parsing
  32447. * for the respective format.
  32448. *
  32449. * @abstract
  32450. * @augments Loader
  32451. */
  32452. class CompressedTextureLoader extends Loader {
  32453. /**
  32454. * Constructs a new compressed texture loader.
  32455. *
  32456. * @param {LoadingManager} [manager] - The loading manager.
  32457. */
  32458. constructor( manager ) {
  32459. super( manager );
  32460. }
  32461. /**
  32462. * Starts loading from the given URL and passes the loaded compressed texture
  32463. * to the `onLoad()` callback. The method also returns a new texture object which can
  32464. * directly be used for material creation. If you do it this way, the texture
  32465. * may pop up in your scene once the respective loading process is finished.
  32466. *
  32467. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32468. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32469. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32470. * @param {onErrorCallback} onError - Executed when errors occur.
  32471. * @return {CompressedTexture} The compressed texture.
  32472. */
  32473. load( url, onLoad, onProgress, onError ) {
  32474. const scope = this;
  32475. const images = [];
  32476. const texture = new CompressedTexture();
  32477. const loader = new FileLoader( this.manager );
  32478. loader.setPath( this.path );
  32479. loader.setResponseType( 'arraybuffer' );
  32480. loader.setRequestHeader( this.requestHeader );
  32481. loader.setWithCredentials( scope.withCredentials );
  32482. let loaded = 0;
  32483. function loadTexture( i ) {
  32484. loader.load( url[ i ], function ( buffer ) {
  32485. const texDatas = scope.parse( buffer, true );
  32486. images[ i ] = {
  32487. width: texDatas.width,
  32488. height: texDatas.height,
  32489. format: texDatas.format,
  32490. mipmaps: texDatas.mipmaps
  32491. };
  32492. loaded += 1;
  32493. if ( loaded === 6 ) {
  32494. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32495. texture.image = images;
  32496. texture.format = texDatas.format;
  32497. texture.needsUpdate = true;
  32498. if ( onLoad ) onLoad( texture );
  32499. }
  32500. }, onProgress, onError );
  32501. }
  32502. if ( Array.isArray( url ) ) {
  32503. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32504. loadTexture( i );
  32505. }
  32506. } else {
  32507. // compressed cubemap texture stored in a single DDS file
  32508. loader.load( url, function ( buffer ) {
  32509. const texDatas = scope.parse( buffer, true );
  32510. if ( texDatas.isCubemap ) {
  32511. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32512. for ( let f = 0; f < faces; f ++ ) {
  32513. images[ f ] = { mipmaps: [] };
  32514. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32515. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32516. images[ f ].format = texDatas.format;
  32517. images[ f ].width = texDatas.width;
  32518. images[ f ].height = texDatas.height;
  32519. }
  32520. }
  32521. texture.image = images;
  32522. } else {
  32523. texture.image.width = texDatas.width;
  32524. texture.image.height = texDatas.height;
  32525. texture.mipmaps = texDatas.mipmaps;
  32526. }
  32527. if ( texDatas.mipmapCount === 1 ) {
  32528. texture.minFilter = LinearFilter;
  32529. }
  32530. texture.format = texDatas.format;
  32531. texture.needsUpdate = true;
  32532. if ( onLoad ) onLoad( texture );
  32533. }, onProgress, onError );
  32534. }
  32535. return texture;
  32536. }
  32537. }
  32538. const _loading = new WeakMap();
  32539. /**
  32540. * A loader for loading images. The class loads images with the HTML `Image` API.
  32541. *
  32542. * ```js
  32543. * const loader = new THREE.ImageLoader();
  32544. * const image = await loader.loadAsync( 'image.png' );
  32545. * ```
  32546. * Please note that `ImageLoader` has dropped support for progress
  32547. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32548. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32549. *
  32550. * @augments Loader
  32551. */
  32552. class ImageLoader extends Loader {
  32553. /**
  32554. * Constructs a new image loader.
  32555. *
  32556. * @param {LoadingManager} [manager] - The loading manager.
  32557. */
  32558. constructor( manager ) {
  32559. super( manager );
  32560. }
  32561. /**
  32562. * Starts loading from the given URL and passes the loaded image
  32563. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32564. * directly be used for texture creation. If you do it this way, the texture
  32565. * may pop up in your scene once the respective loading process is finished.
  32566. *
  32567. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32568. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32569. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32570. * @param {onErrorCallback} onError - Executed when errors occur.
  32571. * @return {Image} The image.
  32572. */
  32573. load( url, onLoad, onProgress, onError ) {
  32574. if ( this.path !== undefined ) url = this.path + url;
  32575. url = this.manager.resolveURL( url );
  32576. const scope = this;
  32577. const cached = Cache.get( `image:${url}` );
  32578. if ( cached !== undefined ) {
  32579. if ( cached.complete === true ) {
  32580. scope.manager.itemStart( url );
  32581. setTimeout( function () {
  32582. if ( onLoad ) onLoad( cached );
  32583. scope.manager.itemEnd( url );
  32584. }, 0 );
  32585. } else {
  32586. let arr = _loading.get( cached );
  32587. if ( arr === undefined ) {
  32588. arr = [];
  32589. _loading.set( cached, arr );
  32590. }
  32591. arr.push( { onLoad, onError } );
  32592. }
  32593. return cached;
  32594. }
  32595. const image = createElementNS( 'img' );
  32596. function onImageLoad() {
  32597. removeEventListeners();
  32598. if ( onLoad ) onLoad( this );
  32599. //
  32600. const callbacks = _loading.get( this ) || [];
  32601. for ( let i = 0; i < callbacks.length; i ++ ) {
  32602. const callback = callbacks[ i ];
  32603. if ( callback.onLoad ) callback.onLoad( this );
  32604. }
  32605. _loading.delete( this );
  32606. scope.manager.itemEnd( url );
  32607. }
  32608. function onImageError( event ) {
  32609. removeEventListeners();
  32610. if ( onError ) onError( event );
  32611. Cache.remove( `image:${url}` );
  32612. //
  32613. const callbacks = _loading.get( this ) || [];
  32614. for ( let i = 0; i < callbacks.length; i ++ ) {
  32615. const callback = callbacks[ i ];
  32616. if ( callback.onError ) callback.onError( event );
  32617. }
  32618. _loading.delete( this );
  32619. scope.manager.itemError( url );
  32620. scope.manager.itemEnd( url );
  32621. }
  32622. function removeEventListeners() {
  32623. image.removeEventListener( 'load', onImageLoad, false );
  32624. image.removeEventListener( 'error', onImageError, false );
  32625. }
  32626. image.addEventListener( 'load', onImageLoad, false );
  32627. image.addEventListener( 'error', onImageError, false );
  32628. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32629. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32630. }
  32631. Cache.add( `image:${url}`, image );
  32632. scope.manager.itemStart( url );
  32633. image.src = url;
  32634. return image;
  32635. }
  32636. }
  32637. /**
  32638. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32639. *
  32640. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32641. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32642. * like vertical and horizontal cross, column and row layouts are not supported.
  32643. *
  32644. * Note that, by convention, cube maps are specified in a coordinate system
  32645. * in which positive-x is to the right when looking up the positive-z axis --
  32646. * in other words, using a left-handed coordinate system. Since three.js uses
  32647. * a right-handed coordinate system, environment maps used in three.js will
  32648. * have pos-x and neg-x swapped.
  32649. *
  32650. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32651. * is set to `SRGBColorSpace` by default.
  32652. *
  32653. * ```js
  32654. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32655. * const cubeTexture = await loader.loadAsync( [
  32656. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32657. * ] );
  32658. * scene.background = cubeTexture;
  32659. * ```
  32660. *
  32661. * @augments Loader
  32662. */
  32663. class CubeTextureLoader extends Loader {
  32664. /**
  32665. * Constructs a new cube texture loader.
  32666. *
  32667. * @param {LoadingManager} [manager] - The loading manager.
  32668. */
  32669. constructor( manager ) {
  32670. super( manager );
  32671. }
  32672. /**
  32673. * Starts loading from the given URL and pass the fully loaded cube texture
  32674. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32675. * directly be used for material creation. If you do it this way, the cube texture
  32676. * may pop up in your scene once the respective loading process is finished.
  32677. *
  32678. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32679. * cube texture. The urls should be specified in the following order: pos-x,
  32680. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32681. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32682. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32683. * @param {onErrorCallback} onError - Executed when errors occur.
  32684. * @return {CubeTexture} The cube texture.
  32685. */
  32686. load( urls, onLoad, onProgress, onError ) {
  32687. const texture = new CubeTexture();
  32688. texture.colorSpace = SRGBColorSpace;
  32689. const loader = new ImageLoader( this.manager );
  32690. loader.setCrossOrigin( this.crossOrigin );
  32691. loader.setPath( this.path );
  32692. let loaded = 0;
  32693. function loadTexture( i ) {
  32694. loader.load( urls[ i ], function ( image ) {
  32695. texture.images[ i ] = image;
  32696. loaded ++;
  32697. if ( loaded === 6 ) {
  32698. texture.needsUpdate = true;
  32699. if ( onLoad ) onLoad( texture );
  32700. }
  32701. }, undefined, onError );
  32702. }
  32703. for ( let i = 0; i < urls.length; ++ i ) {
  32704. loadTexture( i );
  32705. }
  32706. return texture;
  32707. }
  32708. }
  32709. /**
  32710. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32711. * Textures are internally loaded via {@link FileLoader}.
  32712. *
  32713. * Derived classes have to implement the `parse()` method which holds the parsing
  32714. * for the respective format.
  32715. *
  32716. * @abstract
  32717. * @augments Loader
  32718. */
  32719. class DataTextureLoader extends Loader {
  32720. /**
  32721. * Constructs a new data texture loader.
  32722. *
  32723. * @param {LoadingManager} [manager] - The loading manager.
  32724. */
  32725. constructor( manager ) {
  32726. super( manager );
  32727. }
  32728. /**
  32729. * Starts loading from the given URL and passes the loaded data texture
  32730. * to the `onLoad()` callback. The method also returns a new texture object which can
  32731. * directly be used for material creation. If you do it this way, the texture
  32732. * may pop up in your scene once the respective loading process is finished.
  32733. *
  32734. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32735. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32736. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32737. * @param {onErrorCallback} onError - Executed when errors occur.
  32738. * @return {DataTexture} The data texture.
  32739. */
  32740. load( url, onLoad, onProgress, onError ) {
  32741. const scope = this;
  32742. const texture = new DataTexture();
  32743. const loader = new FileLoader( this.manager );
  32744. loader.setResponseType( 'arraybuffer' );
  32745. loader.setRequestHeader( this.requestHeader );
  32746. loader.setPath( this.path );
  32747. loader.setWithCredentials( scope.withCredentials );
  32748. loader.load( url, function ( buffer ) {
  32749. let texData;
  32750. try {
  32751. texData = scope.parse( buffer );
  32752. } catch ( error ) {
  32753. if ( onError !== undefined ) {
  32754. onError( error );
  32755. } else {
  32756. error( error );
  32757. return;
  32758. }
  32759. }
  32760. if ( texData.image !== undefined ) {
  32761. texture.image = texData.image;
  32762. } else if ( texData.data !== undefined ) {
  32763. texture.image.width = texData.width;
  32764. texture.image.height = texData.height;
  32765. texture.image.data = texData.data;
  32766. }
  32767. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32768. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32769. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32770. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32771. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32772. if ( texData.colorSpace !== undefined ) {
  32773. texture.colorSpace = texData.colorSpace;
  32774. }
  32775. if ( texData.flipY !== undefined ) {
  32776. texture.flipY = texData.flipY;
  32777. }
  32778. if ( texData.format !== undefined ) {
  32779. texture.format = texData.format;
  32780. }
  32781. if ( texData.type !== undefined ) {
  32782. texture.type = texData.type;
  32783. }
  32784. if ( texData.mipmaps !== undefined ) {
  32785. texture.mipmaps = texData.mipmaps;
  32786. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32787. }
  32788. if ( texData.mipmapCount === 1 ) {
  32789. texture.minFilter = LinearFilter;
  32790. }
  32791. if ( texData.generateMipmaps !== undefined ) {
  32792. texture.generateMipmaps = texData.generateMipmaps;
  32793. }
  32794. texture.needsUpdate = true;
  32795. if ( onLoad ) onLoad( texture, texData );
  32796. }, onProgress, onError );
  32797. return texture;
  32798. }
  32799. }
  32800. /**
  32801. * Class for loading textures. Images are internally
  32802. * loaded via {@link ImageLoader}.
  32803. *
  32804. * ```js
  32805. * const loader = new THREE.TextureLoader();
  32806. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32807. *
  32808. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32809. * ```
  32810. * Please note that `TextureLoader` has dropped support for progress
  32811. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32812. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  32813. *
  32814. * @augments Loader
  32815. */
  32816. class TextureLoader extends Loader {
  32817. /**
  32818. * Constructs a new texture loader.
  32819. *
  32820. * @param {LoadingManager} [manager] - The loading manager.
  32821. */
  32822. constructor( manager ) {
  32823. super( manager );
  32824. }
  32825. /**
  32826. * Starts loading from the given URL and pass the fully loaded texture
  32827. * to the `onLoad()` callback. The method also returns a new texture object which can
  32828. * directly be used for material creation. If you do it this way, the texture
  32829. * may pop up in your scene once the respective loading process is finished.
  32830. *
  32831. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32832. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32833. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32834. * @param {onErrorCallback} onError - Executed when errors occur.
  32835. * @return {Texture} The texture.
  32836. */
  32837. load( url, onLoad, onProgress, onError ) {
  32838. const texture = new Texture();
  32839. const loader = new ImageLoader( this.manager );
  32840. loader.setCrossOrigin( this.crossOrigin );
  32841. loader.setPath( this.path );
  32842. loader.load( url, function ( image ) {
  32843. texture.image = image;
  32844. texture.needsUpdate = true;
  32845. if ( onLoad !== undefined ) {
  32846. onLoad( texture );
  32847. }
  32848. }, onProgress, onError );
  32849. return texture;
  32850. }
  32851. }
  32852. /**
  32853. * Abstract base class for lights - all other light types inherit the
  32854. * properties and methods described here.
  32855. *
  32856. * @abstract
  32857. * @augments Object3D
  32858. */
  32859. class Light extends Object3D {
  32860. /**
  32861. * Constructs a new light.
  32862. *
  32863. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32864. * @param {number} [intensity=1] - The light's strength/intensity.
  32865. */
  32866. constructor( color, intensity = 1 ) {
  32867. super();
  32868. /**
  32869. * This flag can be used for type testing.
  32870. *
  32871. * @type {boolean}
  32872. * @readonly
  32873. * @default true
  32874. */
  32875. this.isLight = true;
  32876. this.type = 'Light';
  32877. /**
  32878. * The light's color.
  32879. *
  32880. * @type {Color}
  32881. */
  32882. this.color = new Color( color );
  32883. /**
  32884. * The light's intensity.
  32885. *
  32886. * @type {number}
  32887. * @default 1
  32888. */
  32889. this.intensity = intensity;
  32890. }
  32891. /**
  32892. * Frees the GPU-related resources allocated by this instance. Call this
  32893. * method whenever this instance is no longer used in your app.
  32894. */
  32895. dispose() {
  32896. this.dispatchEvent( { type: 'dispose' } );
  32897. }
  32898. copy( source, recursive ) {
  32899. super.copy( source, recursive );
  32900. this.color.copy( source.color );
  32901. this.intensity = source.intensity;
  32902. return this;
  32903. }
  32904. toJSON( meta ) {
  32905. const data = super.toJSON( meta );
  32906. data.object.color = this.color.getHex();
  32907. data.object.intensity = this.intensity;
  32908. return data;
  32909. }
  32910. }
  32911. /**
  32912. * A light source positioned directly above the scene, with color fading from
  32913. * the sky color to the ground color.
  32914. *
  32915. * This light cannot be used to cast shadows.
  32916. *
  32917. * ```js
  32918. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32919. * scene.add( light );
  32920. * ```
  32921. *
  32922. * @augments Light
  32923. */
  32924. class HemisphereLight extends Light {
  32925. /**
  32926. * Constructs a new hemisphere light.
  32927. *
  32928. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32929. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32930. * @param {number} [intensity=1] - The light's strength/intensity.
  32931. */
  32932. constructor( skyColor, groundColor, intensity ) {
  32933. super( skyColor, intensity );
  32934. /**
  32935. * This flag can be used for type testing.
  32936. *
  32937. * @type {boolean}
  32938. * @readonly
  32939. * @default true
  32940. */
  32941. this.isHemisphereLight = true;
  32942. this.type = 'HemisphereLight';
  32943. this.position.copy( Object3D.DEFAULT_UP );
  32944. this.updateMatrix();
  32945. /**
  32946. * The light's ground color.
  32947. *
  32948. * @type {Color}
  32949. */
  32950. this.groundColor = new Color( groundColor );
  32951. }
  32952. copy( source, recursive ) {
  32953. super.copy( source, recursive );
  32954. this.groundColor.copy( source.groundColor );
  32955. return this;
  32956. }
  32957. toJSON( meta ) {
  32958. const data = super.toJSON( meta );
  32959. data.object.groundColor = this.groundColor.getHex();
  32960. return data;
  32961. }
  32962. }
  32963. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32964. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32965. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32966. /**
  32967. * Abstract base class for light shadow classes. These classes
  32968. * represent the shadow configuration for different light types.
  32969. *
  32970. * @abstract
  32971. */
  32972. class LightShadow {
  32973. /**
  32974. * Constructs a new light shadow.
  32975. *
  32976. * @param {Camera} camera - The light's view of the world.
  32977. */
  32978. constructor( camera ) {
  32979. /**
  32980. * The light's view of the world.
  32981. *
  32982. * @type {Camera}
  32983. */
  32984. this.camera = camera;
  32985. /**
  32986. * The intensity of the shadow. The default is `1`.
  32987. * Valid values are in the range `[0, 1]`.
  32988. *
  32989. * @type {number}
  32990. * @default 1
  32991. */
  32992. this.intensity = 1;
  32993. /**
  32994. * Shadow map bias, how much to add or subtract from the normalized depth
  32995. * when deciding whether a surface is in shadow.
  32996. *
  32997. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32998. * may help reduce artifacts in shadows.
  32999. *
  33000. * @type {number}
  33001. * @default 0
  33002. */
  33003. this.bias = 0;
  33004. /**
  33005. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33006. *
  33007. * If a bias node is defined, `bias` has no effect.
  33008. *
  33009. * @type {?Node<float>}
  33010. * @default null
  33011. */
  33012. this.biasNode = null;
  33013. /**
  33014. * Defines how much the position used to query the shadow map is offset along
  33015. * the object normal. The default is `0`. Increasing this value can be used to
  33016. * reduce shadow acne especially in large scenes where light shines onto
  33017. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33018. *
  33019. * @type {number}
  33020. * @default 0
  33021. */
  33022. this.normalBias = 0;
  33023. /**
  33024. * Setting this to values greater than 1 will blur the edges of the shadow.
  33025. * High values will cause unwanted banding effects in the shadows - a greater
  33026. * map size will allow for a higher value to be used here before these effects
  33027. * become visible.
  33028. *
  33029. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33030. *
  33031. * @type {number}
  33032. * @default 1
  33033. */
  33034. this.radius = 1;
  33035. /**
  33036. * The amount of samples to use when blurring a VSM shadow map.
  33037. *
  33038. * @type {number}
  33039. * @default 8
  33040. */
  33041. this.blurSamples = 8;
  33042. /**
  33043. * Defines the width and height of the shadow map. Higher values give better quality
  33044. * shadows at the cost of computation time. Values must be powers of two.
  33045. *
  33046. * @type {Vector2}
  33047. * @default (512,512)
  33048. */
  33049. this.mapSize = new Vector2( 512, 512 );
  33050. /**
  33051. * The type of shadow texture. The default is `UnsignedByteType`.
  33052. *
  33053. * @type {number}
  33054. * @default UnsignedByteType
  33055. */
  33056. this.mapType = UnsignedByteType;
  33057. /**
  33058. * The depth map generated using the internal camera; a location beyond a
  33059. * pixel's depth is in shadow. Computed internally during rendering.
  33060. *
  33061. * @type {?RenderTarget}
  33062. * @default null
  33063. */
  33064. this.map = null;
  33065. /**
  33066. * The distribution map generated using the internal camera; an occlusion is
  33067. * calculated based on the distribution of depths. Computed internally during
  33068. * rendering.
  33069. *
  33070. * @type {?RenderTarget}
  33071. * @default null
  33072. */
  33073. this.mapPass = null;
  33074. /**
  33075. * Model to shadow camera space, to compute location and depth in shadow map.
  33076. * This is computed internally during rendering.
  33077. *
  33078. * @type {Matrix4}
  33079. */
  33080. this.matrix = new Matrix4();
  33081. /**
  33082. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33083. * lighting / shadows, you may set this to `false`.
  33084. *
  33085. * @type {boolean}
  33086. * @default true
  33087. */
  33088. this.autoUpdate = true;
  33089. /**
  33090. * When set to `true`, shadow maps will be updated in the next `render` call.
  33091. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33092. * set this property to `true` and then make a render call to update the light's shadow.
  33093. *
  33094. * @type {boolean}
  33095. * @default false
  33096. */
  33097. this.needsUpdate = false;
  33098. this._frustum = new Frustum();
  33099. this._frameExtents = new Vector2( 1, 1 );
  33100. this._viewportCount = 1;
  33101. this._viewports = [
  33102. new Vector4( 0, 0, 1, 1 )
  33103. ];
  33104. }
  33105. /**
  33106. * Used internally by the renderer to get the number of viewports that need
  33107. * to be rendered for this shadow.
  33108. *
  33109. * @return {number} The viewport count.
  33110. */
  33111. getViewportCount() {
  33112. return this._viewportCount;
  33113. }
  33114. /**
  33115. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33116. *
  33117. * @return {Frustum} The shadow camera frustum.
  33118. */
  33119. getFrustum() {
  33120. return this._frustum;
  33121. }
  33122. /**
  33123. * Update the matrices for the camera and shadow, used internally by the renderer.
  33124. *
  33125. * @param {Light} light - The light for which the shadow is being rendered.
  33126. */
  33127. updateMatrices( light ) {
  33128. const shadowCamera = this.camera;
  33129. const shadowMatrix = this.matrix;
  33130. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33131. shadowCamera.position.copy( _lightPositionWorld$1 );
  33132. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33133. shadowCamera.lookAt( _lookTarget$1 );
  33134. shadowCamera.updateMatrixWorld();
  33135. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33136. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33137. if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) {
  33138. shadowMatrix.set(
  33139. 0.5, 0.0, 0.0, 0.5,
  33140. 0.0, 0.5, 0.0, 0.5,
  33141. 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix)
  33142. 0.0, 0.0, 0.0, 1.0
  33143. );
  33144. } else {
  33145. shadowMatrix.set(
  33146. 0.5, 0.0, 0.0, 0.5,
  33147. 0.0, 0.5, 0.0, 0.5,
  33148. 0.0, 0.0, 0.5, 0.5,
  33149. 0.0, 0.0, 0.0, 1.0
  33150. );
  33151. }
  33152. shadowMatrix.multiply( _projScreenMatrix$1 );
  33153. }
  33154. /**
  33155. * Returns a viewport definition for the given viewport index.
  33156. *
  33157. * @param {number} viewportIndex - The viewport index.
  33158. * @return {Vector4} The viewport.
  33159. */
  33160. getViewport( viewportIndex ) {
  33161. return this._viewports[ viewportIndex ];
  33162. }
  33163. /**
  33164. * Returns the frame extends.
  33165. *
  33166. * @return {Vector2} The frame extends.
  33167. */
  33168. getFrameExtents() {
  33169. return this._frameExtents;
  33170. }
  33171. /**
  33172. * Frees the GPU-related resources allocated by this instance. Call this
  33173. * method whenever this instance is no longer used in your app.
  33174. */
  33175. dispose() {
  33176. if ( this.map ) {
  33177. this.map.dispose();
  33178. }
  33179. if ( this.mapPass ) {
  33180. this.mapPass.dispose();
  33181. }
  33182. }
  33183. /**
  33184. * Copies the values of the given light shadow instance to this instance.
  33185. *
  33186. * @param {LightShadow} source - The light shadow to copy.
  33187. * @return {LightShadow} A reference to this light shadow instance.
  33188. */
  33189. copy( source ) {
  33190. this.camera = source.camera.clone();
  33191. this.intensity = source.intensity;
  33192. this.bias = source.bias;
  33193. this.radius = source.radius;
  33194. this.autoUpdate = source.autoUpdate;
  33195. this.needsUpdate = source.needsUpdate;
  33196. this.normalBias = source.normalBias;
  33197. this.blurSamples = source.blurSamples;
  33198. this.mapSize.copy( source.mapSize );
  33199. this.biasNode = source.biasNode;
  33200. return this;
  33201. }
  33202. /**
  33203. * Returns a new light shadow instance with copied values from this instance.
  33204. *
  33205. * @return {LightShadow} A clone of this instance.
  33206. */
  33207. clone() {
  33208. return new this.constructor().copy( this );
  33209. }
  33210. /**
  33211. * Serializes the light shadow into JSON.
  33212. *
  33213. * @return {Object} A JSON object representing the serialized light shadow.
  33214. * @see {@link ObjectLoader#parse}
  33215. */
  33216. toJSON() {
  33217. const object = {};
  33218. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33219. if ( this.bias !== 0 ) object.bias = this.bias;
  33220. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33221. if ( this.radius !== 1 ) object.radius = this.radius;
  33222. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33223. object.camera = this.camera.toJSON( false ).object;
  33224. delete object.camera.matrix;
  33225. return object;
  33226. }
  33227. }
  33228. const _position$2 = /*@__PURE__*/ new Vector3();
  33229. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33230. const _scale$2 = /*@__PURE__*/ new Vector3();
  33231. /**
  33232. * Abstract base class for cameras. This class should always be inherited
  33233. * when you build a new camera.
  33234. *
  33235. * @abstract
  33236. * @augments Object3D
  33237. */
  33238. class Camera extends Object3D {
  33239. /**
  33240. * Constructs a new camera.
  33241. */
  33242. constructor() {
  33243. super();
  33244. /**
  33245. * This flag can be used for type testing.
  33246. *
  33247. * @type {boolean}
  33248. * @readonly
  33249. * @default true
  33250. */
  33251. this.isCamera = true;
  33252. this.type = 'Camera';
  33253. /**
  33254. * The inverse of the camera's world matrix.
  33255. *
  33256. * @type {Matrix4}
  33257. */
  33258. this.matrixWorldInverse = new Matrix4();
  33259. /**
  33260. * The camera's projection matrix.
  33261. *
  33262. * @type {Matrix4}
  33263. */
  33264. this.projectionMatrix = new Matrix4();
  33265. /**
  33266. * The inverse of the camera's projection matrix.
  33267. *
  33268. * @type {Matrix4}
  33269. */
  33270. this.projectionMatrixInverse = new Matrix4();
  33271. /**
  33272. * The coordinate system in which the camera is used.
  33273. *
  33274. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33275. */
  33276. this.coordinateSystem = WebGLCoordinateSystem;
  33277. this._reversedDepth = false;
  33278. }
  33279. /**
  33280. * The flag that indicates whether the camera uses a reversed depth buffer.
  33281. *
  33282. * @type {boolean}
  33283. * @default false
  33284. */
  33285. get reversedDepth() {
  33286. return this._reversedDepth;
  33287. }
  33288. copy( source, recursive ) {
  33289. super.copy( source, recursive );
  33290. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33291. this.projectionMatrix.copy( source.projectionMatrix );
  33292. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33293. this.coordinateSystem = source.coordinateSystem;
  33294. return this;
  33295. }
  33296. /**
  33297. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33298. *
  33299. * This method is overwritten since cameras have a different forward vector compared to other
  33300. * 3D objects. A camera looks down its local, negative z-axis by default.
  33301. *
  33302. * @param {Vector3} target - The target vector the result is stored to.
  33303. * @return {Vector3} The 3D object's direction in world space.
  33304. */
  33305. getWorldDirection( target ) {
  33306. return super.getWorldDirection( target ).negate();
  33307. }
  33308. updateMatrixWorld( force ) {
  33309. super.updateMatrixWorld( force );
  33310. // exclude scale from view matrix to be glTF conform
  33311. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33312. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33313. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33314. } else {
  33315. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33316. }
  33317. }
  33318. updateWorldMatrix( updateParents, updateChildren ) {
  33319. super.updateWorldMatrix( updateParents, updateChildren );
  33320. // exclude scale from view matrix to be glTF conform
  33321. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33322. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33323. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33324. } else {
  33325. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33326. }
  33327. }
  33328. clone() {
  33329. return new this.constructor().copy( this );
  33330. }
  33331. }
  33332. const _v3$1 = /*@__PURE__*/ new Vector3();
  33333. const _minTarget = /*@__PURE__*/ new Vector2();
  33334. const _maxTarget = /*@__PURE__*/ new Vector2();
  33335. /**
  33336. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33337. *
  33338. * This projection mode is designed to mimic the way the human eye sees. It
  33339. * is the most common projection mode used for rendering a 3D scene.
  33340. *
  33341. * ```js
  33342. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33343. * scene.add( camera );
  33344. * ```
  33345. *
  33346. * @augments Camera
  33347. */
  33348. class PerspectiveCamera extends Camera {
  33349. /**
  33350. * Constructs a new perspective camera.
  33351. *
  33352. * @param {number} [fov=50] - The vertical field of view.
  33353. * @param {number} [aspect=1] - The aspect ratio.
  33354. * @param {number} [near=0.1] - The camera's near plane.
  33355. * @param {number} [far=2000] - The camera's far plane.
  33356. */
  33357. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33358. super();
  33359. /**
  33360. * This flag can be used for type testing.
  33361. *
  33362. * @type {boolean}
  33363. * @readonly
  33364. * @default true
  33365. */
  33366. this.isPerspectiveCamera = true;
  33367. this.type = 'PerspectiveCamera';
  33368. /**
  33369. * The vertical field of view, from bottom to top of view,
  33370. * in degrees.
  33371. *
  33372. * @type {number}
  33373. * @default 50
  33374. */
  33375. this.fov = fov;
  33376. /**
  33377. * The zoom factor of the camera.
  33378. *
  33379. * @type {number}
  33380. * @default 1
  33381. */
  33382. this.zoom = 1;
  33383. /**
  33384. * The camera's near plane. The valid range is greater than `0`
  33385. * and less than the current value of {@link PerspectiveCamera#far}.
  33386. *
  33387. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  33388. * valid value for a perspective camera's near plane.
  33389. *
  33390. * @type {number}
  33391. * @default 0.1
  33392. */
  33393. this.near = near;
  33394. /**
  33395. * The camera's far plane. Must be greater than the
  33396. * current value of {@link PerspectiveCamera#near}.
  33397. *
  33398. * @type {number}
  33399. * @default 2000
  33400. */
  33401. this.far = far;
  33402. /**
  33403. * Object distance used for stereoscopy and depth-of-field effects. This
  33404. * parameter does not influence the projection matrix unless a
  33405. * {@link StereoCamera} is being used.
  33406. *
  33407. * @type {number}
  33408. * @default 10
  33409. */
  33410. this.focus = 10;
  33411. /**
  33412. * The aspect ratio, usually the canvas width / canvas height.
  33413. *
  33414. * @type {number}
  33415. * @default 1
  33416. */
  33417. this.aspect = aspect;
  33418. /**
  33419. * Represents the frustum window specification. This property should not be edited
  33420. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33421. *
  33422. * @type {?Object}
  33423. * @default null
  33424. */
  33425. this.view = null;
  33426. /**
  33427. * Film size used for the larger axis. Default is `35` (millimeters). This
  33428. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  33429. * is set to a nonzero value.
  33430. *
  33431. * @type {number}
  33432. * @default 35
  33433. */
  33434. this.filmGauge = 35;
  33435. /**
  33436. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  33437. *
  33438. * @type {number}
  33439. * @default 0
  33440. */
  33441. this.filmOffset = 0;
  33442. this.updateProjectionMatrix();
  33443. }
  33444. copy( source, recursive ) {
  33445. super.copy( source, recursive );
  33446. this.fov = source.fov;
  33447. this.zoom = source.zoom;
  33448. this.near = source.near;
  33449. this.far = source.far;
  33450. this.focus = source.focus;
  33451. this.aspect = source.aspect;
  33452. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33453. this.filmGauge = source.filmGauge;
  33454. this.filmOffset = source.filmOffset;
  33455. return this;
  33456. }
  33457. /**
  33458. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  33459. *
  33460. * The default film gauge is 35, so that the focal length can be specified for
  33461. * a 35mm (full frame) camera.
  33462. *
  33463. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  33464. */
  33465. setFocalLength( focalLength ) {
  33466. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  33467. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  33468. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  33469. this.updateProjectionMatrix();
  33470. }
  33471. /**
  33472. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  33473. * {@link PerspectiveCamera#filmGauge}.
  33474. *
  33475. * @return {number} The computed focal length.
  33476. */
  33477. getFocalLength() {
  33478. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  33479. return 0.5 * this.getFilmHeight() / vExtentSlope;
  33480. }
  33481. /**
  33482. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  33483. *
  33484. * @return {number} The effective FOV.
  33485. */
  33486. getEffectiveFOV() {
  33487. return RAD2DEG * 2 * Math.atan(
  33488. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  33489. }
  33490. /**
  33491. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33492. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33493. *
  33494. * @return {number} The film width.
  33495. */
  33496. getFilmWidth() {
  33497. // film not completely covered in portrait format (aspect < 1)
  33498. return this.filmGauge * Math.min( this.aspect, 1 );
  33499. }
  33500. /**
  33501. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  33502. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  33503. *
  33504. * @return {number} The film width.
  33505. */
  33506. getFilmHeight() {
  33507. // film not completely covered in landscape format (aspect > 1)
  33508. return this.filmGauge / Math.max( this.aspect, 1 );
  33509. }
  33510. /**
  33511. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  33512. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  33513. *
  33514. * @param {number} distance - The viewing distance.
  33515. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  33516. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  33517. */
  33518. getViewBounds( distance, minTarget, maxTarget ) {
  33519. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33520. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33521. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  33522. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  33523. }
  33524. /**
  33525. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  33526. *
  33527. * @param {number} distance - The viewing distance.
  33528. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  33529. * @returns {Vector2} The view size.
  33530. */
  33531. getViewSize( distance, target ) {
  33532. this.getViewBounds( distance, _minTarget, _maxTarget );
  33533. return target.subVectors( _maxTarget, _minTarget );
  33534. }
  33535. /**
  33536. * Sets an offset in a larger frustum. This is useful for multi-window or
  33537. * multi-monitor/multi-machine setups.
  33538. *
  33539. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  33540. * the monitors are in grid like this
  33541. *```
  33542. * +---+---+---+
  33543. * | A | B | C |
  33544. * +---+---+---+
  33545. * | D | E | F |
  33546. * +---+---+---+
  33547. *```
  33548. * then for each monitor you would call it like this:
  33549. *```js
  33550. * const w = 1920;
  33551. * const h = 1080;
  33552. * const fullWidth = w * 3;
  33553. * const fullHeight = h * 2;
  33554. *
  33555. * // --A--
  33556. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  33557. * // --B--
  33558. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  33559. * // --C--
  33560. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  33561. * // --D--
  33562. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  33563. * // --E--
  33564. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  33565. * // --F--
  33566. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  33567. * ```
  33568. *
  33569. * Note there is no reason monitors have to be the same size or in a grid.
  33570. *
  33571. * @param {number} fullWidth - The full width of multiview setup.
  33572. * @param {number} fullHeight - The full height of multiview setup.
  33573. * @param {number} x - The horizontal offset of the subcamera.
  33574. * @param {number} y - The vertical offset of the subcamera.
  33575. * @param {number} width - The width of subcamera.
  33576. * @param {number} height - The height of subcamera.
  33577. */
  33578. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33579. this.aspect = fullWidth / fullHeight;
  33580. if ( this.view === null ) {
  33581. this.view = {
  33582. enabled: true,
  33583. fullWidth: 1,
  33584. fullHeight: 1,
  33585. offsetX: 0,
  33586. offsetY: 0,
  33587. width: 1,
  33588. height: 1
  33589. };
  33590. }
  33591. this.view.enabled = true;
  33592. this.view.fullWidth = fullWidth;
  33593. this.view.fullHeight = fullHeight;
  33594. this.view.offsetX = x;
  33595. this.view.offsetY = y;
  33596. this.view.width = width;
  33597. this.view.height = height;
  33598. this.updateProjectionMatrix();
  33599. }
  33600. /**
  33601. * Removes the view offset from the projection matrix.
  33602. */
  33603. clearViewOffset() {
  33604. if ( this.view !== null ) {
  33605. this.view.enabled = false;
  33606. }
  33607. this.updateProjectionMatrix();
  33608. }
  33609. /**
  33610. * Updates the camera's projection matrix. Must be called after any change of
  33611. * camera properties.
  33612. */
  33613. updateProjectionMatrix() {
  33614. const near = this.near;
  33615. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  33616. let height = 2 * top;
  33617. let width = this.aspect * height;
  33618. let left = -0.5 * width;
  33619. const view = this.view;
  33620. if ( this.view !== null && this.view.enabled ) {
  33621. const fullWidth = view.fullWidth,
  33622. fullHeight = view.fullHeight;
  33623. left += view.offsetX * width / fullWidth;
  33624. top -= view.offsetY * height / fullHeight;
  33625. width *= view.width / fullWidth;
  33626. height *= view.height / fullHeight;
  33627. }
  33628. const skew = this.filmOffset;
  33629. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  33630. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  33631. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33632. }
  33633. toJSON( meta ) {
  33634. const data = super.toJSON( meta );
  33635. data.object.fov = this.fov;
  33636. data.object.zoom = this.zoom;
  33637. data.object.near = this.near;
  33638. data.object.far = this.far;
  33639. data.object.focus = this.focus;
  33640. data.object.aspect = this.aspect;
  33641. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33642. data.object.filmGauge = this.filmGauge;
  33643. data.object.filmOffset = this.filmOffset;
  33644. return data;
  33645. }
  33646. }
  33647. /**
  33648. * Represents the shadow configuration of directional lights.
  33649. *
  33650. * @augments LightShadow
  33651. */
  33652. class SpotLightShadow extends LightShadow {
  33653. /**
  33654. * Constructs a new spot light shadow.
  33655. */
  33656. constructor() {
  33657. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33658. /**
  33659. * This flag can be used for type testing.
  33660. *
  33661. * @type {boolean}
  33662. * @readonly
  33663. * @default true
  33664. */
  33665. this.isSpotLightShadow = true;
  33666. /**
  33667. * Used to focus the shadow camera. The camera's field of view is set as a
  33668. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33669. *
  33670. * @type {number}
  33671. * @default 1
  33672. */
  33673. this.focus = 1;
  33674. /**
  33675. * Texture aspect ratio.
  33676. *
  33677. * @type {number}
  33678. * @default 1
  33679. */
  33680. this.aspect = 1;
  33681. }
  33682. updateMatrices( light ) {
  33683. const camera = this.camera;
  33684. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33685. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33686. const far = light.distance || camera.far;
  33687. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33688. camera.fov = fov;
  33689. camera.aspect = aspect;
  33690. camera.far = far;
  33691. camera.updateProjectionMatrix();
  33692. }
  33693. super.updateMatrices( light );
  33694. }
  33695. copy( source ) {
  33696. super.copy( source );
  33697. this.focus = source.focus;
  33698. return this;
  33699. }
  33700. }
  33701. /**
  33702. * This light gets emitted from a single point in one direction, along a cone
  33703. * that increases in size the further from the light it gets.
  33704. *
  33705. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33706. *
  33707. * ```js
  33708. * // white spotlight shining from the side, modulated by a texture
  33709. * const spotLight = new THREE.SpotLight( 0xffffff );
  33710. * spotLight.position.set( 100, 1000, 100 );
  33711. * spotLight.map = new THREE.TextureLoader().load( url );
  33712. *
  33713. * spotLight.castShadow = true;
  33714. * spotLight.shadow.mapSize.width = 1024;
  33715. * spotLight.shadow.mapSize.height = 1024;
  33716. * spotLight.shadow.camera.near = 500;
  33717. * spotLight.shadow.camera.far = 4000;
  33718. * spotLight.shadow.camera.fov = 30;s
  33719. * ```
  33720. *
  33721. * @augments Light
  33722. */
  33723. class SpotLight extends Light {
  33724. /**
  33725. * Constructs a new spot light.
  33726. *
  33727. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33728. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33729. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33730. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33731. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33732. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33733. */
  33734. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33735. super( color, intensity );
  33736. /**
  33737. * This flag can be used for type testing.
  33738. *
  33739. * @type {boolean}
  33740. * @readonly
  33741. * @default true
  33742. */
  33743. this.isSpotLight = true;
  33744. this.type = 'SpotLight';
  33745. this.position.copy( Object3D.DEFAULT_UP );
  33746. this.updateMatrix();
  33747. /**
  33748. * The spot light points from its position to the
  33749. * target's position.
  33750. *
  33751. * For the target's position to be changed to anything other
  33752. * than the default, it must be added to the scene.
  33753. *
  33754. * It is also possible to set the target to be another 3D object
  33755. * in the scene. The light will now track the target object.
  33756. *
  33757. * @type {Object3D}
  33758. */
  33759. this.target = new Object3D();
  33760. /**
  33761. * Maximum range of the light. `0` means no limit.
  33762. *
  33763. * @type {number}
  33764. * @default 0
  33765. */
  33766. this.distance = distance;
  33767. /**
  33768. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33769. *
  33770. * @type {number}
  33771. * @default Math.PI/3
  33772. */
  33773. this.angle = angle;
  33774. /**
  33775. * Percent of the spotlight cone that is attenuated due to penumbra.
  33776. * Value range is `[0,1]`.
  33777. *
  33778. * @type {number}
  33779. * @default 0
  33780. */
  33781. this.penumbra = penumbra;
  33782. /**
  33783. * The amount the light dims along the distance of the light. In context of
  33784. * physically-correct rendering the default value should not be changed.
  33785. *
  33786. * @type {number}
  33787. * @default 2
  33788. */
  33789. this.decay = decay;
  33790. /**
  33791. * A texture used to modulate the color of the light. The spot light
  33792. * color is mixed with the RGB value of this texture, with a ratio
  33793. * corresponding to its alpha value. The cookie-like masking effect is
  33794. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33795. *
  33796. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33797. *
  33798. * @type {?Texture}
  33799. * @default null
  33800. */
  33801. this.map = null;
  33802. /**
  33803. * This property holds the light's shadow configuration.
  33804. *
  33805. * @type {SpotLightShadow}
  33806. */
  33807. this.shadow = new SpotLightShadow();
  33808. }
  33809. /**
  33810. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33811. * Changing the power will also change the light's intensity.
  33812. *
  33813. * @type {number}
  33814. */
  33815. get power() {
  33816. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33817. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33818. return this.intensity * Math.PI;
  33819. }
  33820. set power( power ) {
  33821. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33822. this.intensity = power / Math.PI;
  33823. }
  33824. dispose() {
  33825. super.dispose();
  33826. this.shadow.dispose();
  33827. }
  33828. copy( source, recursive ) {
  33829. super.copy( source, recursive );
  33830. this.distance = source.distance;
  33831. this.angle = source.angle;
  33832. this.penumbra = source.penumbra;
  33833. this.decay = source.decay;
  33834. this.target = source.target.clone();
  33835. this.map = source.map;
  33836. this.shadow = source.shadow.clone();
  33837. return this;
  33838. }
  33839. toJSON( meta ) {
  33840. const data = super.toJSON( meta );
  33841. data.object.distance = this.distance;
  33842. data.object.angle = this.angle;
  33843. data.object.decay = this.decay;
  33844. data.object.penumbra = this.penumbra;
  33845. data.object.target = this.target.uuid;
  33846. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33847. data.object.shadow = this.shadow.toJSON();
  33848. return data;
  33849. }
  33850. }
  33851. /**
  33852. * Represents the shadow configuration of point lights.
  33853. *
  33854. * @augments LightShadow
  33855. */
  33856. class PointLightShadow extends LightShadow {
  33857. /**
  33858. * Constructs a new point light shadow.
  33859. */
  33860. constructor() {
  33861. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33862. /**
  33863. * This flag can be used for type testing.
  33864. *
  33865. * @type {boolean}
  33866. * @readonly
  33867. * @default true
  33868. */
  33869. this.isPointLightShadow = true;
  33870. }
  33871. }
  33872. /**
  33873. * A light that gets emitted from a single point in all directions. A common
  33874. * use case for this is to replicate the light emitted from a bare
  33875. * lightbulb.
  33876. *
  33877. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33878. *
  33879. * ```js
  33880. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33881. * light.position.set( 50, 50, 50 );
  33882. * scene.add( light );
  33883. * ```
  33884. *
  33885. * @augments Light
  33886. */
  33887. class PointLight extends Light {
  33888. /**
  33889. * Constructs a new point light.
  33890. *
  33891. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33892. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33893. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33894. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33895. */
  33896. constructor( color, intensity, distance = 0, decay = 2 ) {
  33897. super( color, intensity );
  33898. /**
  33899. * This flag can be used for type testing.
  33900. *
  33901. * @type {boolean}
  33902. * @readonly
  33903. * @default true
  33904. */
  33905. this.isPointLight = true;
  33906. this.type = 'PointLight';
  33907. /**
  33908. * When distance is zero, light will attenuate according to inverse-square
  33909. * law to infinite distance. When distance is non-zero, light will attenuate
  33910. * according to inverse-square law until near the distance cutoff, where it
  33911. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33912. * physically correct.
  33913. *
  33914. * @type {number}
  33915. * @default 0
  33916. */
  33917. this.distance = distance;
  33918. /**
  33919. * The amount the light dims along the distance of the light. In context of
  33920. * physically-correct rendering the default value should not be changed.
  33921. *
  33922. * @type {number}
  33923. * @default 2
  33924. */
  33925. this.decay = decay;
  33926. /**
  33927. * This property holds the light's shadow configuration.
  33928. *
  33929. * @type {PointLightShadow}
  33930. */
  33931. this.shadow = new PointLightShadow();
  33932. }
  33933. /**
  33934. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33935. * Changing the power will also change the light's intensity.
  33936. *
  33937. * @type {number}
  33938. */
  33939. get power() {
  33940. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33941. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33942. return this.intensity * 4 * Math.PI;
  33943. }
  33944. set power( power ) {
  33945. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33946. this.intensity = power / ( 4 * Math.PI );
  33947. }
  33948. dispose() {
  33949. super.dispose();
  33950. this.shadow.dispose();
  33951. }
  33952. copy( source, recursive ) {
  33953. super.copy( source, recursive );
  33954. this.distance = source.distance;
  33955. this.decay = source.decay;
  33956. this.shadow = source.shadow.clone();
  33957. return this;
  33958. }
  33959. toJSON( meta ) {
  33960. const data = super.toJSON( meta );
  33961. data.object.distance = this.distance;
  33962. data.object.decay = this.decay;
  33963. data.object.shadow = this.shadow.toJSON();
  33964. return data;
  33965. }
  33966. }
  33967. /**
  33968. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33969. *
  33970. * In this projection mode, an object's size in the rendered image stays
  33971. * constant regardless of its distance from the camera. This can be useful
  33972. * for rendering 2D scenes and UI elements, amongst other things.
  33973. *
  33974. * ```js
  33975. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33976. * scene.add( camera );
  33977. * ```
  33978. *
  33979. * @augments Camera
  33980. */
  33981. class OrthographicCamera extends Camera {
  33982. /**
  33983. * Constructs a new orthographic camera.
  33984. *
  33985. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33986. * @param {number} [right=1] - The right plane of the camera's frustum.
  33987. * @param {number} [top=1] - The top plane of the camera's frustum.
  33988. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33989. * @param {number} [near=0.1] - The camera's near plane.
  33990. * @param {number} [far=2000] - The camera's far plane.
  33991. */
  33992. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33993. super();
  33994. /**
  33995. * This flag can be used for type testing.
  33996. *
  33997. * @type {boolean}
  33998. * @readonly
  33999. * @default true
  34000. */
  34001. this.isOrthographicCamera = true;
  34002. this.type = 'OrthographicCamera';
  34003. /**
  34004. * The zoom factor of the camera.
  34005. *
  34006. * @type {number}
  34007. * @default 1
  34008. */
  34009. this.zoom = 1;
  34010. /**
  34011. * Represents the frustum window specification. This property should not be edited
  34012. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34013. *
  34014. * @type {?Object}
  34015. * @default null
  34016. */
  34017. this.view = null;
  34018. /**
  34019. * The left plane of the camera's frustum.
  34020. *
  34021. * @type {number}
  34022. * @default -1
  34023. */
  34024. this.left = left;
  34025. /**
  34026. * The right plane of the camera's frustum.
  34027. *
  34028. * @type {number}
  34029. * @default 1
  34030. */
  34031. this.right = right;
  34032. /**
  34033. * The top plane of the camera's frustum.
  34034. *
  34035. * @type {number}
  34036. * @default 1
  34037. */
  34038. this.top = top;
  34039. /**
  34040. * The bottom plane of the camera's frustum.
  34041. *
  34042. * @type {number}
  34043. * @default -1
  34044. */
  34045. this.bottom = bottom;
  34046. /**
  34047. * The camera's near plane. The valid range is greater than `0`
  34048. * and less than the current value of {@link OrthographicCamera#far}.
  34049. *
  34050. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34051. * valid value for an orthographic camera's near plane.
  34052. *
  34053. * @type {number}
  34054. * @default 0.1
  34055. */
  34056. this.near = near;
  34057. /**
  34058. * The camera's far plane. Must be greater than the
  34059. * current value of {@link OrthographicCamera#near}.
  34060. *
  34061. * @type {number}
  34062. * @default 2000
  34063. */
  34064. this.far = far;
  34065. this.updateProjectionMatrix();
  34066. }
  34067. copy( source, recursive ) {
  34068. super.copy( source, recursive );
  34069. this.left = source.left;
  34070. this.right = source.right;
  34071. this.top = source.top;
  34072. this.bottom = source.bottom;
  34073. this.near = source.near;
  34074. this.far = source.far;
  34075. this.zoom = source.zoom;
  34076. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34077. return this;
  34078. }
  34079. /**
  34080. * Sets an offset in a larger frustum. This is useful for multi-window or
  34081. * multi-monitor/multi-machine setups.
  34082. *
  34083. * @param {number} fullWidth - The full width of multiview setup.
  34084. * @param {number} fullHeight - The full height of multiview setup.
  34085. * @param {number} x - The horizontal offset of the subcamera.
  34086. * @param {number} y - The vertical offset of the subcamera.
  34087. * @param {number} width - The width of subcamera.
  34088. * @param {number} height - The height of subcamera.
  34089. * @see {@link PerspectiveCamera#setViewOffset}
  34090. */
  34091. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34092. if ( this.view === null ) {
  34093. this.view = {
  34094. enabled: true,
  34095. fullWidth: 1,
  34096. fullHeight: 1,
  34097. offsetX: 0,
  34098. offsetY: 0,
  34099. width: 1,
  34100. height: 1
  34101. };
  34102. }
  34103. this.view.enabled = true;
  34104. this.view.fullWidth = fullWidth;
  34105. this.view.fullHeight = fullHeight;
  34106. this.view.offsetX = x;
  34107. this.view.offsetY = y;
  34108. this.view.width = width;
  34109. this.view.height = height;
  34110. this.updateProjectionMatrix();
  34111. }
  34112. /**
  34113. * Removes the view offset from the projection matrix.
  34114. */
  34115. clearViewOffset() {
  34116. if ( this.view !== null ) {
  34117. this.view.enabled = false;
  34118. }
  34119. this.updateProjectionMatrix();
  34120. }
  34121. /**
  34122. * Updates the camera's projection matrix. Must be called after any change of
  34123. * camera properties.
  34124. */
  34125. updateProjectionMatrix() {
  34126. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34127. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34128. const cx = ( this.right + this.left ) / 2;
  34129. const cy = ( this.top + this.bottom ) / 2;
  34130. let left = cx - dx;
  34131. let right = cx + dx;
  34132. let top = cy + dy;
  34133. let bottom = cy - dy;
  34134. if ( this.view !== null && this.view.enabled ) {
  34135. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34136. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34137. left += scaleW * this.view.offsetX;
  34138. right = left + scaleW * this.view.width;
  34139. top -= scaleH * this.view.offsetY;
  34140. bottom = top - scaleH * this.view.height;
  34141. }
  34142. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34143. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34144. }
  34145. toJSON( meta ) {
  34146. const data = super.toJSON( meta );
  34147. data.object.zoom = this.zoom;
  34148. data.object.left = this.left;
  34149. data.object.right = this.right;
  34150. data.object.top = this.top;
  34151. data.object.bottom = this.bottom;
  34152. data.object.near = this.near;
  34153. data.object.far = this.far;
  34154. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34155. return data;
  34156. }
  34157. }
  34158. /**
  34159. * Represents the shadow configuration of directional lights.
  34160. *
  34161. * @augments LightShadow
  34162. */
  34163. class DirectionalLightShadow extends LightShadow {
  34164. /**
  34165. * Constructs a new directional light shadow.
  34166. */
  34167. constructor() {
  34168. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34169. /**
  34170. * This flag can be used for type testing.
  34171. *
  34172. * @type {boolean}
  34173. * @readonly
  34174. * @default true
  34175. */
  34176. this.isDirectionalLightShadow = true;
  34177. }
  34178. }
  34179. /**
  34180. * A light that gets emitted in a specific direction. This light will behave
  34181. * as though it is infinitely far away and the rays produced from it are all
  34182. * parallel. The common use case for this is to simulate daylight; the sun is
  34183. * far enough away that its position can be considered to be infinite, and
  34184. * all light rays coming from it are parallel.
  34185. *
  34186. * A common point of confusion for directional lights is that setting the
  34187. * rotation has no effect. This is because three.js's DirectionalLight is the
  34188. * equivalent to what is often called a 'Target Direct Light' in other
  34189. * applications.
  34190. *
  34191. * This means that its direction is calculated as pointing from the light's
  34192. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34193. * (as opposed to a 'Free Direct Light' that just has a rotation
  34194. * component).
  34195. *
  34196. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34197. *
  34198. * ```js
  34199. * // White directional light at half intensity shining from the top.
  34200. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34201. * scene.add( directionalLight );
  34202. * ```
  34203. *
  34204. * @augments Light
  34205. */
  34206. class DirectionalLight extends Light {
  34207. /**
  34208. * Constructs a new directional light.
  34209. *
  34210. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34211. * @param {number} [intensity=1] - The light's strength/intensity.
  34212. */
  34213. constructor( color, intensity ) {
  34214. super( color, intensity );
  34215. /**
  34216. * This flag can be used for type testing.
  34217. *
  34218. * @type {boolean}
  34219. * @readonly
  34220. * @default true
  34221. */
  34222. this.isDirectionalLight = true;
  34223. this.type = 'DirectionalLight';
  34224. this.position.copy( Object3D.DEFAULT_UP );
  34225. this.updateMatrix();
  34226. /**
  34227. * The directional light points from its position to the
  34228. * target's position.
  34229. *
  34230. * For the target's position to be changed to anything other
  34231. * than the default, it must be added to the scene.
  34232. *
  34233. * It is also possible to set the target to be another 3D object
  34234. * in the scene. The light will now track the target object.
  34235. *
  34236. * @type {Object3D}
  34237. */
  34238. this.target = new Object3D();
  34239. /**
  34240. * This property holds the light's shadow configuration.
  34241. *
  34242. * @type {DirectionalLightShadow}
  34243. */
  34244. this.shadow = new DirectionalLightShadow();
  34245. }
  34246. dispose() {
  34247. super.dispose();
  34248. this.shadow.dispose();
  34249. }
  34250. copy( source ) {
  34251. super.copy( source );
  34252. this.target = source.target.clone();
  34253. this.shadow = source.shadow.clone();
  34254. return this;
  34255. }
  34256. toJSON( meta ) {
  34257. const data = super.toJSON( meta );
  34258. data.object.shadow = this.shadow.toJSON();
  34259. data.object.target = this.target.uuid;
  34260. return data;
  34261. }
  34262. }
  34263. /**
  34264. * This light globally illuminates all objects in the scene equally.
  34265. *
  34266. * It cannot be used to cast shadows as it does not have a direction.
  34267. *
  34268. * ```js
  34269. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34270. * scene.add( light );
  34271. * ```
  34272. *
  34273. * @augments Light
  34274. */
  34275. class AmbientLight extends Light {
  34276. /**
  34277. * Constructs a new ambient light.
  34278. *
  34279. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34280. * @param {number} [intensity=1] - The light's strength/intensity.
  34281. */
  34282. constructor( color, intensity ) {
  34283. super( color, intensity );
  34284. /**
  34285. * This flag can be used for type testing.
  34286. *
  34287. * @type {boolean}
  34288. * @readonly
  34289. * @default true
  34290. */
  34291. this.isAmbientLight = true;
  34292. this.type = 'AmbientLight';
  34293. }
  34294. }
  34295. /**
  34296. * This class emits light uniformly across the face a rectangular plane.
  34297. * This light type can be used to simulate light sources such as bright
  34298. * windows or strip lighting.
  34299. *
  34300. * Important Notes:
  34301. *
  34302. * - There is no shadow support.
  34303. * - Only PBR materials are supported.
  34304. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34305. * into your app and init the uniforms/textures.
  34306. *
  34307. * ```js
  34308. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34309. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34310. *
  34311. * const intensity = 1; const width = 10; const height = 10;
  34312. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34313. * rectLight.position.set( 5, 5, 0 );
  34314. * rectLight.lookAt( 0, 0, 0 );
  34315. * scene.add( rectLight )
  34316. * ```
  34317. *
  34318. * @augments Light
  34319. */
  34320. class RectAreaLight extends Light {
  34321. /**
  34322. * Constructs a new area light.
  34323. *
  34324. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34325. * @param {number} [intensity=1] - The light's strength/intensity.
  34326. * @param {number} [width=10] - The width of the light.
  34327. * @param {number} [height=10] - The height of the light.
  34328. */
  34329. constructor( color, intensity, width = 10, height = 10 ) {
  34330. super( color, intensity );
  34331. /**
  34332. * This flag can be used for type testing.
  34333. *
  34334. * @type {boolean}
  34335. * @readonly
  34336. * @default true
  34337. */
  34338. this.isRectAreaLight = true;
  34339. this.type = 'RectAreaLight';
  34340. /**
  34341. * The width of the light.
  34342. *
  34343. * @type {number}
  34344. * @default 10
  34345. */
  34346. this.width = width;
  34347. /**
  34348. * The height of the light.
  34349. *
  34350. * @type {number}
  34351. * @default 10
  34352. */
  34353. this.height = height;
  34354. }
  34355. /**
  34356. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34357. * Changing the power will also change the light's intensity.
  34358. *
  34359. * @type {number}
  34360. */
  34361. get power() {
  34362. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34363. return this.intensity * this.width * this.height * Math.PI;
  34364. }
  34365. set power( power ) {
  34366. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34367. this.intensity = power / ( this.width * this.height * Math.PI );
  34368. }
  34369. copy( source ) {
  34370. super.copy( source );
  34371. this.width = source.width;
  34372. this.height = source.height;
  34373. return this;
  34374. }
  34375. toJSON( meta ) {
  34376. const data = super.toJSON( meta );
  34377. data.object.width = this.width;
  34378. data.object.height = this.height;
  34379. return data;
  34380. }
  34381. }
  34382. /**
  34383. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34384. * to encode lighting information.
  34385. *
  34386. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34387. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34388. */
  34389. class SphericalHarmonics3 {
  34390. /**
  34391. * Constructs a new spherical harmonics.
  34392. */
  34393. constructor() {
  34394. /**
  34395. * This flag can be used for type testing.
  34396. *
  34397. * @type {boolean}
  34398. * @readonly
  34399. * @default true
  34400. */
  34401. this.isSphericalHarmonics3 = true;
  34402. /**
  34403. * An array holding the (9) SH coefficients.
  34404. *
  34405. * @type {Array<Vector3>}
  34406. */
  34407. this.coefficients = [];
  34408. for ( let i = 0; i < 9; i ++ ) {
  34409. this.coefficients.push( new Vector3() );
  34410. }
  34411. }
  34412. /**
  34413. * Sets the given SH coefficients to this instance by copying
  34414. * the values.
  34415. *
  34416. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34417. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34418. */
  34419. set( coefficients ) {
  34420. for ( let i = 0; i < 9; i ++ ) {
  34421. this.coefficients[ i ].copy( coefficients[ i ] );
  34422. }
  34423. return this;
  34424. }
  34425. /**
  34426. * Sets all SH coefficients to `0`.
  34427. *
  34428. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34429. */
  34430. zero() {
  34431. for ( let i = 0; i < 9; i ++ ) {
  34432. this.coefficients[ i ].set( 0, 0, 0 );
  34433. }
  34434. return this;
  34435. }
  34436. /**
  34437. * Returns the radiance in the direction of the given normal.
  34438. *
  34439. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34440. * @param {Vector3} target - The target vector that is used to store the method's result.
  34441. * @return {Vector3} The radiance.
  34442. */
  34443. getAt( normal, target ) {
  34444. // normal is assumed to be unit length
  34445. const x = normal.x, y = normal.y, z = normal.z;
  34446. const coeff = this.coefficients;
  34447. // band 0
  34448. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34449. // band 1
  34450. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34451. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34452. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34453. // band 2
  34454. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34455. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34456. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34457. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34458. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34459. return target;
  34460. }
  34461. /**
  34462. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34463. * direction of the given normal.
  34464. *
  34465. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34466. * @param {Vector3} target - The target vector that is used to store the method's result.
  34467. * @return {Vector3} The irradiance.
  34468. */
  34469. getIrradianceAt( normal, target ) {
  34470. // normal is assumed to be unit length
  34471. const x = normal.x, y = normal.y, z = normal.z;
  34472. const coeff = this.coefficients;
  34473. // band 0
  34474. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34475. // band 1
  34476. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34477. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34478. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34479. // band 2
  34480. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34481. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34482. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34483. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34484. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34485. return target;
  34486. }
  34487. /**
  34488. * Adds the given SH to this instance.
  34489. *
  34490. * @param {SphericalHarmonics3} sh - The SH to add.
  34491. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34492. */
  34493. add( sh ) {
  34494. for ( let i = 0; i < 9; i ++ ) {
  34495. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34496. }
  34497. return this;
  34498. }
  34499. /**
  34500. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34501. * {@link SphericalHarmonics3#scale} at once.
  34502. *
  34503. * @param {SphericalHarmonics3} sh - The SH to add.
  34504. * @param {number} s - The scale factor.
  34505. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34506. */
  34507. addScaledSH( sh, s ) {
  34508. for ( let i = 0; i < 9; i ++ ) {
  34509. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34510. }
  34511. return this;
  34512. }
  34513. /**
  34514. * Scales this SH by the given scale factor.
  34515. *
  34516. * @param {number} s - The scale factor.
  34517. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34518. */
  34519. scale( s ) {
  34520. for ( let i = 0; i < 9; i ++ ) {
  34521. this.coefficients[ i ].multiplyScalar( s );
  34522. }
  34523. return this;
  34524. }
  34525. /**
  34526. * Linear interpolates between the given SH and this instance by the given
  34527. * alpha factor.
  34528. *
  34529. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34530. * @param {number} alpha - The alpha factor.
  34531. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34532. */
  34533. lerp( sh, alpha ) {
  34534. for ( let i = 0; i < 9; i ++ ) {
  34535. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34536. }
  34537. return this;
  34538. }
  34539. /**
  34540. * Returns `true` if this spherical harmonics is equal with the given one.
  34541. *
  34542. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34543. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34544. */
  34545. equals( sh ) {
  34546. for ( let i = 0; i < 9; i ++ ) {
  34547. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34548. return false;
  34549. }
  34550. }
  34551. return true;
  34552. }
  34553. /**
  34554. * Copies the values of the given spherical harmonics to this instance.
  34555. *
  34556. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34557. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34558. */
  34559. copy( sh ) {
  34560. return this.set( sh.coefficients );
  34561. }
  34562. /**
  34563. * Returns a new spherical harmonics with copied values from this instance.
  34564. *
  34565. * @return {SphericalHarmonics3} A clone of this instance.
  34566. */
  34567. clone() {
  34568. return new this.constructor().copy( this );
  34569. }
  34570. /**
  34571. * Sets the SH coefficients of this instance from the given array.
  34572. *
  34573. * @param {Array<number>} array - An array holding the SH coefficients.
  34574. * @param {number} [offset=0] - The array offset where to start copying.
  34575. * @return {SphericalHarmonics3} A clone of this instance.
  34576. */
  34577. fromArray( array, offset = 0 ) {
  34578. const coefficients = this.coefficients;
  34579. for ( let i = 0; i < 9; i ++ ) {
  34580. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34581. }
  34582. return this;
  34583. }
  34584. /**
  34585. * Returns an array with the SH coefficients, or copies them into the provided
  34586. * array. The coefficients are represented as numbers.
  34587. *
  34588. * @param {Array<number>} [array=[]] - The target array.
  34589. * @param {number} [offset=0] - The array offset where to start copying.
  34590. * @return {Array<number>} An array with flat SH coefficients.
  34591. */
  34592. toArray( array = [], offset = 0 ) {
  34593. const coefficients = this.coefficients;
  34594. for ( let i = 0; i < 9; i ++ ) {
  34595. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34596. }
  34597. return array;
  34598. }
  34599. /**
  34600. * Computes the SH basis for the given normal vector.
  34601. *
  34602. * @param {Vector3} normal - The normal.
  34603. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34604. */
  34605. static getBasisAt( normal, shBasis ) {
  34606. // normal is assumed to be unit length
  34607. const x = normal.x, y = normal.y, z = normal.z;
  34608. // band 0
  34609. shBasis[ 0 ] = 0.282095;
  34610. // band 1
  34611. shBasis[ 1 ] = 0.488603 * y;
  34612. shBasis[ 2 ] = 0.488603 * z;
  34613. shBasis[ 3 ] = 0.488603 * x;
  34614. // band 2
  34615. shBasis[ 4 ] = 1.092548 * x * y;
  34616. shBasis[ 5 ] = 1.092548 * y * z;
  34617. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34618. shBasis[ 7 ] = 1.092548 * x * z;
  34619. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34620. }
  34621. }
  34622. /**
  34623. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34624. * classical light sources (e.g. directional, point or spot lights), light
  34625. * probes do not emit light. Instead they store information about light
  34626. * passing through 3D space. During rendering, the light that hits a 3D
  34627. * object is approximated by using the data from the light probe.
  34628. *
  34629. * Light probes are usually created from (radiance) environment maps. The
  34630. * class {@link LightProbeGenerator} can be used to create light probes from
  34631. * cube textures or render targets. However, light estimation data could also
  34632. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34633. * augmented reality content that reacts to real world lighting.
  34634. *
  34635. * The current probe implementation in three.js supports so-called diffuse
  34636. * light probes. This type of light probe is functionally equivalent to an
  34637. * irradiance environment map.
  34638. *
  34639. * @augments Light
  34640. */
  34641. class LightProbe extends Light {
  34642. /**
  34643. * Constructs a new light probe.
  34644. *
  34645. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34646. * @param {number} [intensity=1] - The light's strength/intensity.
  34647. */
  34648. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34649. super( undefined, intensity );
  34650. /**
  34651. * This flag can be used for type testing.
  34652. *
  34653. * @type {boolean}
  34654. * @readonly
  34655. * @default true
  34656. */
  34657. this.isLightProbe = true;
  34658. /**
  34659. * A light probe uses spherical harmonics to encode lighting information.
  34660. *
  34661. * @type {SphericalHarmonics3}
  34662. */
  34663. this.sh = sh;
  34664. }
  34665. copy( source ) {
  34666. super.copy( source );
  34667. this.sh.copy( source.sh );
  34668. return this;
  34669. }
  34670. toJSON( meta ) {
  34671. const data = super.toJSON( meta );
  34672. data.object.sh = this.sh.toArray();
  34673. return data;
  34674. }
  34675. }
  34676. /**
  34677. * Class for loading materials. The files are internally
  34678. * loaded via {@link FileLoader}.
  34679. *
  34680. * ```js
  34681. * const loader = new THREE.MaterialLoader();
  34682. * const material = await loader.loadAsync( 'material.json' );
  34683. * ```
  34684. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34685. *
  34686. * @augments Loader
  34687. */
  34688. class MaterialLoader extends Loader {
  34689. /**
  34690. * Constructs a new material loader.
  34691. *
  34692. * @param {LoadingManager} [manager] - The loading manager.
  34693. */
  34694. constructor( manager ) {
  34695. super( manager );
  34696. /**
  34697. * A dictionary holding textures used by the material.
  34698. *
  34699. * @type {Object<string,Texture>}
  34700. */
  34701. this.textures = {};
  34702. }
  34703. /**
  34704. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34705. *
  34706. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34707. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34708. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34709. * @param {onErrorCallback} onError - Executed when errors occur.
  34710. */
  34711. load( url, onLoad, onProgress, onError ) {
  34712. const scope = this;
  34713. const loader = new FileLoader( scope.manager );
  34714. loader.setPath( scope.path );
  34715. loader.setRequestHeader( scope.requestHeader );
  34716. loader.setWithCredentials( scope.withCredentials );
  34717. loader.load( url, function ( text ) {
  34718. try {
  34719. onLoad( scope.parse( JSON.parse( text ) ) );
  34720. } catch ( e ) {
  34721. if ( onError ) {
  34722. onError( e );
  34723. } else {
  34724. error( e );
  34725. }
  34726. scope.manager.itemError( url );
  34727. }
  34728. }, onProgress, onError );
  34729. }
  34730. /**
  34731. * Parses the given JSON object and returns a material.
  34732. *
  34733. * @param {Object} json - The serialized material.
  34734. * @return {Material} The parsed material.
  34735. */
  34736. parse( json ) {
  34737. const textures = this.textures;
  34738. function getTexture( name ) {
  34739. if ( textures[ name ] === undefined ) {
  34740. warn( 'MaterialLoader: Undefined texture', name );
  34741. }
  34742. return textures[ name ];
  34743. }
  34744. const material = this.createMaterialFromType( json.type );
  34745. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34746. if ( json.name !== undefined ) material.name = json.name;
  34747. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34748. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34749. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34750. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34751. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34752. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34753. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34754. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34755. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34756. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34757. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34758. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34759. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34760. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34761. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34762. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34763. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34764. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34765. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34766. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34767. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34768. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34769. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34770. if ( json.fog !== undefined ) material.fog = json.fog;
  34771. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34772. if ( json.blending !== undefined ) material.blending = json.blending;
  34773. if ( json.combine !== undefined ) material.combine = json.combine;
  34774. if ( json.side !== undefined ) material.side = json.side;
  34775. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34776. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34777. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34778. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34779. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34780. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34781. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34782. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34783. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34784. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34785. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34786. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34787. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34788. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34789. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34790. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34791. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34792. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34793. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34794. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34795. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34796. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34797. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34798. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34799. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34800. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34801. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34802. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34803. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34804. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34805. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34806. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34807. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34808. if ( json.scale !== undefined ) material.scale = json.scale;
  34809. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34810. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34811. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34812. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34813. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34814. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34815. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34816. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34817. if ( json.visible !== undefined ) material.visible = json.visible;
  34818. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34819. if ( json.userData !== undefined ) material.userData = json.userData;
  34820. if ( json.vertexColors !== undefined ) {
  34821. if ( typeof json.vertexColors === 'number' ) {
  34822. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34823. } else {
  34824. material.vertexColors = json.vertexColors;
  34825. }
  34826. }
  34827. // Shader Material
  34828. if ( json.uniforms !== undefined ) {
  34829. for ( const name in json.uniforms ) {
  34830. const uniform = json.uniforms[ name ];
  34831. material.uniforms[ name ] = {};
  34832. switch ( uniform.type ) {
  34833. case 't':
  34834. material.uniforms[ name ].value = getTexture( uniform.value );
  34835. break;
  34836. case 'c':
  34837. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34838. break;
  34839. case 'v2':
  34840. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34841. break;
  34842. case 'v3':
  34843. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34844. break;
  34845. case 'v4':
  34846. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34847. break;
  34848. case 'm3':
  34849. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34850. break;
  34851. case 'm4':
  34852. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34853. break;
  34854. default:
  34855. material.uniforms[ name ].value = uniform.value;
  34856. }
  34857. }
  34858. }
  34859. if ( json.defines !== undefined ) material.defines = json.defines;
  34860. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34861. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34862. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34863. if ( json.extensions !== undefined ) {
  34864. for ( const key in json.extensions ) {
  34865. material.extensions[ key ] = json.extensions[ key ];
  34866. }
  34867. }
  34868. if ( json.lights !== undefined ) material.lights = json.lights;
  34869. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34870. // for PointsMaterial
  34871. if ( json.size !== undefined ) material.size = json.size;
  34872. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34873. // maps
  34874. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34875. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34876. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34877. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34878. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34879. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34880. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34881. if ( json.normalScale !== undefined ) {
  34882. let normalScale = json.normalScale;
  34883. if ( Array.isArray( normalScale ) === false ) {
  34884. // Blender exporter used to export a scalar. See #7459
  34885. normalScale = [ normalScale, normalScale ];
  34886. }
  34887. material.normalScale = new Vector2().fromArray( normalScale );
  34888. }
  34889. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34890. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34891. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34892. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34893. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34894. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34895. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34896. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34897. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34898. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34899. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34900. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34901. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34902. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34903. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34904. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34905. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34906. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34907. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34908. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34909. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34910. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34911. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34912. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34913. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34914. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34915. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34916. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34917. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34918. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34919. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34920. return material;
  34921. }
  34922. /**
  34923. * Textures are not embedded in the material JSON so they have
  34924. * to be injected before the loading process starts.
  34925. *
  34926. * @param {Object} value - A dictionary holding textures for material properties.
  34927. * @return {MaterialLoader} A reference to this material loader.
  34928. */
  34929. setTextures( value ) {
  34930. this.textures = value;
  34931. return this;
  34932. }
  34933. /**
  34934. * Creates a material for the given type.
  34935. *
  34936. * @param {string} type - The material type.
  34937. * @return {Material} The new material.
  34938. */
  34939. createMaterialFromType( type ) {
  34940. return MaterialLoader.createMaterialFromType( type );
  34941. }
  34942. /**
  34943. * Creates a material for the given type.
  34944. *
  34945. * @static
  34946. * @param {string} type - The material type.
  34947. * @return {Material} The new material.
  34948. */
  34949. static createMaterialFromType( type ) {
  34950. const materialLib = {
  34951. ShadowMaterial,
  34952. SpriteMaterial,
  34953. RawShaderMaterial,
  34954. ShaderMaterial,
  34955. PointsMaterial,
  34956. MeshPhysicalMaterial,
  34957. MeshStandardMaterial,
  34958. MeshPhongMaterial,
  34959. MeshToonMaterial,
  34960. MeshNormalMaterial,
  34961. MeshLambertMaterial,
  34962. MeshDepthMaterial,
  34963. MeshDistanceMaterial,
  34964. MeshBasicMaterial,
  34965. MeshMatcapMaterial,
  34966. LineDashedMaterial,
  34967. LineBasicMaterial,
  34968. Material
  34969. };
  34970. return new materialLib[ type ]();
  34971. }
  34972. }
  34973. /**
  34974. * A class with loader utility functions.
  34975. */
  34976. class LoaderUtils {
  34977. /**
  34978. * Extracts the base URL from the given URL.
  34979. *
  34980. * @param {string} url -The URL to extract the base URL from.
  34981. * @return {string} The extracted base URL.
  34982. */
  34983. static extractUrlBase( url ) {
  34984. const index = url.lastIndexOf( '/' );
  34985. if ( index === -1 ) return './';
  34986. return url.slice( 0, index + 1 );
  34987. }
  34988. /**
  34989. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34990. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34991. * string.
  34992. *
  34993. * @param {string} url -The URL to resolve.
  34994. * @param {string} path - The base path for relative URLs to be resolved against.
  34995. * @return {string} The resolved URL.
  34996. */
  34997. static resolveURL( url, path ) {
  34998. // Invalid URL
  34999. if ( typeof url !== 'string' || url === '' ) return '';
  35000. // Host Relative URL
  35001. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35002. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35003. }
  35004. // Absolute URL http://,https://,//
  35005. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35006. // Data URI
  35007. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35008. // Blob URL
  35009. if ( /^blob:.*$/i.test( url ) ) return url;
  35010. // Relative URL
  35011. return path + url;
  35012. }
  35013. }
  35014. /**
  35015. * An instanced version of a geometry.
  35016. */
  35017. class InstancedBufferGeometry extends BufferGeometry {
  35018. /**
  35019. * Constructs a new instanced buffer geometry.
  35020. */
  35021. constructor() {
  35022. super();
  35023. /**
  35024. * This flag can be used for type testing.
  35025. *
  35026. * @type {boolean}
  35027. * @readonly
  35028. * @default true
  35029. */
  35030. this.isInstancedBufferGeometry = true;
  35031. this.type = 'InstancedBufferGeometry';
  35032. /**
  35033. * The instance count.
  35034. *
  35035. * @type {number}
  35036. * @default Infinity
  35037. */
  35038. this.instanceCount = Infinity;
  35039. }
  35040. copy( source ) {
  35041. super.copy( source );
  35042. this.instanceCount = source.instanceCount;
  35043. return this;
  35044. }
  35045. toJSON() {
  35046. const data = super.toJSON();
  35047. data.instanceCount = this.instanceCount;
  35048. data.isInstancedBufferGeometry = true;
  35049. return data;
  35050. }
  35051. }
  35052. /**
  35053. * Class for loading geometries. The files are internally
  35054. * loaded via {@link FileLoader}.
  35055. *
  35056. * ```js
  35057. * const loader = new THREE.BufferGeometryLoader();
  35058. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35059. *
  35060. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35061. * const object = new THREE.Mesh( geometry, material );
  35062. * scene.add( object );
  35063. * ```
  35064. *
  35065. * @augments Loader
  35066. */
  35067. class BufferGeometryLoader extends Loader {
  35068. /**
  35069. * Constructs a new geometry loader.
  35070. *
  35071. * @param {LoadingManager} [manager] - The loading manager.
  35072. */
  35073. constructor( manager ) {
  35074. super( manager );
  35075. }
  35076. /**
  35077. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35078. *
  35079. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35080. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35081. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35082. * @param {onErrorCallback} onError - Executed when errors occur.
  35083. */
  35084. load( url, onLoad, onProgress, onError ) {
  35085. const scope = this;
  35086. const loader = new FileLoader( scope.manager );
  35087. loader.setPath( scope.path );
  35088. loader.setRequestHeader( scope.requestHeader );
  35089. loader.setWithCredentials( scope.withCredentials );
  35090. loader.load( url, function ( text ) {
  35091. try {
  35092. onLoad( scope.parse( JSON.parse( text ) ) );
  35093. } catch ( e ) {
  35094. if ( onError ) {
  35095. onError( e );
  35096. } else {
  35097. error( e );
  35098. }
  35099. scope.manager.itemError( url );
  35100. }
  35101. }, onProgress, onError );
  35102. }
  35103. /**
  35104. * Parses the given JSON object and returns a geometry.
  35105. *
  35106. * @param {Object} json - The serialized geometry.
  35107. * @return {BufferGeometry} The parsed geometry.
  35108. */
  35109. parse( json ) {
  35110. const interleavedBufferMap = {};
  35111. const arrayBufferMap = {};
  35112. function getInterleavedBuffer( json, uuid ) {
  35113. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35114. const interleavedBuffers = json.interleavedBuffers;
  35115. const interleavedBuffer = interleavedBuffers[ uuid ];
  35116. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35117. const array = getTypedArray( interleavedBuffer.type, buffer );
  35118. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35119. ib.uuid = interleavedBuffer.uuid;
  35120. interleavedBufferMap[ uuid ] = ib;
  35121. return ib;
  35122. }
  35123. function getArrayBuffer( json, uuid ) {
  35124. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35125. const arrayBuffers = json.arrayBuffers;
  35126. const arrayBuffer = arrayBuffers[ uuid ];
  35127. const ab = new Uint32Array( arrayBuffer ).buffer;
  35128. arrayBufferMap[ uuid ] = ab;
  35129. return ab;
  35130. }
  35131. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35132. const index = json.data.index;
  35133. if ( index !== undefined ) {
  35134. const typedArray = getTypedArray( index.type, index.array );
  35135. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35136. }
  35137. const attributes = json.data.attributes;
  35138. for ( const key in attributes ) {
  35139. const attribute = attributes[ key ];
  35140. let bufferAttribute;
  35141. if ( attribute.isInterleavedBufferAttribute ) {
  35142. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35143. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35144. } else {
  35145. const typedArray = getTypedArray( attribute.type, attribute.array );
  35146. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35147. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35148. }
  35149. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35150. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35151. geometry.setAttribute( key, bufferAttribute );
  35152. }
  35153. const morphAttributes = json.data.morphAttributes;
  35154. if ( morphAttributes ) {
  35155. for ( const key in morphAttributes ) {
  35156. const attributeArray = morphAttributes[ key ];
  35157. const array = [];
  35158. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35159. const attribute = attributeArray[ i ];
  35160. let bufferAttribute;
  35161. if ( attribute.isInterleavedBufferAttribute ) {
  35162. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35163. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35164. } else {
  35165. const typedArray = getTypedArray( attribute.type, attribute.array );
  35166. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35167. }
  35168. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35169. array.push( bufferAttribute );
  35170. }
  35171. geometry.morphAttributes[ key ] = array;
  35172. }
  35173. }
  35174. const morphTargetsRelative = json.data.morphTargetsRelative;
  35175. if ( morphTargetsRelative ) {
  35176. geometry.morphTargetsRelative = true;
  35177. }
  35178. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35179. if ( groups !== undefined ) {
  35180. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35181. const group = groups[ i ];
  35182. geometry.addGroup( group.start, group.count, group.materialIndex );
  35183. }
  35184. }
  35185. const boundingSphere = json.data.boundingSphere;
  35186. if ( boundingSphere !== undefined ) {
  35187. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35188. }
  35189. if ( json.name ) geometry.name = json.name;
  35190. if ( json.userData ) geometry.userData = json.userData;
  35191. return geometry;
  35192. }
  35193. }
  35194. /**
  35195. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  35196. * The files are internally loaded via {@link FileLoader}.
  35197. *
  35198. * ```js
  35199. * const loader = new THREE.ObjectLoader();
  35200. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35201. * scene.add( obj );
  35202. *
  35203. * // Alternatively, to parse a previously loaded JSON structure
  35204. * const object = await loader.parseAsync( a_json_object );
  35205. * scene.add( object );
  35206. * ```
  35207. *
  35208. * @augments Loader
  35209. */
  35210. class ObjectLoader extends Loader {
  35211. /**
  35212. * Constructs a new object loader.
  35213. *
  35214. * @param {LoadingManager} [manager] - The loading manager.
  35215. */
  35216. constructor( manager ) {
  35217. super( manager );
  35218. }
  35219. /**
  35220. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35221. *
  35222. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35223. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35224. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35225. * @param {onErrorCallback} onError - Executed when errors occur.
  35226. */
  35227. load( url, onLoad, onProgress, onError ) {
  35228. const scope = this;
  35229. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35230. this.resourcePath = this.resourcePath || path;
  35231. const loader = new FileLoader( this.manager );
  35232. loader.setPath( this.path );
  35233. loader.setRequestHeader( this.requestHeader );
  35234. loader.setWithCredentials( this.withCredentials );
  35235. loader.load( url, function ( text ) {
  35236. let json = null;
  35237. try {
  35238. json = JSON.parse( text );
  35239. } catch ( error ) {
  35240. if ( onError !== undefined ) onError( error );
  35241. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35242. return;
  35243. }
  35244. const metadata = json.metadata;
  35245. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35246. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35247. error( 'ObjectLoader: Can\'t load ' + url );
  35248. return;
  35249. }
  35250. scope.parse( json, onLoad );
  35251. }, onProgress, onError );
  35252. }
  35253. /**
  35254. * Async version of {@link ObjectLoader#load}.
  35255. *
  35256. * @async
  35257. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35258. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35259. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35260. */
  35261. async loadAsync( url, onProgress ) {
  35262. const scope = this;
  35263. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35264. this.resourcePath = this.resourcePath || path;
  35265. const loader = new FileLoader( this.manager );
  35266. loader.setPath( this.path );
  35267. loader.setRequestHeader( this.requestHeader );
  35268. loader.setWithCredentials( this.withCredentials );
  35269. const text = await loader.loadAsync( url, onProgress );
  35270. let json;
  35271. try {
  35272. json = JSON.parse( text );
  35273. } catch ( e ) {
  35274. throw new Error( 'ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35275. }
  35276. const metadata = json.metadata;
  35277. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35278. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35279. }
  35280. return await scope.parseAsync( json );
  35281. }
  35282. /**
  35283. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35284. * but can also be used directly to parse a previously loaded JSON structure.
  35285. *
  35286. * @param {Object} json - The serialized 3D object.
  35287. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35288. * @return {Object3D} The parsed 3D object.
  35289. */
  35290. parse( json, onLoad ) {
  35291. const animations = this.parseAnimations( json.animations );
  35292. const shapes = this.parseShapes( json.shapes );
  35293. const geometries = this.parseGeometries( json.geometries, shapes );
  35294. const images = this.parseImages( json.images, function () {
  35295. if ( onLoad !== undefined ) onLoad( object );
  35296. } );
  35297. const textures = this.parseTextures( json.textures, images );
  35298. const materials = this.parseMaterials( json.materials, textures );
  35299. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35300. const skeletons = this.parseSkeletons( json.skeletons, object );
  35301. this.bindSkeletons( object, skeletons );
  35302. this.bindLightTargets( object );
  35303. //
  35304. if ( onLoad !== undefined ) {
  35305. let hasImages = false;
  35306. for ( const uuid in images ) {
  35307. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35308. hasImages = true;
  35309. break;
  35310. }
  35311. }
  35312. if ( hasImages === false ) onLoad( object );
  35313. }
  35314. return object;
  35315. }
  35316. /**
  35317. * Async version of {@link ObjectLoader#parse}.
  35318. *
  35319. * @param {Object} json - The serialized 3D object.
  35320. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35321. */
  35322. async parseAsync( json ) {
  35323. const animations = this.parseAnimations( json.animations );
  35324. const shapes = this.parseShapes( json.shapes );
  35325. const geometries = this.parseGeometries( json.geometries, shapes );
  35326. const images = await this.parseImagesAsync( json.images );
  35327. const textures = this.parseTextures( json.textures, images );
  35328. const materials = this.parseMaterials( json.materials, textures );
  35329. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35330. const skeletons = this.parseSkeletons( json.skeletons, object );
  35331. this.bindSkeletons( object, skeletons );
  35332. this.bindLightTargets( object );
  35333. return object;
  35334. }
  35335. // internals
  35336. parseShapes( json ) {
  35337. const shapes = {};
  35338. if ( json !== undefined ) {
  35339. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35340. const shape = new Shape().fromJSON( json[ i ] );
  35341. shapes[ shape.uuid ] = shape;
  35342. }
  35343. }
  35344. return shapes;
  35345. }
  35346. parseSkeletons( json, object ) {
  35347. const skeletons = {};
  35348. const bones = {};
  35349. // generate bone lookup table
  35350. object.traverse( function ( child ) {
  35351. if ( child.isBone ) bones[ child.uuid ] = child;
  35352. } );
  35353. // create skeletons
  35354. if ( json !== undefined ) {
  35355. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35356. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35357. skeletons[ skeleton.uuid ] = skeleton;
  35358. }
  35359. }
  35360. return skeletons;
  35361. }
  35362. parseGeometries( json, shapes ) {
  35363. const geometries = {};
  35364. if ( json !== undefined ) {
  35365. const bufferGeometryLoader = new BufferGeometryLoader();
  35366. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35367. let geometry;
  35368. const data = json[ i ];
  35369. switch ( data.type ) {
  35370. case 'BufferGeometry':
  35371. case 'InstancedBufferGeometry':
  35372. geometry = bufferGeometryLoader.parse( data );
  35373. break;
  35374. default:
  35375. if ( data.type in Geometries ) {
  35376. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35377. } else {
  35378. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35379. }
  35380. }
  35381. geometry.uuid = data.uuid;
  35382. if ( data.name !== undefined ) geometry.name = data.name;
  35383. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35384. geometries[ data.uuid ] = geometry;
  35385. }
  35386. }
  35387. return geometries;
  35388. }
  35389. parseMaterials( json, textures ) {
  35390. const cache = {}; // MultiMaterial
  35391. const materials = {};
  35392. if ( json !== undefined ) {
  35393. const loader = new MaterialLoader();
  35394. loader.setTextures( textures );
  35395. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35396. const data = json[ i ];
  35397. if ( cache[ data.uuid ] === undefined ) {
  35398. cache[ data.uuid ] = loader.parse( data );
  35399. }
  35400. materials[ data.uuid ] = cache[ data.uuid ];
  35401. }
  35402. }
  35403. return materials;
  35404. }
  35405. parseAnimations( json ) {
  35406. const animations = {};
  35407. if ( json !== undefined ) {
  35408. for ( let i = 0; i < json.length; i ++ ) {
  35409. const data = json[ i ];
  35410. const clip = AnimationClip.parse( data );
  35411. animations[ clip.uuid ] = clip;
  35412. }
  35413. }
  35414. return animations;
  35415. }
  35416. parseImages( json, onLoad ) {
  35417. const scope = this;
  35418. const images = {};
  35419. let loader;
  35420. function loadImage( url ) {
  35421. scope.manager.itemStart( url );
  35422. return loader.load( url, function () {
  35423. scope.manager.itemEnd( url );
  35424. }, undefined, function () {
  35425. scope.manager.itemError( url );
  35426. scope.manager.itemEnd( url );
  35427. } );
  35428. }
  35429. function deserializeImage( image ) {
  35430. if ( typeof image === 'string' ) {
  35431. const url = image;
  35432. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35433. return loadImage( path );
  35434. } else {
  35435. if ( image.data ) {
  35436. return {
  35437. data: getTypedArray( image.type, image.data ),
  35438. width: image.width,
  35439. height: image.height
  35440. };
  35441. } else {
  35442. return null;
  35443. }
  35444. }
  35445. }
  35446. if ( json !== undefined && json.length > 0 ) {
  35447. const manager = new LoadingManager( onLoad );
  35448. loader = new ImageLoader( manager );
  35449. loader.setCrossOrigin( this.crossOrigin );
  35450. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35451. const image = json[ i ];
  35452. const url = image.url;
  35453. if ( Array.isArray( url ) ) {
  35454. // load array of images e.g CubeTexture
  35455. const imageArray = [];
  35456. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35457. const currentUrl = url[ j ];
  35458. const deserializedImage = deserializeImage( currentUrl );
  35459. if ( deserializedImage !== null ) {
  35460. if ( deserializedImage instanceof HTMLImageElement ) {
  35461. imageArray.push( deserializedImage );
  35462. } else {
  35463. // special case: handle array of data textures for cube textures
  35464. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35465. }
  35466. }
  35467. }
  35468. images[ image.uuid ] = new Source( imageArray );
  35469. } else {
  35470. // load single image
  35471. const deserializedImage = deserializeImage( image.url );
  35472. images[ image.uuid ] = new Source( deserializedImage );
  35473. }
  35474. }
  35475. }
  35476. return images;
  35477. }
  35478. async parseImagesAsync( json ) {
  35479. const scope = this;
  35480. const images = {};
  35481. let loader;
  35482. async function deserializeImage( image ) {
  35483. if ( typeof image === 'string' ) {
  35484. const url = image;
  35485. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35486. return await loader.loadAsync( path );
  35487. } else {
  35488. if ( image.data ) {
  35489. return {
  35490. data: getTypedArray( image.type, image.data ),
  35491. width: image.width,
  35492. height: image.height
  35493. };
  35494. } else {
  35495. return null;
  35496. }
  35497. }
  35498. }
  35499. if ( json !== undefined && json.length > 0 ) {
  35500. loader = new ImageLoader( this.manager );
  35501. loader.setCrossOrigin( this.crossOrigin );
  35502. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35503. const image = json[ i ];
  35504. const url = image.url;
  35505. if ( Array.isArray( url ) ) {
  35506. // load array of images e.g CubeTexture
  35507. const imageArray = [];
  35508. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35509. const currentUrl = url[ j ];
  35510. const deserializedImage = await deserializeImage( currentUrl );
  35511. if ( deserializedImage !== null ) {
  35512. if ( deserializedImage instanceof HTMLImageElement ) {
  35513. imageArray.push( deserializedImage );
  35514. } else {
  35515. // special case: handle array of data textures for cube textures
  35516. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35517. }
  35518. }
  35519. }
  35520. images[ image.uuid ] = new Source( imageArray );
  35521. } else {
  35522. // load single image
  35523. const deserializedImage = await deserializeImage( image.url );
  35524. images[ image.uuid ] = new Source( deserializedImage );
  35525. }
  35526. }
  35527. }
  35528. return images;
  35529. }
  35530. parseTextures( json, images ) {
  35531. function parseConstant( value, type ) {
  35532. if ( typeof value === 'number' ) return value;
  35533. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35534. return type[ value ];
  35535. }
  35536. const textures = {};
  35537. if ( json !== undefined ) {
  35538. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35539. const data = json[ i ];
  35540. if ( data.image === undefined ) {
  35541. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35542. }
  35543. if ( images[ data.image ] === undefined ) {
  35544. warn( 'ObjectLoader: Undefined image', data.image );
  35545. }
  35546. const source = images[ data.image ];
  35547. const image = source.data;
  35548. let texture;
  35549. if ( Array.isArray( image ) ) {
  35550. texture = new CubeTexture();
  35551. if ( image.length === 6 ) texture.needsUpdate = true;
  35552. } else {
  35553. if ( image && image.data ) {
  35554. texture = new DataTexture();
  35555. } else {
  35556. texture = new Texture();
  35557. }
  35558. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35559. }
  35560. texture.source = source;
  35561. texture.uuid = data.uuid;
  35562. if ( data.name !== undefined ) texture.name = data.name;
  35563. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35564. if ( data.channel !== undefined ) texture.channel = data.channel;
  35565. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35566. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35567. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35568. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35569. if ( data.wrap !== undefined ) {
  35570. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35571. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35572. }
  35573. if ( data.format !== undefined ) texture.format = data.format;
  35574. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35575. if ( data.type !== undefined ) texture.type = data.type;
  35576. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35577. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35578. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35579. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35580. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35581. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35582. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35583. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35584. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35585. if ( data.userData !== undefined ) texture.userData = data.userData;
  35586. textures[ data.uuid ] = texture;
  35587. }
  35588. }
  35589. return textures;
  35590. }
  35591. parseObject( data, geometries, materials, textures, animations ) {
  35592. let object;
  35593. function getGeometry( name ) {
  35594. if ( geometries[ name ] === undefined ) {
  35595. warn( 'ObjectLoader: Undefined geometry', name );
  35596. }
  35597. return geometries[ name ];
  35598. }
  35599. function getMaterial( name ) {
  35600. if ( name === undefined ) return undefined;
  35601. if ( Array.isArray( name ) ) {
  35602. const array = [];
  35603. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35604. const uuid = name[ i ];
  35605. if ( materials[ uuid ] === undefined ) {
  35606. warn( 'ObjectLoader: Undefined material', uuid );
  35607. }
  35608. array.push( materials[ uuid ] );
  35609. }
  35610. return array;
  35611. }
  35612. if ( materials[ name ] === undefined ) {
  35613. warn( 'ObjectLoader: Undefined material', name );
  35614. }
  35615. return materials[ name ];
  35616. }
  35617. function getTexture( uuid ) {
  35618. if ( textures[ uuid ] === undefined ) {
  35619. warn( 'ObjectLoader: Undefined texture', uuid );
  35620. }
  35621. return textures[ uuid ];
  35622. }
  35623. let geometry, material;
  35624. switch ( data.type ) {
  35625. case 'Scene':
  35626. object = new Scene();
  35627. if ( data.background !== undefined ) {
  35628. if ( Number.isInteger( data.background ) ) {
  35629. object.background = new Color( data.background );
  35630. } else {
  35631. object.background = getTexture( data.background );
  35632. }
  35633. }
  35634. if ( data.environment !== undefined ) {
  35635. object.environment = getTexture( data.environment );
  35636. }
  35637. if ( data.fog !== undefined ) {
  35638. if ( data.fog.type === 'Fog' ) {
  35639. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35640. } else if ( data.fog.type === 'FogExp2' ) {
  35641. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35642. }
  35643. if ( data.fog.name !== '' ) {
  35644. object.fog.name = data.fog.name;
  35645. }
  35646. }
  35647. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35648. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35649. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35650. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35651. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35652. break;
  35653. case 'PerspectiveCamera':
  35654. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35655. if ( data.focus !== undefined ) object.focus = data.focus;
  35656. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35657. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35658. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35659. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35660. break;
  35661. case 'OrthographicCamera':
  35662. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35663. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35664. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35665. break;
  35666. case 'AmbientLight':
  35667. object = new AmbientLight( data.color, data.intensity );
  35668. break;
  35669. case 'DirectionalLight':
  35670. object = new DirectionalLight( data.color, data.intensity );
  35671. object.target = data.target || '';
  35672. break;
  35673. case 'PointLight':
  35674. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35675. break;
  35676. case 'RectAreaLight':
  35677. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35678. break;
  35679. case 'SpotLight':
  35680. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35681. object.target = data.target || '';
  35682. break;
  35683. case 'HemisphereLight':
  35684. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35685. break;
  35686. case 'LightProbe':
  35687. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35688. object = new LightProbe( sh, data.intensity );
  35689. break;
  35690. case 'SkinnedMesh':
  35691. geometry = getGeometry( data.geometry );
  35692. material = getMaterial( data.material );
  35693. object = new SkinnedMesh( geometry, material );
  35694. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35695. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35696. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35697. break;
  35698. case 'Mesh':
  35699. geometry = getGeometry( data.geometry );
  35700. material = getMaterial( data.material );
  35701. object = new Mesh( geometry, material );
  35702. break;
  35703. case 'InstancedMesh':
  35704. geometry = getGeometry( data.geometry );
  35705. material = getMaterial( data.material );
  35706. const count = data.count;
  35707. const instanceMatrix = data.instanceMatrix;
  35708. const instanceColor = data.instanceColor;
  35709. object = new InstancedMesh( geometry, material, count );
  35710. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35711. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35712. break;
  35713. case 'BatchedMesh':
  35714. geometry = getGeometry( data.geometry );
  35715. material = getMaterial( data.material );
  35716. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35717. object.geometry = geometry;
  35718. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35719. object.sortObjects = data.sortObjects;
  35720. object._drawRanges = data.drawRanges;
  35721. object._reservedRanges = data.reservedRanges;
  35722. object._geometryInfo = data.geometryInfo.map( info => {
  35723. let box = null;
  35724. let sphere = null;
  35725. if ( info.boundingBox !== undefined ) {
  35726. box = new Box3().fromJSON( info.boundingBox );
  35727. }
  35728. if ( info.boundingSphere !== undefined ) {
  35729. sphere = new Sphere().fromJSON( info.boundingSphere );
  35730. }
  35731. return {
  35732. ...info,
  35733. boundingBox: box,
  35734. boundingSphere: sphere
  35735. };
  35736. } );
  35737. object._instanceInfo = data.instanceInfo;
  35738. object._availableInstanceIds = data._availableInstanceIds;
  35739. object._availableGeometryIds = data._availableGeometryIds;
  35740. object._nextIndexStart = data.nextIndexStart;
  35741. object._nextVertexStart = data.nextVertexStart;
  35742. object._geometryCount = data.geometryCount;
  35743. object._maxInstanceCount = data.maxInstanceCount;
  35744. object._maxVertexCount = data.maxVertexCount;
  35745. object._maxIndexCount = data.maxIndexCount;
  35746. object._geometryInitialized = data.geometryInitialized;
  35747. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35748. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35749. if ( data.colorsTexture !== undefined ) {
  35750. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35751. }
  35752. if ( data.boundingSphere !== undefined ) {
  35753. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35754. }
  35755. if ( data.boundingBox !== undefined ) {
  35756. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35757. }
  35758. break;
  35759. case 'LOD':
  35760. object = new LOD();
  35761. break;
  35762. case 'Line':
  35763. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35764. break;
  35765. case 'LineLoop':
  35766. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35767. break;
  35768. case 'LineSegments':
  35769. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35770. break;
  35771. case 'PointCloud':
  35772. case 'Points':
  35773. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35774. break;
  35775. case 'Sprite':
  35776. object = new Sprite( getMaterial( data.material ) );
  35777. break;
  35778. case 'Group':
  35779. object = new Group();
  35780. break;
  35781. case 'Bone':
  35782. object = new Bone();
  35783. break;
  35784. default:
  35785. object = new Object3D();
  35786. }
  35787. object.uuid = data.uuid;
  35788. if ( data.name !== undefined ) object.name = data.name;
  35789. if ( data.matrix !== undefined ) {
  35790. object.matrix.fromArray( data.matrix );
  35791. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35792. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35793. } else {
  35794. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35795. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35796. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35797. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35798. }
  35799. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35800. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35801. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  35802. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  35803. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35804. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35805. if ( data.shadow ) {
  35806. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35807. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35808. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35809. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35810. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35811. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35812. }
  35813. if ( data.visible !== undefined ) object.visible = data.visible;
  35814. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35815. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35816. if ( data.static !== undefined ) object.static = data.static;
  35817. if ( data.userData !== undefined ) object.userData = data.userData;
  35818. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35819. if ( data.children !== undefined ) {
  35820. const children = data.children;
  35821. for ( let i = 0; i < children.length; i ++ ) {
  35822. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35823. }
  35824. }
  35825. if ( data.animations !== undefined ) {
  35826. const objectAnimations = data.animations;
  35827. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35828. const uuid = objectAnimations[ i ];
  35829. object.animations.push( animations[ uuid ] );
  35830. }
  35831. }
  35832. if ( data.type === 'LOD' ) {
  35833. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35834. const levels = data.levels;
  35835. for ( let l = 0; l < levels.length; l ++ ) {
  35836. const level = levels[ l ];
  35837. const child = object.getObjectByProperty( 'uuid', level.object );
  35838. if ( child !== undefined ) {
  35839. object.addLevel( child, level.distance, level.hysteresis );
  35840. }
  35841. }
  35842. }
  35843. return object;
  35844. }
  35845. bindSkeletons( object, skeletons ) {
  35846. if ( Object.keys( skeletons ).length === 0 ) return;
  35847. object.traverse( function ( child ) {
  35848. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35849. const skeleton = skeletons[ child.skeleton ];
  35850. if ( skeleton === undefined ) {
  35851. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35852. } else {
  35853. child.bind( skeleton, child.bindMatrix );
  35854. }
  35855. }
  35856. } );
  35857. }
  35858. bindLightTargets( object ) {
  35859. object.traverse( function ( child ) {
  35860. if ( child.isDirectionalLight || child.isSpotLight ) {
  35861. const uuid = child.target;
  35862. const target = object.getObjectByProperty( 'uuid', uuid );
  35863. if ( target !== undefined ) {
  35864. child.target = target;
  35865. } else {
  35866. child.target = new Object3D();
  35867. }
  35868. }
  35869. } );
  35870. }
  35871. }
  35872. const TEXTURE_MAPPING = {
  35873. UVMapping: UVMapping,
  35874. CubeReflectionMapping: CubeReflectionMapping,
  35875. CubeRefractionMapping: CubeRefractionMapping,
  35876. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35877. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35878. CubeUVReflectionMapping: CubeUVReflectionMapping
  35879. };
  35880. const TEXTURE_WRAPPING = {
  35881. RepeatWrapping: RepeatWrapping,
  35882. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35883. MirroredRepeatWrapping: MirroredRepeatWrapping
  35884. };
  35885. const TEXTURE_FILTER = {
  35886. NearestFilter: NearestFilter,
  35887. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35888. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35889. LinearFilter: LinearFilter,
  35890. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35891. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35892. };
  35893. const _errorMap = new WeakMap();
  35894. /**
  35895. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35896. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35897. * textures for rendering.
  35898. *
  35899. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35900. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35901. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35902. *
  35903. * To match the default behaviour of {@link Texture}, the following options are needed:
  35904. *
  35905. * ```js
  35906. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35907. * ```
  35908. *
  35909. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35910. *
  35911. * ```js
  35912. * const loader = new THREE.ImageBitmapLoader();
  35913. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35914. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35915. *
  35916. * const texture = new THREE.Texture( imageBitmap );
  35917. * texture.needsUpdate = true;
  35918. * ```
  35919. *
  35920. * @augments Loader
  35921. */
  35922. class ImageBitmapLoader extends Loader {
  35923. /**
  35924. * Constructs a new image bitmap loader.
  35925. *
  35926. * @param {LoadingManager} [manager] - The loading manager.
  35927. */
  35928. constructor( manager ) {
  35929. super( manager );
  35930. /**
  35931. * This flag can be used for type testing.
  35932. *
  35933. * @type {boolean}
  35934. * @readonly
  35935. * @default true
  35936. */
  35937. this.isImageBitmapLoader = true;
  35938. if ( typeof createImageBitmap === 'undefined' ) {
  35939. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35940. }
  35941. if ( typeof fetch === 'undefined' ) {
  35942. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35943. }
  35944. /**
  35945. * Represents the loader options.
  35946. *
  35947. * @type {Object}
  35948. * @default {premultiplyAlpha:'none'}
  35949. */
  35950. this.options = { premultiplyAlpha: 'none' };
  35951. /**
  35952. * Used for aborting requests.
  35953. *
  35954. * @private
  35955. * @type {AbortController}
  35956. */
  35957. this._abortController = new AbortController();
  35958. }
  35959. /**
  35960. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35961. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35962. *
  35963. * @param {Object} options - The loader options to set.
  35964. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35965. */
  35966. setOptions( options ) {
  35967. this.options = options;
  35968. return this;
  35969. }
  35970. /**
  35971. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35972. *
  35973. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35974. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35975. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35976. * @param {onErrorCallback} onError - Executed when errors occur.
  35977. * @return {ImageBitmap|undefined} The image bitmap.
  35978. */
  35979. load( url, onLoad, onProgress, onError ) {
  35980. if ( url === undefined ) url = '';
  35981. if ( this.path !== undefined ) url = this.path + url;
  35982. url = this.manager.resolveURL( url );
  35983. const scope = this;
  35984. const cached = Cache.get( `image-bitmap:${url}` );
  35985. if ( cached !== undefined ) {
  35986. scope.manager.itemStart( url );
  35987. // If cached is a promise, wait for it to resolve
  35988. if ( cached.then ) {
  35989. cached.then( imageBitmap => {
  35990. // check if there is an error for the cached promise
  35991. if ( _errorMap.has( cached ) === true ) {
  35992. if ( onError ) onError( _errorMap.get( cached ) );
  35993. scope.manager.itemError( url );
  35994. scope.manager.itemEnd( url );
  35995. } else {
  35996. if ( onLoad ) onLoad( imageBitmap );
  35997. scope.manager.itemEnd( url );
  35998. return imageBitmap;
  35999. }
  36000. } );
  36001. return;
  36002. }
  36003. // If cached is not a promise (i.e., it's already an imageBitmap)
  36004. setTimeout( function () {
  36005. if ( onLoad ) onLoad( cached );
  36006. scope.manager.itemEnd( url );
  36007. }, 0 );
  36008. return cached;
  36009. }
  36010. const fetchOptions = {};
  36011. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36012. fetchOptions.headers = this.requestHeader;
  36013. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36014. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36015. return res.blob();
  36016. } ).then( function ( blob ) {
  36017. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36018. } ).then( function ( imageBitmap ) {
  36019. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36020. if ( onLoad ) onLoad( imageBitmap );
  36021. scope.manager.itemEnd( url );
  36022. return imageBitmap;
  36023. } ).catch( function ( e ) {
  36024. if ( onError ) onError( e );
  36025. _errorMap.set( promise, e );
  36026. Cache.remove( `image-bitmap:${url}` );
  36027. scope.manager.itemError( url );
  36028. scope.manager.itemEnd( url );
  36029. } );
  36030. Cache.add( `image-bitmap:${url}`, promise );
  36031. scope.manager.itemStart( url );
  36032. }
  36033. /**
  36034. * Aborts ongoing fetch requests.
  36035. *
  36036. * @return {ImageBitmapLoader} A reference to this instance.
  36037. */
  36038. abort() {
  36039. this._abortController.abort();
  36040. this._abortController = new AbortController();
  36041. return this;
  36042. }
  36043. }
  36044. let _context;
  36045. /**
  36046. * Manages the global audio context in the engine.
  36047. *
  36048. * @hideconstructor
  36049. */
  36050. class AudioContext {
  36051. /**
  36052. * Returns the global native audio context.
  36053. *
  36054. * @return {AudioContext} The native audio context.
  36055. */
  36056. static getContext() {
  36057. if ( _context === undefined ) {
  36058. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36059. }
  36060. return _context;
  36061. }
  36062. /**
  36063. * Allows to set the global native audio context from outside.
  36064. *
  36065. * @param {AudioContext} value - The native context to set.
  36066. */
  36067. static setContext( value ) {
  36068. _context = value;
  36069. }
  36070. }
  36071. /**
  36072. * Class for loading audio buffers. Audios are internally
  36073. * loaded via {@link FileLoader}.
  36074. *
  36075. * ```js
  36076. * const audioListener = new THREE.AudioListener();
  36077. * const ambientSound = new THREE.Audio( audioListener );
  36078. *
  36079. * const loader = new THREE.AudioLoader();
  36080. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36081. *
  36082. * ambientSound.setBuffer( audioBuffer );
  36083. * ambientSound.play();
  36084. * ```
  36085. *
  36086. * @augments Loader
  36087. */
  36088. class AudioLoader extends Loader {
  36089. /**
  36090. * Constructs a new audio loader.
  36091. *
  36092. * @param {LoadingManager} [manager] - The loading manager.
  36093. */
  36094. constructor( manager ) {
  36095. super( manager );
  36096. }
  36097. /**
  36098. * Starts loading from the given URL and passes the loaded audio buffer
  36099. * to the `onLoad()` callback.
  36100. *
  36101. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36102. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36103. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36104. * @param {onErrorCallback} onError - Executed when errors occur.
  36105. */
  36106. load( url, onLoad, onProgress, onError ) {
  36107. const scope = this;
  36108. const loader = new FileLoader( this.manager );
  36109. loader.setResponseType( 'arraybuffer' );
  36110. loader.setPath( this.path );
  36111. loader.setRequestHeader( this.requestHeader );
  36112. loader.setWithCredentials( this.withCredentials );
  36113. loader.load( url, function ( buffer ) {
  36114. try {
  36115. // Create a copy of the buffer. The `decodeAudioData` method
  36116. // detaches the buffer when complete, preventing reuse.
  36117. const bufferCopy = buffer.slice( 0 );
  36118. const context = AudioContext.getContext();
  36119. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36120. onLoad( audioBuffer );
  36121. } ).catch( handleError );
  36122. } catch ( e ) {
  36123. handleError( e );
  36124. }
  36125. }, onProgress, onError );
  36126. function handleError( e ) {
  36127. if ( onError ) {
  36128. onError( e );
  36129. } else {
  36130. error( e );
  36131. }
  36132. scope.manager.itemError( url );
  36133. }
  36134. }
  36135. }
  36136. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36137. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36138. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36139. /**
  36140. * A special type of camera that uses two perspective cameras with
  36141. * stereoscopic projection. Can be used for rendering stereo effects
  36142. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36143. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36144. */
  36145. class StereoCamera {
  36146. /**
  36147. * Constructs a new stereo camera.
  36148. */
  36149. constructor() {
  36150. /**
  36151. * The type property is used for detecting the object type
  36152. * in context of serialization/deserialization.
  36153. *
  36154. * @type {string}
  36155. * @readonly
  36156. */
  36157. this.type = 'StereoCamera';
  36158. /**
  36159. * The aspect.
  36160. *
  36161. * @type {number}
  36162. * @default 1
  36163. */
  36164. this.aspect = 1;
  36165. /**
  36166. * The eye separation which represents the distance
  36167. * between the left and right camera.
  36168. *
  36169. * @type {number}
  36170. * @default 0.064
  36171. */
  36172. this.eyeSep = 0.064;
  36173. /**
  36174. * The camera representing the left eye. This is added to layer `1` so objects to be
  36175. * rendered by the left camera must also be added to this layer.
  36176. *
  36177. * @type {PerspectiveCamera}
  36178. */
  36179. this.cameraL = new PerspectiveCamera();
  36180. this.cameraL.layers.enable( 1 );
  36181. this.cameraL.matrixAutoUpdate = false;
  36182. /**
  36183. * The camera representing the right eye. This is added to layer `2` so objects to be
  36184. * rendered by the right camera must also be added to this layer.
  36185. *
  36186. * @type {PerspectiveCamera}
  36187. */
  36188. this.cameraR = new PerspectiveCamera();
  36189. this.cameraR.layers.enable( 2 );
  36190. this.cameraR.matrixAutoUpdate = false;
  36191. this._cache = {
  36192. focus: null,
  36193. fov: null,
  36194. aspect: null,
  36195. near: null,
  36196. far: null,
  36197. zoom: null,
  36198. eyeSep: null
  36199. };
  36200. }
  36201. /**
  36202. * Updates the stereo camera based on the given perspective camera.
  36203. *
  36204. * @param {PerspectiveCamera} camera - The perspective camera.
  36205. */
  36206. update( camera ) {
  36207. const cache = this._cache;
  36208. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36209. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36210. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36211. if ( needsUpdate ) {
  36212. cache.focus = camera.focus;
  36213. cache.fov = camera.fov;
  36214. cache.aspect = camera.aspect * this.aspect;
  36215. cache.near = camera.near;
  36216. cache.far = camera.far;
  36217. cache.zoom = camera.zoom;
  36218. cache.eyeSep = this.eyeSep;
  36219. // Off-axis stereoscopic effect based on
  36220. // http://paulbourke.net/stereographics/stereorender/
  36221. _projectionMatrix.copy( camera.projectionMatrix );
  36222. const eyeSepHalf = cache.eyeSep / 2;
  36223. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36224. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36225. let xmin, xmax;
  36226. // translate xOffset
  36227. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36228. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36229. // for left eye
  36230. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36231. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36232. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36233. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36234. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36235. // for right eye
  36236. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36237. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36238. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36239. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36240. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36241. }
  36242. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36243. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36244. }
  36245. }
  36246. const fov = -90; // negative fov is not an error
  36247. const aspect = 1;
  36248. /**
  36249. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36250. * cube render target. The render target can then be used as an environment map for rendering
  36251. * realtime reflections in your scene.
  36252. *
  36253. * ```js
  36254. * // Create cube render target
  36255. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36256. *
  36257. * // Create cube camera
  36258. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36259. * scene.add( cubeCamera );
  36260. *
  36261. * // Create car
  36262. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36263. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36264. * scene.add( car );
  36265. *
  36266. * // Update the render target cube
  36267. * car.visible = false;
  36268. * cubeCamera.position.copy( car.position );
  36269. * cubeCamera.update( renderer, scene );
  36270. *
  36271. * // Render the scene
  36272. * car.visible = true;
  36273. * renderer.render( scene, camera );
  36274. * ```
  36275. *
  36276. * @augments Object3D
  36277. */
  36278. class CubeCamera extends Object3D {
  36279. /**
  36280. * Constructs a new cube camera.
  36281. *
  36282. * @param {number} near - The camera's near plane.
  36283. * @param {number} far - The camera's far plane.
  36284. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36285. */
  36286. constructor( near, far, renderTarget ) {
  36287. super();
  36288. this.type = 'CubeCamera';
  36289. /**
  36290. * A reference to the cube render target.
  36291. *
  36292. * @type {WebGLCubeRenderTarget}
  36293. */
  36294. this.renderTarget = renderTarget;
  36295. /**
  36296. * The current active coordinate system.
  36297. *
  36298. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36299. * @default null
  36300. */
  36301. this.coordinateSystem = null;
  36302. /**
  36303. * The current active mipmap level
  36304. *
  36305. * @type {number}
  36306. * @default 0
  36307. */
  36308. this.activeMipmapLevel = 0;
  36309. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36310. cameraPX.layers = this.layers;
  36311. this.add( cameraPX );
  36312. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36313. cameraNX.layers = this.layers;
  36314. this.add( cameraNX );
  36315. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36316. cameraPY.layers = this.layers;
  36317. this.add( cameraPY );
  36318. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36319. cameraNY.layers = this.layers;
  36320. this.add( cameraNY );
  36321. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36322. cameraPZ.layers = this.layers;
  36323. this.add( cameraPZ );
  36324. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36325. cameraNZ.layers = this.layers;
  36326. this.add( cameraNZ );
  36327. }
  36328. /**
  36329. * Must be called when the coordinate system of the cube camera is changed.
  36330. */
  36331. updateCoordinateSystem() {
  36332. const coordinateSystem = this.coordinateSystem;
  36333. const cameras = this.children.concat();
  36334. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36335. for ( const camera of cameras ) this.remove( camera );
  36336. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36337. cameraPX.up.set( 0, 1, 0 );
  36338. cameraPX.lookAt( 1, 0, 0 );
  36339. cameraNX.up.set( 0, 1, 0 );
  36340. cameraNX.lookAt( -1, 0, 0 );
  36341. cameraPY.up.set( 0, 0, -1 );
  36342. cameraPY.lookAt( 0, 1, 0 );
  36343. cameraNY.up.set( 0, 0, 1 );
  36344. cameraNY.lookAt( 0, -1, 0 );
  36345. cameraPZ.up.set( 0, 1, 0 );
  36346. cameraPZ.lookAt( 0, 0, 1 );
  36347. cameraNZ.up.set( 0, 1, 0 );
  36348. cameraNZ.lookAt( 0, 0, -1 );
  36349. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36350. cameraPX.up.set( 0, -1, 0 );
  36351. cameraPX.lookAt( -1, 0, 0 );
  36352. cameraNX.up.set( 0, -1, 0 );
  36353. cameraNX.lookAt( 1, 0, 0 );
  36354. cameraPY.up.set( 0, 0, 1 );
  36355. cameraPY.lookAt( 0, 1, 0 );
  36356. cameraNY.up.set( 0, 0, -1 );
  36357. cameraNY.lookAt( 0, -1, 0 );
  36358. cameraPZ.up.set( 0, -1, 0 );
  36359. cameraPZ.lookAt( 0, 0, 1 );
  36360. cameraNZ.up.set( 0, -1, 0 );
  36361. cameraNZ.lookAt( 0, 0, -1 );
  36362. } else {
  36363. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36364. }
  36365. for ( const camera of cameras ) {
  36366. this.add( camera );
  36367. camera.updateMatrixWorld();
  36368. }
  36369. }
  36370. /**
  36371. * Calling this method will render the given scene with the given renderer
  36372. * into the cube render target of the camera.
  36373. *
  36374. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36375. * @param {Scene} scene - The scene to render.
  36376. */
  36377. update( renderer, scene ) {
  36378. if ( this.parent === null ) this.updateMatrixWorld();
  36379. const { renderTarget, activeMipmapLevel } = this;
  36380. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36381. this.coordinateSystem = renderer.coordinateSystem;
  36382. this.updateCoordinateSystem();
  36383. }
  36384. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36385. const currentRenderTarget = renderer.getRenderTarget();
  36386. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36387. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36388. const currentXrEnabled = renderer.xr.enabled;
  36389. renderer.xr.enabled = false;
  36390. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36391. renderTarget.texture.generateMipmaps = false;
  36392. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36393. let reversedDepthBuffer = false;
  36394. if ( renderer.isWebGLRenderer === true ) {
  36395. reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  36396. } else {
  36397. reversedDepthBuffer = renderer.reversedDepthBuffer;
  36398. }
  36399. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36400. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36401. renderer.render( scene, cameraPX );
  36402. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36403. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36404. renderer.render( scene, cameraNX );
  36405. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36406. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36407. renderer.render( scene, cameraPY );
  36408. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36409. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36410. renderer.render( scene, cameraNY );
  36411. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36412. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36413. renderer.render( scene, cameraPZ );
  36414. // mipmaps are generated during the last call of render()
  36415. // at this point, all sides of the cube render target are defined
  36416. renderTarget.texture.generateMipmaps = generateMipmaps;
  36417. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36418. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36419. renderer.render( scene, cameraNZ );
  36420. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36421. renderer.xr.enabled = currentXrEnabled;
  36422. renderTarget.texture.needsPMREMUpdate = true;
  36423. }
  36424. }
  36425. /**
  36426. * This type of camera can be used in order to efficiently render a scene with a
  36427. * predefined set of cameras. This is an important performance aspect for
  36428. * rendering VR scenes.
  36429. *
  36430. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36431. * to define for each sub camera the `viewport` property which determines the
  36432. * part of the viewport that is rendered with this camera.
  36433. *
  36434. * @augments PerspectiveCamera
  36435. */
  36436. class ArrayCamera extends PerspectiveCamera {
  36437. /**
  36438. * Constructs a new array camera.
  36439. *
  36440. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36441. */
  36442. constructor( array = [] ) {
  36443. super();
  36444. /**
  36445. * This flag can be used for type testing.
  36446. *
  36447. * @type {boolean}
  36448. * @readonly
  36449. * @default true
  36450. */
  36451. this.isArrayCamera = true;
  36452. /**
  36453. * Whether this camera is used with multiview rendering or not.
  36454. *
  36455. * @type {boolean}
  36456. * @readonly
  36457. * @default false
  36458. */
  36459. this.isMultiViewCamera = false;
  36460. /**
  36461. * An array of perspective sub cameras.
  36462. *
  36463. * @type {Array<PerspectiveCamera>}
  36464. */
  36465. this.cameras = array;
  36466. }
  36467. }
  36468. /**
  36469. * This class is an alternative to {@link Clock} with a different API design and behavior.
  36470. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  36471. *
  36472. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  36473. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  36474. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  36475. * is inactive (e.g. tab switched or browser hidden).
  36476. *
  36477. * ```js
  36478. * const timer = new Timer();
  36479. * timer.connect( document ); // use Page Visibility API
  36480. * ```
  36481. */
  36482. class Timer {
  36483. /**
  36484. * Constructs a new timer.
  36485. */
  36486. constructor() {
  36487. this._previousTime = 0;
  36488. this._currentTime = 0;
  36489. this._startTime = performance.now();
  36490. this._delta = 0;
  36491. this._elapsed = 0;
  36492. this._timescale = 1;
  36493. this._document = null;
  36494. this._pageVisibilityHandler = null;
  36495. }
  36496. /**
  36497. * Connect the timer to the given document.Calling this method is not mandatory to
  36498. * use the timer but enables the usage of the Page Visibility API to avoid large time
  36499. * delta values.
  36500. *
  36501. * @param {Document} document - The document.
  36502. */
  36503. connect( document ) {
  36504. this._document = document;
  36505. // use Page Visibility API to avoid large time delta values
  36506. if ( document.hidden !== undefined ) {
  36507. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  36508. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  36509. }
  36510. }
  36511. /**
  36512. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  36513. */
  36514. disconnect() {
  36515. if ( this._pageVisibilityHandler !== null ) {
  36516. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  36517. this._pageVisibilityHandler = null;
  36518. }
  36519. this._document = null;
  36520. }
  36521. /**
  36522. * Returns the time delta in seconds.
  36523. *
  36524. * @return {number} The time delta in second.
  36525. */
  36526. getDelta() {
  36527. return this._delta / 1000;
  36528. }
  36529. /**
  36530. * Returns the elapsed time in seconds.
  36531. *
  36532. * @return {number} The elapsed time in second.
  36533. */
  36534. getElapsed() {
  36535. return this._elapsed / 1000;
  36536. }
  36537. /**
  36538. * Returns the timescale.
  36539. *
  36540. * @return {number} The timescale.
  36541. */
  36542. getTimescale() {
  36543. return this._timescale;
  36544. }
  36545. /**
  36546. * Sets the given timescale which scale the time delta computation
  36547. * in `update()`.
  36548. *
  36549. * @param {number} timescale - The timescale to set.
  36550. * @return {Timer} A reference to this timer.
  36551. */
  36552. setTimescale( timescale ) {
  36553. this._timescale = timescale;
  36554. return this;
  36555. }
  36556. /**
  36557. * Resets the time computation for the current simulation step.
  36558. *
  36559. * @return {Timer} A reference to this timer.
  36560. */
  36561. reset() {
  36562. this._currentTime = performance.now() - this._startTime;
  36563. return this;
  36564. }
  36565. /**
  36566. * Can be used to free all internal resources. Usually called when
  36567. * the timer instance isn't required anymore.
  36568. */
  36569. dispose() {
  36570. this.disconnect();
  36571. }
  36572. /**
  36573. * Updates the internal state of the timer. This method should be called
  36574. * once per simulation step and before you perform queries against the timer
  36575. * (e.g. via `getDelta()`).
  36576. *
  36577. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  36578. * from the `requestAnimationFrame` callback argument. If not provided, the current
  36579. * time will be determined with `performance.now`.
  36580. * @return {Timer} A reference to this timer.
  36581. */
  36582. update( timestamp ) {
  36583. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  36584. this._delta = 0;
  36585. } else {
  36586. this._previousTime = this._currentTime;
  36587. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  36588. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  36589. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  36590. }
  36591. return this;
  36592. }
  36593. }
  36594. function handleVisibilityChange() {
  36595. if ( this._document.hidden === false ) this.reset();
  36596. }
  36597. const _position$1 = /*@__PURE__*/ new Vector3();
  36598. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36599. const _scale$1 = /*@__PURE__*/ new Vector3();
  36600. const _forward = /*@__PURE__*/ new Vector3();
  36601. const _up = /*@__PURE__*/ new Vector3();
  36602. /**
  36603. * The class represents a virtual listener of the all positional and non-positional audio effects
  36604. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36605. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36606. *
  36607. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36608. * camera represents the 3D transformation of the listener.
  36609. *
  36610. * @augments Object3D
  36611. */
  36612. class AudioListener extends Object3D {
  36613. /**
  36614. * Constructs a new audio listener.
  36615. */
  36616. constructor() {
  36617. super();
  36618. this.type = 'AudioListener';
  36619. /**
  36620. * The native audio context.
  36621. *
  36622. * @type {AudioContext}
  36623. * @readonly
  36624. */
  36625. this.context = AudioContext.getContext();
  36626. /**
  36627. * The gain node used for volume control.
  36628. *
  36629. * @type {GainNode}
  36630. * @readonly
  36631. */
  36632. this.gain = this.context.createGain();
  36633. this.gain.connect( this.context.destination );
  36634. /**
  36635. * An optional filter.
  36636. *
  36637. * Defined via {@link AudioListener#setFilter}.
  36638. *
  36639. * @type {?AudioNode}
  36640. * @default null
  36641. * @readonly
  36642. */
  36643. this.filter = null;
  36644. /**
  36645. * Time delta values required for `linearRampToValueAtTime()` usage.
  36646. *
  36647. * @type {number}
  36648. * @default 0
  36649. * @readonly
  36650. */
  36651. this.timeDelta = 0;
  36652. // private
  36653. this._timer = new Timer();
  36654. }
  36655. /**
  36656. * Returns the listener's input node.
  36657. *
  36658. * This method is used by other audio nodes to connect to this listener.
  36659. *
  36660. * @return {GainNode} The input node.
  36661. */
  36662. getInput() {
  36663. return this.gain;
  36664. }
  36665. /**
  36666. * Removes the current filter from this listener.
  36667. *
  36668. * @return {AudioListener} A reference to this listener.
  36669. */
  36670. removeFilter() {
  36671. if ( this.filter !== null ) {
  36672. this.gain.disconnect( this.filter );
  36673. this.filter.disconnect( this.context.destination );
  36674. this.gain.connect( this.context.destination );
  36675. this.filter = null;
  36676. }
  36677. return this;
  36678. }
  36679. /**
  36680. * Returns the current set filter.
  36681. *
  36682. * @return {?AudioNode} The filter.
  36683. */
  36684. getFilter() {
  36685. return this.filter;
  36686. }
  36687. /**
  36688. * Sets the given filter to this listener.
  36689. *
  36690. * @param {AudioNode} value - The filter to set.
  36691. * @return {AudioListener} A reference to this listener.
  36692. */
  36693. setFilter( value ) {
  36694. if ( this.filter !== null ) {
  36695. this.gain.disconnect( this.filter );
  36696. this.filter.disconnect( this.context.destination );
  36697. } else {
  36698. this.gain.disconnect( this.context.destination );
  36699. }
  36700. this.filter = value;
  36701. this.gain.connect( this.filter );
  36702. this.filter.connect( this.context.destination );
  36703. return this;
  36704. }
  36705. /**
  36706. * Returns the applications master volume.
  36707. *
  36708. * @return {number} The master volume.
  36709. */
  36710. getMasterVolume() {
  36711. return this.gain.gain.value;
  36712. }
  36713. /**
  36714. * Sets the applications master volume. This volume setting affects
  36715. * all audio nodes in the scene.
  36716. *
  36717. * @param {number} value - The master volume to set.
  36718. * @return {AudioListener} A reference to this listener.
  36719. */
  36720. setMasterVolume( value ) {
  36721. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36722. return this;
  36723. }
  36724. updateMatrixWorld( force ) {
  36725. super.updateMatrixWorld( force );
  36726. this._timer.update();
  36727. const listener = this.context.listener;
  36728. this.timeDelta = this._timer.getDelta();
  36729. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36730. // the initial forward and up directions must be orthogonal
  36731. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36732. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36733. if ( listener.positionX ) {
  36734. // code path for Chrome (see #14393)
  36735. const endTime = this.context.currentTime + this.timeDelta;
  36736. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36737. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36738. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36739. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36740. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36741. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36742. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36743. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36744. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36745. } else {
  36746. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36747. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36748. }
  36749. }
  36750. }
  36751. /**
  36752. * Represents a non-positional ( global ) audio object.
  36753. *
  36754. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36755. *
  36756. * ```js
  36757. * // create an AudioListener and add it to the camera
  36758. * const listener = new THREE.AudioListener();
  36759. * camera.add( listener );
  36760. *
  36761. * // create a global audio source
  36762. * const sound = new THREE.Audio( listener );
  36763. *
  36764. * // load a sound and set it as the Audio object's buffer
  36765. * const audioLoader = new THREE.AudioLoader();
  36766. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36767. * sound.setBuffer( buffer );
  36768. * sound.setLoop( true );
  36769. * sound.setVolume( 0.5 );
  36770. * sound.play();
  36771. * });
  36772. * ```
  36773. *
  36774. * @augments Object3D
  36775. */
  36776. class Audio extends Object3D {
  36777. /**
  36778. * Constructs a new audio.
  36779. *
  36780. * @param {AudioListener} listener - The global audio listener.
  36781. */
  36782. constructor( listener ) {
  36783. super();
  36784. this.type = 'Audio';
  36785. /**
  36786. * The global audio listener.
  36787. *
  36788. * @type {AudioListener}
  36789. * @readonly
  36790. */
  36791. this.listener = listener;
  36792. /**
  36793. * The audio context.
  36794. *
  36795. * @type {AudioContext}
  36796. * @readonly
  36797. */
  36798. this.context = listener.context;
  36799. /**
  36800. * The gain node used for volume control.
  36801. *
  36802. * @type {GainNode}
  36803. * @readonly
  36804. */
  36805. this.gain = this.context.createGain();
  36806. this.gain.connect( listener.getInput() );
  36807. /**
  36808. * Whether to start playback automatically or not.
  36809. *
  36810. * @type {boolean}
  36811. * @default false
  36812. */
  36813. this.autoplay = false;
  36814. /**
  36815. * A reference to an audio buffer.
  36816. *
  36817. * Defined via {@link Audio#setBuffer}.
  36818. *
  36819. * @type {?AudioBuffer}
  36820. * @default null
  36821. * @readonly
  36822. */
  36823. this.buffer = null;
  36824. /**
  36825. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36826. * +/- 1200 is an octave.
  36827. *
  36828. * Defined via {@link Audio#setDetune}.
  36829. *
  36830. * @type {number}
  36831. * @default 0
  36832. * @readonly
  36833. */
  36834. this.detune = 0;
  36835. /**
  36836. * Whether the audio should loop or not.
  36837. *
  36838. * Defined via {@link Audio#setLoop}.
  36839. *
  36840. * @type {boolean}
  36841. * @default false
  36842. * @readonly
  36843. */
  36844. this.loop = false;
  36845. /**
  36846. * Defines where in the audio buffer the replay should
  36847. * start, in seconds.
  36848. *
  36849. * @type {number}
  36850. * @default 0
  36851. */
  36852. this.loopStart = 0;
  36853. /**
  36854. * Defines where in the audio buffer the replay should
  36855. * stop, in seconds.
  36856. *
  36857. * @type {number}
  36858. * @default 0
  36859. */
  36860. this.loopEnd = 0;
  36861. /**
  36862. * An offset to the time within the audio buffer the playback
  36863. * should begin, in seconds.
  36864. *
  36865. * @type {number}
  36866. * @default 0
  36867. */
  36868. this.offset = 0;
  36869. /**
  36870. * Overrides the default duration of the audio.
  36871. *
  36872. * @type {undefined|number}
  36873. * @default undefined
  36874. */
  36875. this.duration = undefined;
  36876. /**
  36877. * The playback speed.
  36878. *
  36879. * Defined via {@link Audio#setPlaybackRate}.
  36880. *
  36881. * @type {number}
  36882. * @readonly
  36883. * @default 1
  36884. */
  36885. this.playbackRate = 1;
  36886. /**
  36887. * Indicates whether the audio is playing or not.
  36888. *
  36889. * This flag will be automatically set when using {@link Audio#play},
  36890. * {@link Audio#pause}, {@link Audio#stop}.
  36891. *
  36892. * @type {boolean}
  36893. * @readonly
  36894. * @default false
  36895. */
  36896. this.isPlaying = false;
  36897. /**
  36898. * Indicates whether the audio playback can be controlled
  36899. * with method like {@link Audio#play} or {@link Audio#pause}.
  36900. *
  36901. * This flag will be automatically set when audio sources are
  36902. * defined.
  36903. *
  36904. * @type {boolean}
  36905. * @readonly
  36906. * @default true
  36907. */
  36908. this.hasPlaybackControl = true;
  36909. /**
  36910. * Holds a reference to the current audio source.
  36911. *
  36912. * The property is automatically by one of the `set*()` methods.
  36913. *
  36914. * @type {?AudioNode}
  36915. * @readonly
  36916. * @default null
  36917. */
  36918. this.source = null;
  36919. /**
  36920. * Defines the source type.
  36921. *
  36922. * The property is automatically set by one of the `set*()` methods.
  36923. *
  36924. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36925. * @readonly
  36926. * @default 'empty'
  36927. */
  36928. this.sourceType = 'empty';
  36929. this._startedAt = 0;
  36930. this._progress = 0;
  36931. this._connected = false;
  36932. /**
  36933. * Can be used to apply a variety of low-order filters to create
  36934. * more complex sound effects e.g. via `BiquadFilterNode`.
  36935. *
  36936. * The property is automatically set by {@link Audio#setFilters}.
  36937. *
  36938. * @type {Array<AudioNode>}
  36939. * @readonly
  36940. */
  36941. this.filters = [];
  36942. }
  36943. /**
  36944. * Returns the output audio node.
  36945. *
  36946. * @return {GainNode} The output node.
  36947. */
  36948. getOutput() {
  36949. return this.gain;
  36950. }
  36951. /**
  36952. * Sets the given audio node as the source of this instance.
  36953. *
  36954. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36955. *
  36956. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36957. * @return {Audio} A reference to this instance.
  36958. */
  36959. setNodeSource( audioNode ) {
  36960. this.hasPlaybackControl = false;
  36961. this.sourceType = 'audioNode';
  36962. this.source = audioNode;
  36963. this.connect();
  36964. return this;
  36965. }
  36966. /**
  36967. * Sets the given media element as the source of this instance.
  36968. *
  36969. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36970. *
  36971. * @param {HTMLMediaElement} mediaElement - The media element.
  36972. * @return {Audio} A reference to this instance.
  36973. */
  36974. setMediaElementSource( mediaElement ) {
  36975. this.hasPlaybackControl = false;
  36976. this.sourceType = 'mediaNode';
  36977. this.source = this.context.createMediaElementSource( mediaElement );
  36978. this.connect();
  36979. return this;
  36980. }
  36981. /**
  36982. * Sets the given media stream as the source of this instance.
  36983. *
  36984. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36985. *
  36986. * @param {MediaStream} mediaStream - The media stream.
  36987. * @return {Audio} A reference to this instance.
  36988. */
  36989. setMediaStreamSource( mediaStream ) {
  36990. this.hasPlaybackControl = false;
  36991. this.sourceType = 'mediaStreamNode';
  36992. this.source = this.context.createMediaStreamSource( mediaStream );
  36993. this.connect();
  36994. return this;
  36995. }
  36996. /**
  36997. * Sets the given audio buffer as the source of this instance.
  36998. *
  36999. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37000. *
  37001. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37002. * @return {Audio} A reference to this instance.
  37003. */
  37004. setBuffer( audioBuffer ) {
  37005. this.buffer = audioBuffer;
  37006. this.sourceType = 'buffer';
  37007. if ( this.autoplay ) this.play();
  37008. return this;
  37009. }
  37010. /**
  37011. * Starts the playback of the audio.
  37012. *
  37013. * Can only be used with compatible audio sources that allow playback control.
  37014. *
  37015. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37016. * @return {Audio|undefined} A reference to this instance.
  37017. */
  37018. play( delay = 0 ) {
  37019. if ( this.isPlaying === true ) {
  37020. warn( 'Audio: Audio is already playing.' );
  37021. return;
  37022. }
  37023. if ( this.hasPlaybackControl === false ) {
  37024. warn( 'Audio: this Audio has no playback control.' );
  37025. return;
  37026. }
  37027. this._startedAt = this.context.currentTime + delay;
  37028. const source = this.context.createBufferSource();
  37029. source.buffer = this.buffer;
  37030. source.loop = this.loop;
  37031. source.loopStart = this.loopStart;
  37032. source.loopEnd = this.loopEnd;
  37033. source.onended = this.onEnded.bind( this );
  37034. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37035. this.isPlaying = true;
  37036. this.source = source;
  37037. this.setDetune( this.detune );
  37038. this.setPlaybackRate( this.playbackRate );
  37039. return this.connect();
  37040. }
  37041. /**
  37042. * Pauses the playback of the audio.
  37043. *
  37044. * Can only be used with compatible audio sources that allow playback control.
  37045. *
  37046. * @return {Audio|undefined} A reference to this instance.
  37047. */
  37048. pause() {
  37049. if ( this.hasPlaybackControl === false ) {
  37050. warn( 'Audio: this Audio has no playback control.' );
  37051. return;
  37052. }
  37053. if ( this.isPlaying === true ) {
  37054. // update current progress
  37055. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37056. if ( this.loop === true ) {
  37057. // ensure _progress does not exceed duration with looped audios
  37058. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37059. }
  37060. this.source.stop();
  37061. this.source.onended = null;
  37062. this.isPlaying = false;
  37063. }
  37064. return this;
  37065. }
  37066. /**
  37067. * Stops the playback of the audio.
  37068. *
  37069. * Can only be used with compatible audio sources that allow playback control.
  37070. *
  37071. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37072. * @return {Audio|undefined} A reference to this instance.
  37073. */
  37074. stop( delay = 0 ) {
  37075. if ( this.hasPlaybackControl === false ) {
  37076. warn( 'Audio: this Audio has no playback control.' );
  37077. return;
  37078. }
  37079. this._progress = 0;
  37080. if ( this.source !== null ) {
  37081. this.source.stop( this.context.currentTime + delay );
  37082. this.source.onended = null;
  37083. }
  37084. this.isPlaying = false;
  37085. return this;
  37086. }
  37087. /**
  37088. * Connects to the audio source. This is used internally on
  37089. * initialisation and when setting / removing filters.
  37090. *
  37091. * @return {Audio} A reference to this instance.
  37092. */
  37093. connect() {
  37094. if ( this.filters.length > 0 ) {
  37095. this.source.connect( this.filters[ 0 ] );
  37096. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37097. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37098. }
  37099. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37100. } else {
  37101. this.source.connect( this.getOutput() );
  37102. }
  37103. this._connected = true;
  37104. return this;
  37105. }
  37106. /**
  37107. * Disconnects to the audio source. This is used internally on
  37108. * initialisation and when setting / removing filters.
  37109. *
  37110. * @return {Audio|undefined} A reference to this instance.
  37111. */
  37112. disconnect() {
  37113. if ( this._connected === false ) {
  37114. return;
  37115. }
  37116. if ( this.filters.length > 0 ) {
  37117. this.source.disconnect( this.filters[ 0 ] );
  37118. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37119. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37120. }
  37121. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37122. } else {
  37123. this.source.disconnect( this.getOutput() );
  37124. }
  37125. this._connected = false;
  37126. return this;
  37127. }
  37128. /**
  37129. * Returns the current set filters.
  37130. *
  37131. * @return {Array<AudioNode>} The list of filters.
  37132. */
  37133. getFilters() {
  37134. return this.filters;
  37135. }
  37136. /**
  37137. * Sets an array of filters and connects them with the audio source.
  37138. *
  37139. * @param {Array<AudioNode>} [value] - A list of filters.
  37140. * @return {Audio} A reference to this instance.
  37141. */
  37142. setFilters( value ) {
  37143. if ( ! value ) value = [];
  37144. if ( this._connected === true ) {
  37145. this.disconnect();
  37146. this.filters = value.slice();
  37147. this.connect();
  37148. } else {
  37149. this.filters = value.slice();
  37150. }
  37151. return this;
  37152. }
  37153. /**
  37154. * Defines the detuning of oscillation in cents.
  37155. *
  37156. * @param {number} value - The detuning of oscillation in cents.
  37157. * @return {Audio} A reference to this instance.
  37158. */
  37159. setDetune( value ) {
  37160. this.detune = value;
  37161. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37162. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37163. }
  37164. return this;
  37165. }
  37166. /**
  37167. * Returns the detuning of oscillation in cents.
  37168. *
  37169. * @return {number} The detuning of oscillation in cents.
  37170. */
  37171. getDetune() {
  37172. return this.detune;
  37173. }
  37174. /**
  37175. * Returns the first filter in the list of filters.
  37176. *
  37177. * @return {AudioNode|undefined} The first filter in the list of filters.
  37178. */
  37179. getFilter() {
  37180. return this.getFilters()[ 0 ];
  37181. }
  37182. /**
  37183. * Applies a single filter node to the audio.
  37184. *
  37185. * @param {AudioNode} [filter] - The filter to set.
  37186. * @return {Audio} A reference to this instance.
  37187. */
  37188. setFilter( filter ) {
  37189. return this.setFilters( filter ? [ filter ] : [] );
  37190. }
  37191. /**
  37192. * Sets the playback rate.
  37193. *
  37194. * Can only be used with compatible audio sources that allow playback control.
  37195. *
  37196. * @param {number} [value] - The playback rate to set.
  37197. * @return {Audio|undefined} A reference to this instance.
  37198. */
  37199. setPlaybackRate( value ) {
  37200. if ( this.hasPlaybackControl === false ) {
  37201. warn( 'Audio: this Audio has no playback control.' );
  37202. return;
  37203. }
  37204. this.playbackRate = value;
  37205. if ( this.isPlaying === true ) {
  37206. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37207. }
  37208. return this;
  37209. }
  37210. /**
  37211. * Returns the current playback rate.
  37212. * @return {number} The playback rate.
  37213. */
  37214. getPlaybackRate() {
  37215. return this.playbackRate;
  37216. }
  37217. /**
  37218. * Automatically called when playback finished.
  37219. */
  37220. onEnded() {
  37221. this.isPlaying = false;
  37222. this._progress = 0;
  37223. }
  37224. /**
  37225. * Returns the loop flag.
  37226. *
  37227. * Can only be used with compatible audio sources that allow playback control.
  37228. *
  37229. * @return {boolean} Whether the audio should loop or not.
  37230. */
  37231. getLoop() {
  37232. if ( this.hasPlaybackControl === false ) {
  37233. warn( 'Audio: this Audio has no playback control.' );
  37234. return false;
  37235. }
  37236. return this.loop;
  37237. }
  37238. /**
  37239. * Sets the loop flag.
  37240. *
  37241. * Can only be used with compatible audio sources that allow playback control.
  37242. *
  37243. * @param {boolean} value - Whether the audio should loop or not.
  37244. * @return {Audio|undefined} A reference to this instance.
  37245. */
  37246. setLoop( value ) {
  37247. if ( this.hasPlaybackControl === false ) {
  37248. warn( 'Audio: this Audio has no playback control.' );
  37249. return;
  37250. }
  37251. this.loop = value;
  37252. if ( this.isPlaying === true ) {
  37253. this.source.loop = this.loop;
  37254. }
  37255. return this;
  37256. }
  37257. /**
  37258. * Sets the loop start value which defines where in the audio buffer the replay should
  37259. * start, in seconds.
  37260. *
  37261. * @param {number} value - The loop start value.
  37262. * @return {Audio} A reference to this instance.
  37263. */
  37264. setLoopStart( value ) {
  37265. this.loopStart = value;
  37266. return this;
  37267. }
  37268. /**
  37269. * Sets the loop end value which defines where in the audio buffer the replay should
  37270. * stop, in seconds.
  37271. *
  37272. * @param {number} value - The loop end value.
  37273. * @return {Audio} A reference to this instance.
  37274. */
  37275. setLoopEnd( value ) {
  37276. this.loopEnd = value;
  37277. return this;
  37278. }
  37279. /**
  37280. * Returns the volume.
  37281. *
  37282. * @return {number} The volume.
  37283. */
  37284. getVolume() {
  37285. return this.gain.gain.value;
  37286. }
  37287. /**
  37288. * Sets the volume.
  37289. *
  37290. * @param {number} value - The volume to set.
  37291. * @return {Audio} A reference to this instance.
  37292. */
  37293. setVolume( value ) {
  37294. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37295. return this;
  37296. }
  37297. copy( source, recursive ) {
  37298. super.copy( source, recursive );
  37299. if ( source.sourceType !== 'buffer' ) {
  37300. warn( 'Audio: Audio source type cannot be copied.' );
  37301. return this;
  37302. }
  37303. this.autoplay = source.autoplay;
  37304. this.buffer = source.buffer;
  37305. this.detune = source.detune;
  37306. this.loop = source.loop;
  37307. this.loopStart = source.loopStart;
  37308. this.loopEnd = source.loopEnd;
  37309. this.offset = source.offset;
  37310. this.duration = source.duration;
  37311. this.playbackRate = source.playbackRate;
  37312. this.hasPlaybackControl = source.hasPlaybackControl;
  37313. this.sourceType = source.sourceType;
  37314. this.filters = source.filters.slice();
  37315. return this;
  37316. }
  37317. clone( recursive ) {
  37318. return new this.constructor( this.listener ).copy( this, recursive );
  37319. }
  37320. }
  37321. const _position = /*@__PURE__*/ new Vector3();
  37322. const _quaternion = /*@__PURE__*/ new Quaternion();
  37323. const _scale = /*@__PURE__*/ new Vector3();
  37324. const _orientation = /*@__PURE__*/ new Vector3();
  37325. /**
  37326. * Represents a positional audio object.
  37327. *
  37328. * ```js
  37329. * // create an AudioListener and add it to the camera
  37330. * const listener = new THREE.AudioListener();
  37331. * camera.add( listener );
  37332. *
  37333. * // create the PositionalAudio object (passing in the listener)
  37334. * const sound = new THREE.PositionalAudio( listener );
  37335. *
  37336. * // load a sound and set it as the PositionalAudio object's buffer
  37337. * const audioLoader = new THREE.AudioLoader();
  37338. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37339. * sound.setBuffer( buffer );
  37340. * sound.setRefDistance( 20 );
  37341. * sound.play();
  37342. * });
  37343. *
  37344. * // create an object for the sound to play from
  37345. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37346. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37347. * const mesh = new THREE.Mesh( sphere, material );
  37348. * scene.add( mesh );
  37349. *
  37350. * // finally add the sound to the mesh
  37351. * mesh.add( sound );
  37352. *
  37353. * @augments Audio
  37354. */
  37355. class PositionalAudio extends Audio {
  37356. /**
  37357. * Constructs a positional audio.
  37358. *
  37359. * @param {AudioListener} listener - The global audio listener.
  37360. */
  37361. constructor( listener ) {
  37362. super( listener );
  37363. /**
  37364. * The panner node represents the location, direction, and behavior of an audio
  37365. * source in 3D space.
  37366. *
  37367. * @type {PannerNode}
  37368. * @readonly
  37369. */
  37370. this.panner = this.context.createPanner();
  37371. this.panner.panningModel = 'HRTF';
  37372. this.panner.connect( this.gain );
  37373. }
  37374. connect() {
  37375. super.connect();
  37376. this.panner.connect( this.gain );
  37377. return this;
  37378. }
  37379. disconnect() {
  37380. super.disconnect();
  37381. this.panner.disconnect( this.gain );
  37382. return this;
  37383. }
  37384. getOutput() {
  37385. return this.panner;
  37386. }
  37387. /**
  37388. * Returns the current reference distance.
  37389. *
  37390. * @return {number} The reference distance.
  37391. */
  37392. getRefDistance() {
  37393. return this.panner.refDistance;
  37394. }
  37395. /**
  37396. * Defines the reference distance for reducing volume as the audio source moves
  37397. * further from the listener – i.e. the distance at which the volume reduction
  37398. * starts taking effect.
  37399. *
  37400. * @param {number} value - The reference distance to set.
  37401. * @return {PositionalAudio} A reference to this instance.
  37402. */
  37403. setRefDistance( value ) {
  37404. this.panner.refDistance = value;
  37405. return this;
  37406. }
  37407. /**
  37408. * Returns the current rolloff factor.
  37409. *
  37410. * @return {number} The rolloff factor.
  37411. */
  37412. getRolloffFactor() {
  37413. return this.panner.rolloffFactor;
  37414. }
  37415. /**
  37416. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37417. *
  37418. * @param {number} value - The rolloff factor.
  37419. * @return {PositionalAudio} A reference to this instance.
  37420. */
  37421. setRolloffFactor( value ) {
  37422. this.panner.rolloffFactor = value;
  37423. return this;
  37424. }
  37425. /**
  37426. * Returns the current distance model.
  37427. *
  37428. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37429. */
  37430. getDistanceModel() {
  37431. return this.panner.distanceModel;
  37432. }
  37433. /**
  37434. * Defines which algorithm to use to reduce the volume of the audio source
  37435. * as it moves away from the listener.
  37436. *
  37437. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37438. * for more details.
  37439. *
  37440. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37441. * @return {PositionalAudio} A reference to this instance.
  37442. */
  37443. setDistanceModel( value ) {
  37444. this.panner.distanceModel = value;
  37445. return this;
  37446. }
  37447. /**
  37448. * Returns the current max distance.
  37449. *
  37450. * @return {number} The max distance.
  37451. */
  37452. getMaxDistance() {
  37453. return this.panner.maxDistance;
  37454. }
  37455. /**
  37456. * Defines the maximum distance between the audio source and the listener,
  37457. * after which the volume is not reduced any further.
  37458. *
  37459. * This value is used only by the `linear` distance model.
  37460. *
  37461. * @param {number} value - The max distance.
  37462. * @return {PositionalAudio} A reference to this instance.
  37463. */
  37464. setMaxDistance( value ) {
  37465. this.panner.maxDistance = value;
  37466. return this;
  37467. }
  37468. /**
  37469. * Sets the directional cone in which the audio can be listened.
  37470. *
  37471. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37472. * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter.
  37473. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37474. * @return {PositionalAudio} A reference to this instance.
  37475. */
  37476. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37477. this.panner.coneInnerAngle = coneInnerAngle;
  37478. this.panner.coneOuterAngle = coneOuterAngle;
  37479. this.panner.coneOuterGain = coneOuterGain;
  37480. return this;
  37481. }
  37482. updateMatrixWorld( force ) {
  37483. super.updateMatrixWorld( force );
  37484. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37485. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37486. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37487. const panner = this.panner;
  37488. if ( panner.positionX ) {
  37489. // code path for Chrome and Firefox (see #14393)
  37490. const endTime = this.context.currentTime + this.listener.timeDelta;
  37491. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37492. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37493. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37494. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37495. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37496. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37497. } else {
  37498. panner.setPosition( _position.x, _position.y, _position.z );
  37499. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37500. }
  37501. }
  37502. }
  37503. /**
  37504. * This class can be used to analyse audio data.
  37505. *
  37506. * ```js
  37507. * // create an AudioListener and add it to the camera
  37508. * const listener = new THREE.AudioListener();
  37509. * camera.add( listener );
  37510. *
  37511. * // create an Audio source
  37512. * const sound = new THREE.Audio( listener );
  37513. *
  37514. * // load a sound and set it as the Audio object's buffer
  37515. * const audioLoader = new THREE.AudioLoader();
  37516. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37517. * sound.setBuffer( buffer );
  37518. * sound.setLoop(true);
  37519. * sound.setVolume(0.5);
  37520. * sound.play();
  37521. * });
  37522. *
  37523. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37524. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37525. *
  37526. * // get the average frequency of the sound
  37527. * const data = analyser.getAverageFrequency();
  37528. * ```
  37529. */
  37530. class AudioAnalyser {
  37531. /**
  37532. * Constructs a new audio analyzer.
  37533. *
  37534. * @param {Audio} audio - The audio to analyze.
  37535. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37536. */
  37537. constructor( audio, fftSize = 2048 ) {
  37538. /**
  37539. * The global audio listener.
  37540. *
  37541. * @type {AnalyserNode}
  37542. */
  37543. this.analyser = audio.context.createAnalyser();
  37544. this.analyser.fftSize = fftSize;
  37545. /**
  37546. * Holds the analyzed data.
  37547. *
  37548. * @type {Uint8Array}
  37549. */
  37550. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37551. audio.getOutput().connect( this.analyser );
  37552. }
  37553. /**
  37554. * Returns an array with frequency data of the audio.
  37555. *
  37556. * Each item in the array represents the decibel value for a specific frequency.
  37557. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37558. * For example, for 48000 sample rate, the last item of the array will represent
  37559. * the decibel value for 24000 Hz.
  37560. *
  37561. * @return {Uint8Array} The frequency data.
  37562. */
  37563. getFrequencyData() {
  37564. this.analyser.getByteFrequencyData( this.data );
  37565. return this.data;
  37566. }
  37567. /**
  37568. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37569. *
  37570. * @return {number} The average frequency.
  37571. */
  37572. getAverageFrequency() {
  37573. let value = 0;
  37574. const data = this.getFrequencyData();
  37575. for ( let i = 0; i < data.length; i ++ ) {
  37576. value += data[ i ];
  37577. }
  37578. return value / data.length;
  37579. }
  37580. }
  37581. /**
  37582. * Buffered scene graph property that allows weighted accumulation; used internally.
  37583. */
  37584. class PropertyMixer {
  37585. /**
  37586. * Constructs a new property mixer.
  37587. *
  37588. * @param {PropertyBinding} binding - The property binding.
  37589. * @param {string} typeName - The keyframe track type name.
  37590. * @param {number} valueSize - The keyframe track value size.
  37591. */
  37592. constructor( binding, typeName, valueSize ) {
  37593. /**
  37594. * The property binding.
  37595. *
  37596. * @type {PropertyBinding}
  37597. */
  37598. this.binding = binding;
  37599. /**
  37600. * The keyframe track value size.
  37601. *
  37602. * @type {number}
  37603. */
  37604. this.valueSize = valueSize;
  37605. let mixFunction,
  37606. mixFunctionAdditive,
  37607. setIdentity;
  37608. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37609. //
  37610. // interpolators can use .buffer as their .result
  37611. // the data then goes to 'incoming'
  37612. //
  37613. // 'accu0' and 'accu1' are used frame-interleaved for
  37614. // the cumulative result and are compared to detect
  37615. // changes
  37616. //
  37617. // 'orig' stores the original state of the property
  37618. //
  37619. // 'add' is used for additive cumulative results
  37620. //
  37621. // 'work' is optional and is only present for quaternion types. It is used
  37622. // to store intermediate quaternion multiplication results
  37623. switch ( typeName ) {
  37624. case 'quaternion':
  37625. mixFunction = this._slerp;
  37626. mixFunctionAdditive = this._slerpAdditive;
  37627. setIdentity = this._setAdditiveIdentityQuaternion;
  37628. this.buffer = new Float64Array( valueSize * 6 );
  37629. this._workIndex = 5;
  37630. break;
  37631. case 'string':
  37632. case 'bool':
  37633. mixFunction = this._select;
  37634. // Use the regular mix function and for additive on these types,
  37635. // additive is not relevant for non-numeric types
  37636. mixFunctionAdditive = this._select;
  37637. setIdentity = this._setAdditiveIdentityOther;
  37638. this.buffer = new Array( valueSize * 5 );
  37639. break;
  37640. default:
  37641. mixFunction = this._lerp;
  37642. mixFunctionAdditive = this._lerpAdditive;
  37643. setIdentity = this._setAdditiveIdentityNumeric;
  37644. this.buffer = new Float64Array( valueSize * 5 );
  37645. }
  37646. this._mixBufferRegion = mixFunction;
  37647. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37648. this._setIdentity = setIdentity;
  37649. this._origIndex = 3;
  37650. this._addIndex = 4;
  37651. /**
  37652. * Accumulated weight of the property binding.
  37653. *
  37654. * @type {number}
  37655. * @default 0
  37656. */
  37657. this.cumulativeWeight = 0;
  37658. /**
  37659. * Accumulated additive weight of the property binding.
  37660. *
  37661. * @type {number}
  37662. * @default 0
  37663. */
  37664. this.cumulativeWeightAdditive = 0;
  37665. /**
  37666. * Number of active keyframe tracks currently using this property binding.
  37667. *
  37668. * @type {number}
  37669. * @default 0
  37670. */
  37671. this.useCount = 0;
  37672. /**
  37673. * Number of keyframe tracks referencing this property binding.
  37674. *
  37675. * @type {number}
  37676. * @default 0
  37677. */
  37678. this.referenceCount = 0;
  37679. }
  37680. /**
  37681. * Accumulates data in the `incoming` region into `accu<i>`.
  37682. *
  37683. * @param {number} accuIndex - The accumulation index.
  37684. * @param {number} weight - The weight.
  37685. */
  37686. accumulate( accuIndex, weight ) {
  37687. // note: happily accumulating nothing when weight = 0, the caller knows
  37688. // the weight and shouldn't have made the call in the first place
  37689. const buffer = this.buffer,
  37690. stride = this.valueSize,
  37691. offset = accuIndex * stride + stride;
  37692. let currentWeight = this.cumulativeWeight;
  37693. if ( currentWeight === 0 ) {
  37694. // accuN := incoming * weight
  37695. for ( let i = 0; i !== stride; ++ i ) {
  37696. buffer[ offset + i ] = buffer[ i ];
  37697. }
  37698. currentWeight = weight;
  37699. } else {
  37700. // accuN := accuN + incoming * weight
  37701. currentWeight += weight;
  37702. const mix = weight / currentWeight;
  37703. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37704. }
  37705. this.cumulativeWeight = currentWeight;
  37706. }
  37707. /**
  37708. * Accumulates data in the `incoming` region into `add`.
  37709. *
  37710. * @param {number} weight - The weight.
  37711. */
  37712. accumulateAdditive( weight ) {
  37713. const buffer = this.buffer,
  37714. stride = this.valueSize,
  37715. offset = stride * this._addIndex;
  37716. if ( this.cumulativeWeightAdditive === 0 ) {
  37717. // add = identity
  37718. this._setIdentity();
  37719. }
  37720. // add := add + incoming * weight
  37721. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37722. this.cumulativeWeightAdditive += weight;
  37723. }
  37724. /**
  37725. * Applies the state of `accu<i>` to the binding when accus differ.
  37726. *
  37727. * @param {number} accuIndex - The accumulation index.
  37728. */
  37729. apply( accuIndex ) {
  37730. const stride = this.valueSize,
  37731. buffer = this.buffer,
  37732. offset = accuIndex * stride + stride,
  37733. weight = this.cumulativeWeight,
  37734. weightAdditive = this.cumulativeWeightAdditive,
  37735. binding = this.binding;
  37736. this.cumulativeWeight = 0;
  37737. this.cumulativeWeightAdditive = 0;
  37738. if ( weight < 1 ) {
  37739. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37740. const originalValueOffset = stride * this._origIndex;
  37741. this._mixBufferRegion(
  37742. buffer, offset, originalValueOffset, 1 - weight, stride );
  37743. }
  37744. if ( weightAdditive > 0 ) {
  37745. // accuN := accuN + additive accuN
  37746. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37747. }
  37748. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37749. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37750. // value has changed -> update scene graph
  37751. binding.setValue( buffer, offset );
  37752. break;
  37753. }
  37754. }
  37755. }
  37756. /**
  37757. * Remembers the state of the bound property and copy it to both accus.
  37758. */
  37759. saveOriginalState() {
  37760. const binding = this.binding;
  37761. const buffer = this.buffer,
  37762. stride = this.valueSize,
  37763. originalValueOffset = stride * this._origIndex;
  37764. binding.getValue( buffer, originalValueOffset );
  37765. // accu[0..1] := orig -- initially detect changes against the original
  37766. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37767. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37768. }
  37769. // Add to identity for additive
  37770. this._setIdentity();
  37771. this.cumulativeWeight = 0;
  37772. this.cumulativeWeightAdditive = 0;
  37773. }
  37774. /**
  37775. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37776. */
  37777. restoreOriginalState() {
  37778. const originalValueOffset = this.valueSize * 3;
  37779. this.binding.setValue( this.buffer, originalValueOffset );
  37780. }
  37781. // internals
  37782. _setAdditiveIdentityNumeric() {
  37783. const startIndex = this._addIndex * this.valueSize;
  37784. const endIndex = startIndex + this.valueSize;
  37785. for ( let i = startIndex; i < endIndex; i ++ ) {
  37786. this.buffer[ i ] = 0;
  37787. }
  37788. }
  37789. _setAdditiveIdentityQuaternion() {
  37790. this._setAdditiveIdentityNumeric();
  37791. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37792. }
  37793. _setAdditiveIdentityOther() {
  37794. const startIndex = this._origIndex * this.valueSize;
  37795. const targetIndex = this._addIndex * this.valueSize;
  37796. for ( let i = 0; i < this.valueSize; i ++ ) {
  37797. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37798. }
  37799. }
  37800. // mix functions
  37801. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37802. if ( t >= 0.5 ) {
  37803. for ( let i = 0; i !== stride; ++ i ) {
  37804. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37805. }
  37806. }
  37807. }
  37808. _slerp( buffer, dstOffset, srcOffset, t ) {
  37809. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37810. }
  37811. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37812. const workOffset = this._workIndex * stride;
  37813. // Store result in intermediate buffer offset
  37814. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37815. // Slerp to the intermediate result
  37816. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37817. }
  37818. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37819. const s = 1 - t;
  37820. for ( let i = 0; i !== stride; ++ i ) {
  37821. const j = dstOffset + i;
  37822. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37823. }
  37824. }
  37825. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37826. for ( let i = 0; i !== stride; ++ i ) {
  37827. const j = dstOffset + i;
  37828. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37829. }
  37830. }
  37831. }
  37832. // Characters [].:/ are reserved for track binding syntax.
  37833. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37834. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37835. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37836. // only latin characters, and the unicode \p{L} is not yet supported. So
  37837. // instead, we exclude reserved characters and match everything else.
  37838. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37839. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37840. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37841. // be matched to parse the rest of the track name.
  37842. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37843. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37844. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37845. // Object on target node, and accessor. May not contain reserved
  37846. // characters. Accessor may contain any character except closing bracket.
  37847. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37848. // Property and accessor. May not contain reserved characters. Accessor may
  37849. // contain any non-bracket characters.
  37850. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37851. const _trackRe = new RegExp( ''
  37852. + '^'
  37853. + _directoryRe
  37854. + _nodeRe
  37855. + _objectRe
  37856. + _propertyRe
  37857. + '$'
  37858. );
  37859. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37860. class Composite {
  37861. constructor( targetGroup, path, optionalParsedPath ) {
  37862. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37863. this._targetGroup = targetGroup;
  37864. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37865. }
  37866. getValue( array, offset ) {
  37867. this.bind(); // bind all binding
  37868. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37869. binding = this._bindings[ firstValidIndex ];
  37870. // and only call .getValue on the first
  37871. if ( binding !== undefined ) binding.getValue( array, offset );
  37872. }
  37873. setValue( array, offset ) {
  37874. const bindings = this._bindings;
  37875. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37876. bindings[ i ].setValue( array, offset );
  37877. }
  37878. }
  37879. bind() {
  37880. const bindings = this._bindings;
  37881. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37882. bindings[ i ].bind();
  37883. }
  37884. }
  37885. unbind() {
  37886. const bindings = this._bindings;
  37887. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37888. bindings[ i ].unbind();
  37889. }
  37890. }
  37891. }
  37892. // Note: This class uses a State pattern on a per-method basis:
  37893. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37894. // prototype version of these methods with one that represents
  37895. // the bound state. When the property is not found, the methods
  37896. // become no-ops.
  37897. /**
  37898. * This holds a reference to a real property in the scene graph; used internally.
  37899. */
  37900. class PropertyBinding {
  37901. /**
  37902. * Constructs a new property binding.
  37903. *
  37904. * @param {Object} rootNode - The root node.
  37905. * @param {string} path - The path.
  37906. * @param {?Object} [parsedPath] - The parsed path.
  37907. */
  37908. constructor( rootNode, path, parsedPath ) {
  37909. /**
  37910. * The object path to the animated property.
  37911. *
  37912. * @type {string}
  37913. */
  37914. this.path = path;
  37915. /**
  37916. * An object holding information about the path.
  37917. *
  37918. * @type {Object}
  37919. */
  37920. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37921. /**
  37922. * The object owns the animated property.
  37923. *
  37924. * @type {?Object}
  37925. */
  37926. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37927. /**
  37928. * The root node.
  37929. *
  37930. * @type {Object3D|Skeleton}
  37931. */
  37932. this.rootNode = rootNode;
  37933. // initial state of these methods that calls 'bind'
  37934. this.getValue = this._getValue_unbound;
  37935. this.setValue = this._setValue_unbound;
  37936. }
  37937. /**
  37938. * Factory method for creating a property binding from the given parameters.
  37939. *
  37940. * @static
  37941. * @param {Object} root - The root node.
  37942. * @param {string} path - The path.
  37943. * @param {?Object} [parsedPath] - The parsed path.
  37944. * @return {PropertyBinding|Composite} The created property binding or composite.
  37945. */
  37946. static create( root, path, parsedPath ) {
  37947. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37948. return new PropertyBinding( root, path, parsedPath );
  37949. } else {
  37950. return new PropertyBinding.Composite( root, path, parsedPath );
  37951. }
  37952. }
  37953. /**
  37954. * Replaces spaces with underscores and removes unsupported characters from
  37955. * node names, to ensure compatibility with parseTrackName().
  37956. *
  37957. * @param {string} name - Node name to be sanitized.
  37958. * @return {string} The sanitized node name.
  37959. */
  37960. static sanitizeNodeName( name ) {
  37961. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37962. }
  37963. /**
  37964. * Parses the given track name (an object path to an animated property) and
  37965. * returns an object with information about the path. Matches strings in the following forms:
  37966. *
  37967. * - nodeName.property
  37968. * - nodeName.property[accessor]
  37969. * - nodeName.material.property[accessor]
  37970. * - uuid.property[accessor]
  37971. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37972. * - parentName/nodeName.property
  37973. * - parentName/parentName/nodeName.property[index]
  37974. * - .bone[Armature.DEF_cog].position
  37975. * - scene:helium_balloon_model:helium_balloon_model.position
  37976. *
  37977. * @static
  37978. * @param {string} trackName - The track name to parse.
  37979. * @return {Object} The parsed track name as an object.
  37980. */
  37981. static parseTrackName( trackName ) {
  37982. const matches = _trackRe.exec( trackName );
  37983. if ( matches === null ) {
  37984. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37985. }
  37986. const results = {
  37987. // directoryName: matches[ 1 ], // (tschw) currently unused
  37988. nodeName: matches[ 2 ],
  37989. objectName: matches[ 3 ],
  37990. objectIndex: matches[ 4 ],
  37991. propertyName: matches[ 5 ], // required
  37992. propertyIndex: matches[ 6 ]
  37993. };
  37994. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37995. if ( lastDot !== undefined && lastDot !== -1 ) {
  37996. const objectName = results.nodeName.substring( lastDot + 1 );
  37997. // Object names must be checked against an allowlist. Otherwise, there
  37998. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37999. // 'bar' could be the objectName, or part of a nodeName (which can
  38000. // include '.' characters).
  38001. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38002. results.nodeName = results.nodeName.substring( 0, lastDot );
  38003. results.objectName = objectName;
  38004. }
  38005. }
  38006. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38007. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38008. }
  38009. return results;
  38010. }
  38011. /**
  38012. * Searches for a node in the hierarchy of the given root object by the given
  38013. * node name.
  38014. *
  38015. * @static
  38016. * @param {Object} root - The root object.
  38017. * @param {string|number} nodeName - The name of the node.
  38018. * @return {?Object} The found node. Returns `null` if no object was found.
  38019. */
  38020. static findNode( root, nodeName ) {
  38021. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38022. return root;
  38023. }
  38024. // search into skeleton bones.
  38025. if ( root.skeleton ) {
  38026. const bone = root.skeleton.getBoneByName( nodeName );
  38027. if ( bone !== undefined ) {
  38028. return bone;
  38029. }
  38030. }
  38031. // search into node subtree.
  38032. if ( root.children ) {
  38033. const searchNodeSubtree = function ( children ) {
  38034. for ( let i = 0; i < children.length; i ++ ) {
  38035. const childNode = children[ i ];
  38036. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38037. return childNode;
  38038. }
  38039. const result = searchNodeSubtree( childNode.children );
  38040. if ( result ) return result;
  38041. }
  38042. return null;
  38043. };
  38044. const subTreeNode = searchNodeSubtree( root.children );
  38045. if ( subTreeNode ) {
  38046. return subTreeNode;
  38047. }
  38048. }
  38049. return null;
  38050. }
  38051. // these are used to "bind" a nonexistent property
  38052. _getValue_unavailable() {}
  38053. _setValue_unavailable() {}
  38054. // Getters
  38055. _getValue_direct( buffer, offset ) {
  38056. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38057. }
  38058. _getValue_array( buffer, offset ) {
  38059. const source = this.resolvedProperty;
  38060. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38061. buffer[ offset ++ ] = source[ i ];
  38062. }
  38063. }
  38064. _getValue_arrayElement( buffer, offset ) {
  38065. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38066. }
  38067. _getValue_toArray( buffer, offset ) {
  38068. this.resolvedProperty.toArray( buffer, offset );
  38069. }
  38070. // Direct
  38071. _setValue_direct( buffer, offset ) {
  38072. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38073. }
  38074. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38075. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38076. this.targetObject.needsUpdate = true;
  38077. }
  38078. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38079. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38080. this.targetObject.matrixWorldNeedsUpdate = true;
  38081. }
  38082. // EntireArray
  38083. _setValue_array( buffer, offset ) {
  38084. const dest = this.resolvedProperty;
  38085. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38086. dest[ i ] = buffer[ offset ++ ];
  38087. }
  38088. }
  38089. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38090. const dest = this.resolvedProperty;
  38091. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38092. dest[ i ] = buffer[ offset ++ ];
  38093. }
  38094. this.targetObject.needsUpdate = true;
  38095. }
  38096. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38097. const dest = this.resolvedProperty;
  38098. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38099. dest[ i ] = buffer[ offset ++ ];
  38100. }
  38101. this.targetObject.matrixWorldNeedsUpdate = true;
  38102. }
  38103. // ArrayElement
  38104. _setValue_arrayElement( buffer, offset ) {
  38105. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38106. }
  38107. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38108. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38109. this.targetObject.needsUpdate = true;
  38110. }
  38111. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38112. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38113. this.targetObject.matrixWorldNeedsUpdate = true;
  38114. }
  38115. // HasToFromArray
  38116. _setValue_fromArray( buffer, offset ) {
  38117. this.resolvedProperty.fromArray( buffer, offset );
  38118. }
  38119. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38120. this.resolvedProperty.fromArray( buffer, offset );
  38121. this.targetObject.needsUpdate = true;
  38122. }
  38123. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38124. this.resolvedProperty.fromArray( buffer, offset );
  38125. this.targetObject.matrixWorldNeedsUpdate = true;
  38126. }
  38127. _getValue_unbound( targetArray, offset ) {
  38128. this.bind();
  38129. this.getValue( targetArray, offset );
  38130. }
  38131. _setValue_unbound( sourceArray, offset ) {
  38132. this.bind();
  38133. this.setValue( sourceArray, offset );
  38134. }
  38135. /**
  38136. * Creates a getter / setter pair for the property tracked by this binding.
  38137. */
  38138. bind() {
  38139. let targetObject = this.node;
  38140. const parsedPath = this.parsedPath;
  38141. const objectName = parsedPath.objectName;
  38142. const propertyName = parsedPath.propertyName;
  38143. let propertyIndex = parsedPath.propertyIndex;
  38144. if ( ! targetObject ) {
  38145. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38146. this.node = targetObject;
  38147. }
  38148. // set fail state so we can just 'return' on error
  38149. this.getValue = this._getValue_unavailable;
  38150. this.setValue = this._setValue_unavailable;
  38151. // ensure there is a value node
  38152. if ( ! targetObject ) {
  38153. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38154. return;
  38155. }
  38156. if ( objectName ) {
  38157. let objectIndex = parsedPath.objectIndex;
  38158. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38159. switch ( objectName ) {
  38160. case 'materials':
  38161. if ( ! targetObject.material ) {
  38162. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38163. return;
  38164. }
  38165. if ( ! targetObject.material.materials ) {
  38166. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38167. return;
  38168. }
  38169. targetObject = targetObject.material.materials;
  38170. break;
  38171. case 'bones':
  38172. if ( ! targetObject.skeleton ) {
  38173. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38174. return;
  38175. }
  38176. // potential future optimization: skip this if propertyIndex is already an integer
  38177. // and convert the integer string to a true integer.
  38178. targetObject = targetObject.skeleton.bones;
  38179. // support resolving morphTarget names into indices.
  38180. for ( let i = 0; i < targetObject.length; i ++ ) {
  38181. if ( targetObject[ i ].name === objectIndex ) {
  38182. objectIndex = i;
  38183. break;
  38184. }
  38185. }
  38186. break;
  38187. case 'map':
  38188. if ( 'map' in targetObject ) {
  38189. targetObject = targetObject.map;
  38190. break;
  38191. }
  38192. if ( ! targetObject.material ) {
  38193. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38194. return;
  38195. }
  38196. if ( ! targetObject.material.map ) {
  38197. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38198. return;
  38199. }
  38200. targetObject = targetObject.material.map;
  38201. break;
  38202. default:
  38203. if ( targetObject[ objectName ] === undefined ) {
  38204. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38205. return;
  38206. }
  38207. targetObject = targetObject[ objectName ];
  38208. }
  38209. if ( objectIndex !== undefined ) {
  38210. if ( targetObject[ objectIndex ] === undefined ) {
  38211. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38212. return;
  38213. }
  38214. targetObject = targetObject[ objectIndex ];
  38215. }
  38216. }
  38217. // resolve property
  38218. const nodeProperty = targetObject[ propertyName ];
  38219. if ( nodeProperty === undefined ) {
  38220. const nodeName = parsedPath.nodeName;
  38221. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38222. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38223. return;
  38224. }
  38225. // determine versioning scheme
  38226. let versioning = this.Versioning.None;
  38227. this.targetObject = targetObject;
  38228. if ( targetObject.isMaterial === true ) {
  38229. versioning = this.Versioning.NeedsUpdate;
  38230. } else if ( targetObject.isObject3D === true ) {
  38231. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38232. }
  38233. // determine how the property gets bound
  38234. let bindingType = this.BindingType.Direct;
  38235. if ( propertyIndex !== undefined ) {
  38236. // access a sub element of the property array (only primitives are supported right now)
  38237. if ( propertyName === 'morphTargetInfluences' ) {
  38238. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38239. // support resolving morphTarget names into indices.
  38240. if ( ! targetObject.geometry ) {
  38241. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38242. return;
  38243. }
  38244. if ( ! targetObject.geometry.morphAttributes ) {
  38245. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38246. return;
  38247. }
  38248. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38249. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38250. }
  38251. }
  38252. bindingType = this.BindingType.ArrayElement;
  38253. this.resolvedProperty = nodeProperty;
  38254. this.propertyIndex = propertyIndex;
  38255. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38256. // must use copy for Object3D.Euler/Quaternion
  38257. bindingType = this.BindingType.HasFromToArray;
  38258. this.resolvedProperty = nodeProperty;
  38259. } else if ( Array.isArray( nodeProperty ) ) {
  38260. bindingType = this.BindingType.EntireArray;
  38261. this.resolvedProperty = nodeProperty;
  38262. } else {
  38263. this.propertyName = propertyName;
  38264. }
  38265. // select getter / setter
  38266. this.getValue = this.GetterByBindingType[ bindingType ];
  38267. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38268. }
  38269. /**
  38270. * Unbinds the property.
  38271. */
  38272. unbind() {
  38273. this.node = null;
  38274. // back to the prototype version of getValue / setValue
  38275. // note: avoiding to mutate the shape of 'this' via 'delete'
  38276. this.getValue = this._getValue_unbound;
  38277. this.setValue = this._setValue_unbound;
  38278. }
  38279. }
  38280. PropertyBinding.Composite = Composite;
  38281. PropertyBinding.prototype.BindingType = {
  38282. Direct: 0,
  38283. EntireArray: 1,
  38284. ArrayElement: 2,
  38285. HasFromToArray: 3
  38286. };
  38287. PropertyBinding.prototype.Versioning = {
  38288. None: 0,
  38289. NeedsUpdate: 1,
  38290. MatrixWorldNeedsUpdate: 2
  38291. };
  38292. PropertyBinding.prototype.GetterByBindingType = [
  38293. PropertyBinding.prototype._getValue_direct,
  38294. PropertyBinding.prototype._getValue_array,
  38295. PropertyBinding.prototype._getValue_arrayElement,
  38296. PropertyBinding.prototype._getValue_toArray,
  38297. ];
  38298. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38299. [
  38300. // Direct
  38301. PropertyBinding.prototype._setValue_direct,
  38302. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38303. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38304. ], [
  38305. // EntireArray
  38306. PropertyBinding.prototype._setValue_array,
  38307. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38308. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38309. ], [
  38310. // ArrayElement
  38311. PropertyBinding.prototype._setValue_arrayElement,
  38312. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38313. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38314. ], [
  38315. // HasToFromArray
  38316. PropertyBinding.prototype._setValue_fromArray,
  38317. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38318. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38319. ]
  38320. ];
  38321. /**
  38322. * A group of objects that receives a shared animation state.
  38323. *
  38324. * Usage:
  38325. *
  38326. * - Add objects you would otherwise pass as 'root' to the
  38327. * constructor or the .clipAction method of AnimationMixer.
  38328. * - Instead pass this object as 'root'.
  38329. * - You can also add and remove objects later when the mixer is running.
  38330. *
  38331. * Note:
  38332. *
  38333. * - Objects of this class appear as one object to the mixer,
  38334. * so cache control of the individual objects must be done on the group.
  38335. *
  38336. * Limitation:
  38337. *
  38338. * - The animated properties must be compatible among the all objects in the group.
  38339. * - A single property can either be controlled through a target group or directly, but not both.
  38340. */
  38341. class AnimationObjectGroup {
  38342. /**
  38343. * Constructs a new animation group.
  38344. *
  38345. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38346. */
  38347. constructor() {
  38348. /**
  38349. * This flag can be used for type testing.
  38350. *
  38351. * @type {boolean}
  38352. * @readonly
  38353. * @default true
  38354. */
  38355. this.isAnimationObjectGroup = true;
  38356. /**
  38357. * The UUID of the 3D object.
  38358. *
  38359. * @type {string}
  38360. * @readonly
  38361. */
  38362. this.uuid = generateUUID();
  38363. // cached objects followed by the active ones
  38364. this._objects = Array.prototype.slice.call( arguments );
  38365. this.nCachedObjects_ = 0; // threshold
  38366. // note: read by PropertyBinding.Composite
  38367. const indices = {};
  38368. this._indicesByUUID = indices; // for bookkeeping
  38369. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38370. indices[ arguments[ i ].uuid ] = i;
  38371. }
  38372. this._paths = []; // inside: string
  38373. this._parsedPaths = []; // inside: { we don't care, here }
  38374. this._bindings = []; // inside: Array< PropertyBinding >
  38375. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38376. const scope = this;
  38377. this.stats = {
  38378. objects: {
  38379. get total() {
  38380. return scope._objects.length;
  38381. },
  38382. get inUse() {
  38383. return this.total - scope.nCachedObjects_;
  38384. }
  38385. },
  38386. get bindingsPerObject() {
  38387. return scope._bindings.length;
  38388. }
  38389. };
  38390. }
  38391. /**
  38392. * Adds an arbitrary number of objects to this animation group.
  38393. *
  38394. * @param {...Object3D} arguments - The 3D objects to add.
  38395. */
  38396. add() {
  38397. const objects = this._objects,
  38398. indicesByUUID = this._indicesByUUID,
  38399. paths = this._paths,
  38400. parsedPaths = this._parsedPaths,
  38401. bindings = this._bindings,
  38402. nBindings = bindings.length;
  38403. let knownObject = undefined,
  38404. nObjects = objects.length,
  38405. nCachedObjects = this.nCachedObjects_;
  38406. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38407. const object = arguments[ i ],
  38408. uuid = object.uuid;
  38409. let index = indicesByUUID[ uuid ];
  38410. if ( index === undefined ) {
  38411. // unknown object -> add it to the ACTIVE region
  38412. index = nObjects ++;
  38413. indicesByUUID[ uuid ] = index;
  38414. objects.push( object );
  38415. // accounting is done, now do the same for all bindings
  38416. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38417. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38418. }
  38419. } else if ( index < nCachedObjects ) {
  38420. knownObject = objects[ index ];
  38421. // move existing object to the ACTIVE region
  38422. const firstActiveIndex = -- nCachedObjects,
  38423. lastCachedObject = objects[ firstActiveIndex ];
  38424. indicesByUUID[ lastCachedObject.uuid ] = index;
  38425. objects[ index ] = lastCachedObject;
  38426. indicesByUUID[ uuid ] = firstActiveIndex;
  38427. objects[ firstActiveIndex ] = object;
  38428. // accounting is done, now do the same for all bindings
  38429. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38430. const bindingsForPath = bindings[ j ],
  38431. lastCached = bindingsForPath[ firstActiveIndex ];
  38432. let binding = bindingsForPath[ index ];
  38433. bindingsForPath[ index ] = lastCached;
  38434. if ( binding === undefined ) {
  38435. // since we do not bother to create new bindings
  38436. // for objects that are cached, the binding may
  38437. // or may not exist
  38438. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38439. }
  38440. bindingsForPath[ firstActiveIndex ] = binding;
  38441. }
  38442. } else if ( objects[ index ] !== knownObject ) {
  38443. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38444. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38445. } // else the object is already where we want it to be
  38446. } // for arguments
  38447. this.nCachedObjects_ = nCachedObjects;
  38448. }
  38449. /**
  38450. * Removes an arbitrary number of objects to this animation group
  38451. *
  38452. * @param {...Object3D} arguments - The 3D objects to remove.
  38453. */
  38454. remove() {
  38455. const objects = this._objects,
  38456. indicesByUUID = this._indicesByUUID,
  38457. bindings = this._bindings,
  38458. nBindings = bindings.length;
  38459. let nCachedObjects = this.nCachedObjects_;
  38460. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38461. const object = arguments[ i ],
  38462. uuid = object.uuid,
  38463. index = indicesByUUID[ uuid ];
  38464. if ( index !== undefined && index >= nCachedObjects ) {
  38465. // move existing object into the CACHED region
  38466. const lastCachedIndex = nCachedObjects ++,
  38467. firstActiveObject = objects[ lastCachedIndex ];
  38468. indicesByUUID[ firstActiveObject.uuid ] = index;
  38469. objects[ index ] = firstActiveObject;
  38470. indicesByUUID[ uuid ] = lastCachedIndex;
  38471. objects[ lastCachedIndex ] = object;
  38472. // accounting is done, now do the same for all bindings
  38473. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38474. const bindingsForPath = bindings[ j ],
  38475. firstActive = bindingsForPath[ lastCachedIndex ],
  38476. binding = bindingsForPath[ index ];
  38477. bindingsForPath[ index ] = firstActive;
  38478. bindingsForPath[ lastCachedIndex ] = binding;
  38479. }
  38480. }
  38481. } // for arguments
  38482. this.nCachedObjects_ = nCachedObjects;
  38483. }
  38484. /**
  38485. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38486. *
  38487. * @param {...Object3D} arguments - The 3D objects to uncache.
  38488. */
  38489. uncache() {
  38490. const objects = this._objects,
  38491. indicesByUUID = this._indicesByUUID,
  38492. bindings = this._bindings,
  38493. nBindings = bindings.length;
  38494. let nCachedObjects = this.nCachedObjects_,
  38495. nObjects = objects.length;
  38496. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38497. const object = arguments[ i ],
  38498. uuid = object.uuid,
  38499. index = indicesByUUID[ uuid ];
  38500. if ( index !== undefined ) {
  38501. delete indicesByUUID[ uuid ];
  38502. if ( index < nCachedObjects ) {
  38503. // object is cached, shrink the CACHED region
  38504. const firstActiveIndex = -- nCachedObjects,
  38505. lastCachedObject = objects[ firstActiveIndex ],
  38506. lastIndex = -- nObjects,
  38507. lastObject = objects[ lastIndex ];
  38508. // last cached object takes this object's place
  38509. indicesByUUID[ lastCachedObject.uuid ] = index;
  38510. objects[ index ] = lastCachedObject;
  38511. // last object goes to the activated slot and pop
  38512. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38513. objects[ firstActiveIndex ] = lastObject;
  38514. objects.pop();
  38515. // accounting is done, now do the same for all bindings
  38516. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38517. const bindingsForPath = bindings[ j ],
  38518. lastCached = bindingsForPath[ firstActiveIndex ],
  38519. last = bindingsForPath[ lastIndex ];
  38520. bindingsForPath[ index ] = lastCached;
  38521. bindingsForPath[ firstActiveIndex ] = last;
  38522. bindingsForPath.pop();
  38523. }
  38524. } else {
  38525. // object is active, just swap with the last and pop
  38526. const lastIndex = -- nObjects,
  38527. lastObject = objects[ lastIndex ];
  38528. if ( lastIndex > 0 ) {
  38529. indicesByUUID[ lastObject.uuid ] = index;
  38530. }
  38531. objects[ index ] = lastObject;
  38532. objects.pop();
  38533. // accounting is done, now do the same for all bindings
  38534. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38535. const bindingsForPath = bindings[ j ];
  38536. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38537. bindingsForPath.pop();
  38538. }
  38539. } // cached or active
  38540. } // if object is known
  38541. } // for arguments
  38542. this.nCachedObjects_ = nCachedObjects;
  38543. }
  38544. // Internal interface used by befriended PropertyBinding.Composite:
  38545. subscribe_( path, parsedPath ) {
  38546. // returns an array of bindings for the given path that is changed
  38547. // according to the contained objects in the group
  38548. const indicesByPath = this._bindingsIndicesByPath;
  38549. let index = indicesByPath[ path ];
  38550. const bindings = this._bindings;
  38551. if ( index !== undefined ) return bindings[ index ];
  38552. const paths = this._paths,
  38553. parsedPaths = this._parsedPaths,
  38554. objects = this._objects,
  38555. nObjects = objects.length,
  38556. nCachedObjects = this.nCachedObjects_,
  38557. bindingsForPath = new Array( nObjects );
  38558. index = bindings.length;
  38559. indicesByPath[ path ] = index;
  38560. paths.push( path );
  38561. parsedPaths.push( parsedPath );
  38562. bindings.push( bindingsForPath );
  38563. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38564. const object = objects[ i ];
  38565. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38566. }
  38567. return bindingsForPath;
  38568. }
  38569. unsubscribe_( path ) {
  38570. // tells the group to forget about a property path and no longer
  38571. // update the array previously obtained with 'subscribe_'
  38572. const indicesByPath = this._bindingsIndicesByPath,
  38573. index = indicesByPath[ path ];
  38574. if ( index !== undefined ) {
  38575. const paths = this._paths,
  38576. parsedPaths = this._parsedPaths,
  38577. bindings = this._bindings,
  38578. lastBindingsIndex = bindings.length - 1,
  38579. lastBindings = bindings[ lastBindingsIndex ],
  38580. lastBindingsPath = path[ lastBindingsIndex ];
  38581. indicesByPath[ lastBindingsPath ] = index;
  38582. bindings[ index ] = lastBindings;
  38583. bindings.pop();
  38584. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38585. parsedPaths.pop();
  38586. paths[ index ] = paths[ lastBindingsIndex ];
  38587. paths.pop();
  38588. }
  38589. }
  38590. }
  38591. /**
  38592. * An instance of `AnimationAction` schedules the playback of an animation which is
  38593. * stored in {@link AnimationClip}.
  38594. */
  38595. class AnimationAction {
  38596. /**
  38597. * Constructs a new animation action.
  38598. *
  38599. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38600. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38601. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38602. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38603. */
  38604. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38605. this._mixer = mixer;
  38606. this._clip = clip;
  38607. this._localRoot = localRoot;
  38608. /**
  38609. * Defines how the animation is blended/combined when two or more animations
  38610. * are simultaneously played.
  38611. *
  38612. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38613. */
  38614. this.blendMode = blendMode;
  38615. const tracks = clip.tracks,
  38616. nTracks = tracks.length,
  38617. interpolants = new Array( nTracks );
  38618. const interpolantSettings = {
  38619. endingStart: ZeroCurvatureEnding,
  38620. endingEnd: ZeroCurvatureEnding
  38621. };
  38622. for ( let i = 0; i !== nTracks; ++ i ) {
  38623. const interpolant = tracks[ i ].createInterpolant( null );
  38624. interpolants[ i ] = interpolant;
  38625. interpolant.settings = interpolantSettings;
  38626. }
  38627. this._interpolantSettings = interpolantSettings;
  38628. this._interpolants = interpolants; // bound by the mixer
  38629. // inside: PropertyMixer (managed by the mixer)
  38630. this._propertyBindings = new Array( nTracks );
  38631. this._cacheIndex = null; // for the memory manager
  38632. this._byClipCacheIndex = null; // for the memory manager
  38633. this._timeScaleInterpolant = null;
  38634. this._weightInterpolant = null;
  38635. /**
  38636. * The loop mode, set via {@link AnimationAction#setLoop}.
  38637. *
  38638. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38639. * @default LoopRepeat
  38640. */
  38641. this.loop = LoopRepeat;
  38642. this._loopCount = -1;
  38643. // global mixer time when the action is to be started
  38644. // it's set back to 'null' upon start of the action
  38645. this._startTime = null;
  38646. /**
  38647. * The local time of this action (in seconds, starting with `0`).
  38648. *
  38649. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38650. * loop state).
  38651. *
  38652. * @type {number}
  38653. * @default Infinity
  38654. */
  38655. this.time = 0;
  38656. /**
  38657. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38658. * animation to pause. Negative values cause the animation to play backwards.
  38659. *
  38660. * @type {number}
  38661. * @default 1
  38662. */
  38663. this.timeScale = 1;
  38664. this._effectiveTimeScale = 1;
  38665. /**
  38666. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38667. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38668. * several actions.
  38669. *
  38670. * @type {number}
  38671. * @default 1
  38672. */
  38673. this.weight = 1;
  38674. this._effectiveWeight = 1;
  38675. /**
  38676. * The number of repetitions of the performed clip over the course of this action.
  38677. * Can be set via {@link AnimationAction#setLoop}.
  38678. *
  38679. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38680. * `THREE:LoopOnce`.
  38681. *
  38682. * @type {number}
  38683. * @default Infinity
  38684. */
  38685. this.repetitions = Infinity;
  38686. /**
  38687. * If set to `true`, the playback of the action is paused.
  38688. *
  38689. * @type {boolean}
  38690. * @default false
  38691. */
  38692. this.paused = false;
  38693. /**
  38694. * If set to `false`, the action is disabled so it has no impact.
  38695. *
  38696. * When the action is re-enabled, the animation continues from its current
  38697. * time (setting `enabled` to `false` doesn't reset the action).
  38698. *
  38699. * @type {boolean}
  38700. * @default true
  38701. */
  38702. this.enabled = true;
  38703. /**
  38704. * If set to true the animation will automatically be paused on its last frame.
  38705. *
  38706. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38707. * to `false` when the last loop of the action has finished, so that this action has
  38708. * no further impact.
  38709. *
  38710. * Note: This member has no impact if the action is interrupted (it
  38711. * has only an effect if its last loop has really finished).
  38712. *
  38713. * @type {boolean}
  38714. * @default false
  38715. */
  38716. this.clampWhenFinished = false;
  38717. /**
  38718. * Enables smooth interpolation without separate clips for start, loop and end.
  38719. *
  38720. * @type {boolean}
  38721. * @default true
  38722. */
  38723. this.zeroSlopeAtStart = true;
  38724. /**
  38725. * Enables smooth interpolation without separate clips for start, loop and end.
  38726. *
  38727. * @type {boolean}
  38728. * @default true
  38729. */
  38730. this.zeroSlopeAtEnd = true;
  38731. }
  38732. /**
  38733. * Starts the playback of the animation.
  38734. *
  38735. * @return {AnimationAction} A reference to this animation action.
  38736. */
  38737. play() {
  38738. this._mixer._activateAction( this );
  38739. return this;
  38740. }
  38741. /**
  38742. * Stops the playback of the animation.
  38743. *
  38744. * @return {AnimationAction} A reference to this animation action.
  38745. */
  38746. stop() {
  38747. this._mixer._deactivateAction( this );
  38748. return this.reset();
  38749. }
  38750. /**
  38751. * Resets the playback of the animation.
  38752. *
  38753. * @return {AnimationAction} A reference to this animation action.
  38754. */
  38755. reset() {
  38756. this.paused = false;
  38757. this.enabled = true;
  38758. this.time = 0; // restart clip
  38759. this._loopCount = -1;// forget previous loops
  38760. this._startTime = null;// forget scheduling
  38761. return this.stopFading().stopWarping();
  38762. }
  38763. /**
  38764. * Returns `true` if the animation is running.
  38765. *
  38766. * @return {boolean} Whether the animation is running or not.
  38767. */
  38768. isRunning() {
  38769. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38770. this._startTime === null && this._mixer._isActiveAction( this );
  38771. }
  38772. /**
  38773. * Returns `true` when {@link AnimationAction#play} has been called.
  38774. *
  38775. * @return {boolean} Whether the animation is scheduled or not.
  38776. */
  38777. isScheduled() {
  38778. return this._mixer._isActiveAction( this );
  38779. }
  38780. /**
  38781. * Defines the time when the animation should start.
  38782. *
  38783. * @param {number} time - The start time in seconds.
  38784. * @return {AnimationAction} A reference to this animation action.
  38785. */
  38786. startAt( time ) {
  38787. this._startTime = time;
  38788. return this;
  38789. }
  38790. /**
  38791. * Configures the loop settings for this action.
  38792. *
  38793. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38794. * @param {number} repetitions - The number of repetitions.
  38795. * @return {AnimationAction} A reference to this animation action.
  38796. */
  38797. setLoop( mode, repetitions ) {
  38798. this.loop = mode;
  38799. this.repetitions = repetitions;
  38800. return this;
  38801. }
  38802. /**
  38803. * Sets the effective weight of this action.
  38804. *
  38805. * An action has no effect and thus an effective weight of zero when the
  38806. * action is disabled.
  38807. *
  38808. * @param {number} weight - The weight to set.
  38809. * @return {AnimationAction} A reference to this animation action.
  38810. */
  38811. setEffectiveWeight( weight ) {
  38812. this.weight = weight;
  38813. // note: same logic as when updated at runtime
  38814. this._effectiveWeight = this.enabled ? weight : 0;
  38815. return this.stopFading();
  38816. }
  38817. /**
  38818. * Returns the effective weight of this action.
  38819. *
  38820. * @return {number} The effective weight.
  38821. */
  38822. getEffectiveWeight() {
  38823. return this._effectiveWeight;
  38824. }
  38825. /**
  38826. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38827. * within the passed time interval.
  38828. *
  38829. * @param {number} duration - The duration of the fade.
  38830. * @return {AnimationAction} A reference to this animation action.
  38831. */
  38832. fadeIn( duration ) {
  38833. return this._scheduleFading( duration, 0, 1 );
  38834. }
  38835. /**
  38836. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38837. * within the passed time interval.
  38838. *
  38839. * @param {number} duration - The duration of the fade.
  38840. * @return {AnimationAction} A reference to this animation action.
  38841. */
  38842. fadeOut( duration ) {
  38843. return this._scheduleFading( duration, 1, 0 );
  38844. }
  38845. /**
  38846. * Causes this action to fade in and the given action to fade out,
  38847. * within the passed time interval.
  38848. *
  38849. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38850. * @param {number} duration - The duration of the fade.
  38851. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38852. * @return {AnimationAction} A reference to this animation action.
  38853. */
  38854. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38855. fadeOutAction.fadeOut( duration );
  38856. this.fadeIn( duration );
  38857. if ( warp === true ) {
  38858. const fadeInDuration = this._clip.duration,
  38859. fadeOutDuration = fadeOutAction._clip.duration,
  38860. startEndRatio = fadeOutDuration / fadeInDuration,
  38861. endStartRatio = fadeInDuration / fadeOutDuration;
  38862. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38863. this.warp( endStartRatio, 1.0, duration );
  38864. }
  38865. return this;
  38866. }
  38867. /**
  38868. * Causes this action to fade out and the given action to fade in,
  38869. * within the passed time interval.
  38870. *
  38871. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38872. * @param {number} duration - The duration of the fade.
  38873. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38874. * @return {AnimationAction} A reference to this animation action.
  38875. */
  38876. crossFadeTo( fadeInAction, duration, warp = false ) {
  38877. return fadeInAction.crossFadeFrom( this, duration, warp );
  38878. }
  38879. /**
  38880. * Stops any fading which is applied to this action.
  38881. *
  38882. * @return {AnimationAction} A reference to this animation action.
  38883. */
  38884. stopFading() {
  38885. const weightInterpolant = this._weightInterpolant;
  38886. if ( weightInterpolant !== null ) {
  38887. this._weightInterpolant = null;
  38888. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38889. }
  38890. return this;
  38891. }
  38892. /**
  38893. * Sets the effective time scale of this action.
  38894. *
  38895. * An action has no effect and thus an effective time scale of zero when the
  38896. * action is paused.
  38897. *
  38898. * @param {number} timeScale - The time scale to set.
  38899. * @return {AnimationAction} A reference to this animation action.
  38900. */
  38901. setEffectiveTimeScale( timeScale ) {
  38902. this.timeScale = timeScale;
  38903. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38904. return this.stopWarping();
  38905. }
  38906. /**
  38907. * Returns the effective time scale of this action.
  38908. *
  38909. * @return {number} The effective time scale.
  38910. */
  38911. getEffectiveTimeScale() {
  38912. return this._effectiveTimeScale;
  38913. }
  38914. /**
  38915. * Sets the duration for a single loop of this action.
  38916. *
  38917. * @param {number} duration - The duration to set.
  38918. * @return {AnimationAction} A reference to this animation action.
  38919. */
  38920. setDuration( duration ) {
  38921. this.timeScale = this._clip.duration / duration;
  38922. return this.stopWarping();
  38923. }
  38924. /**
  38925. * Synchronizes this action with the passed other action.
  38926. *
  38927. * @param {AnimationAction} action - The action to sync with.
  38928. * @return {AnimationAction} A reference to this animation action.
  38929. */
  38930. syncWith( action ) {
  38931. this.time = action.time;
  38932. this.timeScale = action.timeScale;
  38933. return this.stopWarping();
  38934. }
  38935. /**
  38936. * Decelerates this animation's speed to `0` within the passed time interval.
  38937. *
  38938. * @param {number} duration - The duration.
  38939. * @return {AnimationAction} A reference to this animation action.
  38940. */
  38941. halt( duration ) {
  38942. return this.warp( this._effectiveTimeScale, 0, duration );
  38943. }
  38944. /**
  38945. * Changes the playback speed, within the passed time interval, by modifying
  38946. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38947. * `endTimeScale`.
  38948. *
  38949. * @param {number} startTimeScale - The start time scale.
  38950. * @param {number} endTimeScale - The end time scale.
  38951. * @param {number} duration - The duration.
  38952. * @return {AnimationAction} A reference to this animation action.
  38953. */
  38954. warp( startTimeScale, endTimeScale, duration ) {
  38955. const mixer = this._mixer,
  38956. now = mixer.time,
  38957. timeScale = this.timeScale;
  38958. let interpolant = this._timeScaleInterpolant;
  38959. if ( interpolant === null ) {
  38960. interpolant = mixer._lendControlInterpolant();
  38961. this._timeScaleInterpolant = interpolant;
  38962. }
  38963. const times = interpolant.parameterPositions,
  38964. values = interpolant.sampleValues;
  38965. times[ 0 ] = now;
  38966. times[ 1 ] = now + duration;
  38967. values[ 0 ] = startTimeScale / timeScale;
  38968. values[ 1 ] = endTimeScale / timeScale;
  38969. return this;
  38970. }
  38971. /**
  38972. * Stops any scheduled warping which is applied to this action.
  38973. *
  38974. * @return {AnimationAction} A reference to this animation action.
  38975. */
  38976. stopWarping() {
  38977. const timeScaleInterpolant = this._timeScaleInterpolant;
  38978. if ( timeScaleInterpolant !== null ) {
  38979. this._timeScaleInterpolant = null;
  38980. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38981. }
  38982. return this;
  38983. }
  38984. /**
  38985. * Returns the animation mixer of this animation action.
  38986. *
  38987. * @return {AnimationMixer} The animation mixer.
  38988. */
  38989. getMixer() {
  38990. return this._mixer;
  38991. }
  38992. /**
  38993. * Returns the animation clip of this animation action.
  38994. *
  38995. * @return {AnimationClip} The animation clip.
  38996. */
  38997. getClip() {
  38998. return this._clip;
  38999. }
  39000. /**
  39001. * Returns the root object of this animation action.
  39002. *
  39003. * @return {Object3D} The root object.
  39004. */
  39005. getRoot() {
  39006. return this._localRoot || this._mixer._root;
  39007. }
  39008. // Internal
  39009. _update( time, deltaTime, timeDirection, accuIndex ) {
  39010. // called by the mixer
  39011. if ( ! this.enabled ) {
  39012. // call ._updateWeight() to update ._effectiveWeight
  39013. this._updateWeight( time );
  39014. return;
  39015. }
  39016. const startTime = this._startTime;
  39017. if ( startTime !== null ) {
  39018. // check for scheduled start of action
  39019. const timeRunning = ( time - startTime ) * timeDirection;
  39020. if ( timeRunning < 0 || timeDirection === 0 ) {
  39021. deltaTime = 0;
  39022. } else {
  39023. this._startTime = null; // unschedule
  39024. deltaTime = timeDirection * timeRunning;
  39025. }
  39026. }
  39027. // apply time scale and advance time
  39028. deltaTime *= this._updateTimeScale( time );
  39029. const clipTime = this._updateTime( deltaTime );
  39030. // note: _updateTime may disable the action resulting in
  39031. // an effective weight of 0
  39032. const weight = this._updateWeight( time );
  39033. if ( weight > 0 ) {
  39034. const interpolants = this._interpolants;
  39035. const propertyMixers = this._propertyBindings;
  39036. switch ( this.blendMode ) {
  39037. case AdditiveAnimationBlendMode:
  39038. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39039. interpolants[ j ].evaluate( clipTime );
  39040. propertyMixers[ j ].accumulateAdditive( weight );
  39041. }
  39042. break;
  39043. case NormalAnimationBlendMode:
  39044. default:
  39045. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39046. interpolants[ j ].evaluate( clipTime );
  39047. propertyMixers[ j ].accumulate( accuIndex, weight );
  39048. }
  39049. }
  39050. }
  39051. }
  39052. _updateWeight( time ) {
  39053. let weight = 0;
  39054. if ( this.enabled ) {
  39055. weight = this.weight;
  39056. const interpolant = this._weightInterpolant;
  39057. if ( interpolant !== null ) {
  39058. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39059. weight *= interpolantValue;
  39060. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39061. this.stopFading();
  39062. if ( interpolantValue === 0 ) {
  39063. // faded out, disable
  39064. this.enabled = false;
  39065. }
  39066. }
  39067. }
  39068. }
  39069. this._effectiveWeight = weight;
  39070. return weight;
  39071. }
  39072. _updateTimeScale( time ) {
  39073. let timeScale = 0;
  39074. if ( ! this.paused ) {
  39075. timeScale = this.timeScale;
  39076. const interpolant = this._timeScaleInterpolant;
  39077. if ( interpolant !== null ) {
  39078. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39079. timeScale *= interpolantValue;
  39080. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39081. this.stopWarping();
  39082. if ( timeScale === 0 ) {
  39083. // motion has halted, pause
  39084. this.paused = true;
  39085. } else {
  39086. // warp done - apply final time scale
  39087. this.timeScale = timeScale;
  39088. }
  39089. }
  39090. }
  39091. }
  39092. this._effectiveTimeScale = timeScale;
  39093. return timeScale;
  39094. }
  39095. _updateTime( deltaTime ) {
  39096. const duration = this._clip.duration;
  39097. const loop = this.loop;
  39098. let time = this.time + deltaTime;
  39099. let loopCount = this._loopCount;
  39100. const pingPong = ( loop === LoopPingPong );
  39101. if ( deltaTime === 0 ) {
  39102. if ( loopCount === -1 ) return time;
  39103. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39104. }
  39105. if ( loop === LoopOnce ) {
  39106. if ( loopCount === -1 ) {
  39107. // just started
  39108. this._loopCount = 0;
  39109. this._setEndings( true, true, false );
  39110. }
  39111. handle_stop: {
  39112. if ( time >= duration ) {
  39113. time = duration;
  39114. } else if ( time < 0 ) {
  39115. time = 0;
  39116. } else {
  39117. this.time = time;
  39118. break handle_stop;
  39119. }
  39120. if ( this.clampWhenFinished ) this.paused = true;
  39121. else this.enabled = false;
  39122. this.time = time;
  39123. this._mixer.dispatchEvent( {
  39124. type: 'finished', action: this,
  39125. direction: deltaTime < 0 ? -1 : 1
  39126. } );
  39127. }
  39128. } else { // repetitive Repeat or PingPong
  39129. if ( loopCount === -1 ) {
  39130. // just started
  39131. if ( deltaTime >= 0 ) {
  39132. loopCount = 0;
  39133. this._setEndings( true, this.repetitions === 0, pingPong );
  39134. } else {
  39135. // when looping in reverse direction, the initial
  39136. // transition through zero counts as a repetition,
  39137. // so leave loopCount at -1
  39138. this._setEndings( this.repetitions === 0, true, pingPong );
  39139. }
  39140. }
  39141. if ( time >= duration || time < 0 ) {
  39142. // wrap around
  39143. const loopDelta = Math.floor( time / duration ); // signed
  39144. time -= duration * loopDelta;
  39145. loopCount += Math.abs( loopDelta );
  39146. const pending = this.repetitions - loopCount;
  39147. if ( pending <= 0 ) {
  39148. // have to stop (switch state, clamp time, fire event)
  39149. if ( this.clampWhenFinished ) this.paused = true;
  39150. else this.enabled = false;
  39151. time = deltaTime > 0 ? duration : 0;
  39152. this.time = time;
  39153. this._mixer.dispatchEvent( {
  39154. type: 'finished', action: this,
  39155. direction: deltaTime > 0 ? 1 : -1
  39156. } );
  39157. } else {
  39158. // keep running
  39159. if ( pending === 1 ) {
  39160. // entering the last round
  39161. const atStart = deltaTime < 0;
  39162. this._setEndings( atStart, ! atStart, pingPong );
  39163. } else {
  39164. this._setEndings( false, false, pingPong );
  39165. }
  39166. this._loopCount = loopCount;
  39167. this.time = time;
  39168. this._mixer.dispatchEvent( {
  39169. type: 'loop', action: this, loopDelta: loopDelta
  39170. } );
  39171. }
  39172. } else {
  39173. this.time = time;
  39174. }
  39175. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39176. // invert time for the "pong round"
  39177. return duration - time;
  39178. }
  39179. }
  39180. return time;
  39181. }
  39182. _setEndings( atStart, atEnd, pingPong ) {
  39183. const settings = this._interpolantSettings;
  39184. if ( pingPong ) {
  39185. settings.endingStart = ZeroSlopeEnding;
  39186. settings.endingEnd = ZeroSlopeEnding;
  39187. } else {
  39188. // assuming for LoopOnce atStart == atEnd == true
  39189. if ( atStart ) {
  39190. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39191. } else {
  39192. settings.endingStart = WrapAroundEnding;
  39193. }
  39194. if ( atEnd ) {
  39195. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39196. } else {
  39197. settings.endingEnd = WrapAroundEnding;
  39198. }
  39199. }
  39200. }
  39201. _scheduleFading( duration, weightNow, weightThen ) {
  39202. const mixer = this._mixer, now = mixer.time;
  39203. let interpolant = this._weightInterpolant;
  39204. if ( interpolant === null ) {
  39205. interpolant = mixer._lendControlInterpolant();
  39206. this._weightInterpolant = interpolant;
  39207. }
  39208. const times = interpolant.parameterPositions,
  39209. values = interpolant.sampleValues;
  39210. times[ 0 ] = now;
  39211. values[ 0 ] = weightNow;
  39212. times[ 1 ] = now + duration;
  39213. values[ 1 ] = weightThen;
  39214. return this;
  39215. }
  39216. }
  39217. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39218. /**
  39219. * `AnimationMixer` is a player for animations on a particular object in
  39220. * the scene. When multiple objects in the scene are animated independently,
  39221. * one `AnimationMixer` may be used for each object.
  39222. */
  39223. class AnimationMixer extends EventDispatcher {
  39224. /**
  39225. * Constructs a new animation mixer.
  39226. *
  39227. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39228. */
  39229. constructor( root ) {
  39230. super();
  39231. this._root = root;
  39232. this._initMemoryManager();
  39233. this._accuIndex = 0;
  39234. /**
  39235. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39236. *
  39237. * @type {number}
  39238. * @default 0
  39239. */
  39240. this.time = 0;
  39241. /**
  39242. * A scaling factor for the global time.
  39243. *
  39244. * Note: Setting this member to `0` and later back to `1` is a
  39245. * possibility to pause/unpause all actions that are controlled by this
  39246. * mixer.
  39247. *
  39248. * @type {number}
  39249. * @default 1
  39250. */
  39251. this.timeScale = 1.0;
  39252. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39253. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39254. }
  39255. }
  39256. _bindAction( action, prototypeAction ) {
  39257. const root = action._localRoot || this._root,
  39258. tracks = action._clip.tracks,
  39259. nTracks = tracks.length,
  39260. bindings = action._propertyBindings,
  39261. interpolants = action._interpolants,
  39262. rootUuid = root.uuid,
  39263. bindingsByRoot = this._bindingsByRootAndName;
  39264. let bindingsByName = bindingsByRoot[ rootUuid ];
  39265. if ( bindingsByName === undefined ) {
  39266. bindingsByName = {};
  39267. bindingsByRoot[ rootUuid ] = bindingsByName;
  39268. }
  39269. for ( let i = 0; i !== nTracks; ++ i ) {
  39270. const track = tracks[ i ],
  39271. trackName = track.name;
  39272. let binding = bindingsByName[ trackName ];
  39273. if ( binding !== undefined ) {
  39274. ++ binding.referenceCount;
  39275. bindings[ i ] = binding;
  39276. } else {
  39277. binding = bindings[ i ];
  39278. if ( binding !== undefined ) {
  39279. // existing binding, make sure the cache knows
  39280. if ( binding._cacheIndex === null ) {
  39281. ++ binding.referenceCount;
  39282. this._addInactiveBinding( binding, rootUuid, trackName );
  39283. }
  39284. continue;
  39285. }
  39286. const path = prototypeAction && prototypeAction.
  39287. _propertyBindings[ i ].binding.parsedPath;
  39288. binding = new PropertyMixer(
  39289. PropertyBinding.create( root, trackName, path ),
  39290. track.ValueTypeName, track.getValueSize() );
  39291. ++ binding.referenceCount;
  39292. this._addInactiveBinding( binding, rootUuid, trackName );
  39293. bindings[ i ] = binding;
  39294. }
  39295. interpolants[ i ].resultBuffer = binding.buffer;
  39296. }
  39297. }
  39298. _activateAction( action ) {
  39299. if ( ! this._isActiveAction( action ) ) {
  39300. if ( action._cacheIndex === null ) {
  39301. // this action has been forgotten by the cache, but the user
  39302. // appears to be still using it -> rebind
  39303. const rootUuid = ( action._localRoot || this._root ).uuid,
  39304. clipUuid = action._clip.uuid,
  39305. actionsForClip = this._actionsByClip[ clipUuid ];
  39306. this._bindAction( action,
  39307. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39308. this._addInactiveAction( action, clipUuid, rootUuid );
  39309. }
  39310. const bindings = action._propertyBindings;
  39311. // increment reference counts / sort out state
  39312. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39313. const binding = bindings[ i ];
  39314. if ( binding.useCount ++ === 0 ) {
  39315. this._lendBinding( binding );
  39316. binding.saveOriginalState();
  39317. }
  39318. }
  39319. this._lendAction( action );
  39320. }
  39321. }
  39322. _deactivateAction( action ) {
  39323. if ( this._isActiveAction( action ) ) {
  39324. const bindings = action._propertyBindings;
  39325. // decrement reference counts / sort out state
  39326. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39327. const binding = bindings[ i ];
  39328. if ( -- binding.useCount === 0 ) {
  39329. binding.restoreOriginalState();
  39330. this._takeBackBinding( binding );
  39331. }
  39332. }
  39333. this._takeBackAction( action );
  39334. }
  39335. }
  39336. // Memory manager
  39337. _initMemoryManager() {
  39338. this._actions = []; // 'nActiveActions' followed by inactive ones
  39339. this._nActiveActions = 0;
  39340. this._actionsByClip = {};
  39341. // inside:
  39342. // {
  39343. // knownActions: Array< AnimationAction > - used as prototypes
  39344. // actionByRoot: AnimationAction - lookup
  39345. // }
  39346. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39347. this._nActiveBindings = 0;
  39348. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39349. this._controlInterpolants = []; // same game as above
  39350. this._nActiveControlInterpolants = 0;
  39351. const scope = this;
  39352. this.stats = {
  39353. actions: {
  39354. get total() {
  39355. return scope._actions.length;
  39356. },
  39357. get inUse() {
  39358. return scope._nActiveActions;
  39359. }
  39360. },
  39361. bindings: {
  39362. get total() {
  39363. return scope._bindings.length;
  39364. },
  39365. get inUse() {
  39366. return scope._nActiveBindings;
  39367. }
  39368. },
  39369. controlInterpolants: {
  39370. get total() {
  39371. return scope._controlInterpolants.length;
  39372. },
  39373. get inUse() {
  39374. return scope._nActiveControlInterpolants;
  39375. }
  39376. }
  39377. };
  39378. }
  39379. // Memory management for AnimationAction objects
  39380. _isActiveAction( action ) {
  39381. const index = action._cacheIndex;
  39382. return index !== null && index < this._nActiveActions;
  39383. }
  39384. _addInactiveAction( action, clipUuid, rootUuid ) {
  39385. const actions = this._actions,
  39386. actionsByClip = this._actionsByClip;
  39387. let actionsForClip = actionsByClip[ clipUuid ];
  39388. if ( actionsForClip === undefined ) {
  39389. actionsForClip = {
  39390. knownActions: [ action ],
  39391. actionByRoot: {}
  39392. };
  39393. action._byClipCacheIndex = 0;
  39394. actionsByClip[ clipUuid ] = actionsForClip;
  39395. } else {
  39396. const knownActions = actionsForClip.knownActions;
  39397. action._byClipCacheIndex = knownActions.length;
  39398. knownActions.push( action );
  39399. }
  39400. action._cacheIndex = actions.length;
  39401. actions.push( action );
  39402. actionsForClip.actionByRoot[ rootUuid ] = action;
  39403. }
  39404. _removeInactiveAction( action ) {
  39405. const actions = this._actions,
  39406. lastInactiveAction = actions[ actions.length - 1 ],
  39407. cacheIndex = action._cacheIndex;
  39408. lastInactiveAction._cacheIndex = cacheIndex;
  39409. actions[ cacheIndex ] = lastInactiveAction;
  39410. actions.pop();
  39411. action._cacheIndex = null;
  39412. const clipUuid = action._clip.uuid,
  39413. actionsByClip = this._actionsByClip,
  39414. actionsForClip = actionsByClip[ clipUuid ],
  39415. knownActionsForClip = actionsForClip.knownActions,
  39416. lastKnownAction =
  39417. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39418. byClipCacheIndex = action._byClipCacheIndex;
  39419. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39420. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39421. knownActionsForClip.pop();
  39422. action._byClipCacheIndex = null;
  39423. const actionByRoot = actionsForClip.actionByRoot,
  39424. rootUuid = ( action._localRoot || this._root ).uuid;
  39425. delete actionByRoot[ rootUuid ];
  39426. if ( knownActionsForClip.length === 0 ) {
  39427. delete actionsByClip[ clipUuid ];
  39428. }
  39429. this._removeInactiveBindingsForAction( action );
  39430. }
  39431. _removeInactiveBindingsForAction( action ) {
  39432. const bindings = action._propertyBindings;
  39433. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39434. const binding = bindings[ i ];
  39435. if ( -- binding.referenceCount === 0 ) {
  39436. this._removeInactiveBinding( binding );
  39437. }
  39438. }
  39439. }
  39440. _lendAction( action ) {
  39441. // [ active actions | inactive actions ]
  39442. // [ active actions >| inactive actions ]
  39443. // s a
  39444. // <-swap->
  39445. // a s
  39446. const actions = this._actions,
  39447. prevIndex = action._cacheIndex,
  39448. lastActiveIndex = this._nActiveActions ++,
  39449. firstInactiveAction = actions[ lastActiveIndex ];
  39450. action._cacheIndex = lastActiveIndex;
  39451. actions[ lastActiveIndex ] = action;
  39452. firstInactiveAction._cacheIndex = prevIndex;
  39453. actions[ prevIndex ] = firstInactiveAction;
  39454. }
  39455. _takeBackAction( action ) {
  39456. // [ active actions | inactive actions ]
  39457. // [ active actions |< inactive actions ]
  39458. // a s
  39459. // <-swap->
  39460. // s a
  39461. const actions = this._actions,
  39462. prevIndex = action._cacheIndex,
  39463. firstInactiveIndex = -- this._nActiveActions,
  39464. lastActiveAction = actions[ firstInactiveIndex ];
  39465. action._cacheIndex = firstInactiveIndex;
  39466. actions[ firstInactiveIndex ] = action;
  39467. lastActiveAction._cacheIndex = prevIndex;
  39468. actions[ prevIndex ] = lastActiveAction;
  39469. }
  39470. // Memory management for PropertyMixer objects
  39471. _addInactiveBinding( binding, rootUuid, trackName ) {
  39472. const bindingsByRoot = this._bindingsByRootAndName,
  39473. bindings = this._bindings;
  39474. let bindingByName = bindingsByRoot[ rootUuid ];
  39475. if ( bindingByName === undefined ) {
  39476. bindingByName = {};
  39477. bindingsByRoot[ rootUuid ] = bindingByName;
  39478. }
  39479. bindingByName[ trackName ] = binding;
  39480. binding._cacheIndex = bindings.length;
  39481. bindings.push( binding );
  39482. }
  39483. _removeInactiveBinding( binding ) {
  39484. const bindings = this._bindings,
  39485. propBinding = binding.binding,
  39486. rootUuid = propBinding.rootNode.uuid,
  39487. trackName = propBinding.path,
  39488. bindingsByRoot = this._bindingsByRootAndName,
  39489. bindingByName = bindingsByRoot[ rootUuid ],
  39490. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39491. cacheIndex = binding._cacheIndex;
  39492. lastInactiveBinding._cacheIndex = cacheIndex;
  39493. bindings[ cacheIndex ] = lastInactiveBinding;
  39494. bindings.pop();
  39495. delete bindingByName[ trackName ];
  39496. if ( Object.keys( bindingByName ).length === 0 ) {
  39497. delete bindingsByRoot[ rootUuid ];
  39498. }
  39499. }
  39500. _lendBinding( binding ) {
  39501. const bindings = this._bindings,
  39502. prevIndex = binding._cacheIndex,
  39503. lastActiveIndex = this._nActiveBindings ++,
  39504. firstInactiveBinding = bindings[ lastActiveIndex ];
  39505. binding._cacheIndex = lastActiveIndex;
  39506. bindings[ lastActiveIndex ] = binding;
  39507. firstInactiveBinding._cacheIndex = prevIndex;
  39508. bindings[ prevIndex ] = firstInactiveBinding;
  39509. }
  39510. _takeBackBinding( binding ) {
  39511. const bindings = this._bindings,
  39512. prevIndex = binding._cacheIndex,
  39513. firstInactiveIndex = -- this._nActiveBindings,
  39514. lastActiveBinding = bindings[ firstInactiveIndex ];
  39515. binding._cacheIndex = firstInactiveIndex;
  39516. bindings[ firstInactiveIndex ] = binding;
  39517. lastActiveBinding._cacheIndex = prevIndex;
  39518. bindings[ prevIndex ] = lastActiveBinding;
  39519. }
  39520. // Memory management of Interpolants for weight and time scale
  39521. _lendControlInterpolant() {
  39522. const interpolants = this._controlInterpolants,
  39523. lastActiveIndex = this._nActiveControlInterpolants ++;
  39524. let interpolant = interpolants[ lastActiveIndex ];
  39525. if ( interpolant === undefined ) {
  39526. interpolant = new LinearInterpolant(
  39527. new Float32Array( 2 ), new Float32Array( 2 ),
  39528. 1, _controlInterpolantsResultBuffer );
  39529. interpolant.__cacheIndex = lastActiveIndex;
  39530. interpolants[ lastActiveIndex ] = interpolant;
  39531. }
  39532. return interpolant;
  39533. }
  39534. _takeBackControlInterpolant( interpolant ) {
  39535. const interpolants = this._controlInterpolants,
  39536. prevIndex = interpolant.__cacheIndex,
  39537. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39538. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39539. interpolant.__cacheIndex = firstInactiveIndex;
  39540. interpolants[ firstInactiveIndex ] = interpolant;
  39541. lastActiveInterpolant.__cacheIndex = prevIndex;
  39542. interpolants[ prevIndex ] = lastActiveInterpolant;
  39543. }
  39544. /**
  39545. * Returns an instance of {@link AnimationAction} for the passed clip.
  39546. *
  39547. * If an action fitting the clip and root parameters doesn't yet exist, it
  39548. * will be created by this method. Calling this method several times with the
  39549. * same clip and root parameters always returns the same action.
  39550. *
  39551. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39552. * @param {Object3D} [optionalRoot] - An alternative root object.
  39553. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39554. * @return {?AnimationAction} The animation action.
  39555. */
  39556. clipAction( clip, optionalRoot, blendMode ) {
  39557. const root = optionalRoot || this._root,
  39558. rootUuid = root.uuid;
  39559. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39560. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39561. const actionsForClip = this._actionsByClip[ clipUuid ];
  39562. let prototypeAction = null;
  39563. if ( blendMode === undefined ) {
  39564. if ( clipObject !== null ) {
  39565. blendMode = clipObject.blendMode;
  39566. } else {
  39567. blendMode = NormalAnimationBlendMode;
  39568. }
  39569. }
  39570. if ( actionsForClip !== undefined ) {
  39571. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39572. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39573. return existingAction;
  39574. }
  39575. // we know the clip, so we don't have to parse all
  39576. // the bindings again but can just copy
  39577. prototypeAction = actionsForClip.knownActions[ 0 ];
  39578. // also, take the clip from the prototype action
  39579. if ( clipObject === null )
  39580. clipObject = prototypeAction._clip;
  39581. }
  39582. // clip must be known when specified via string
  39583. if ( clipObject === null ) return null;
  39584. // allocate all resources required to run it
  39585. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39586. this._bindAction( newAction, prototypeAction );
  39587. // and make the action known to the memory manager
  39588. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39589. return newAction;
  39590. }
  39591. /**
  39592. * Returns an existing animation action for the passed clip.
  39593. *
  39594. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39595. * @param {Object3D} [optionalRoot] - An alternative root object.
  39596. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39597. */
  39598. existingAction( clip, optionalRoot ) {
  39599. const root = optionalRoot || this._root,
  39600. rootUuid = root.uuid,
  39601. clipObject = typeof clip === 'string' ?
  39602. AnimationClip.findByName( root, clip ) : clip,
  39603. clipUuid = clipObject ? clipObject.uuid : clip,
  39604. actionsForClip = this._actionsByClip[ clipUuid ];
  39605. if ( actionsForClip !== undefined ) {
  39606. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39607. }
  39608. return null;
  39609. }
  39610. /**
  39611. * Deactivates all previously scheduled actions on this mixer.
  39612. *
  39613. * @return {AnimationMixer} A reference to this animation mixer.
  39614. */
  39615. stopAllAction() {
  39616. const actions = this._actions,
  39617. nActions = this._nActiveActions;
  39618. for ( let i = nActions - 1; i >= 0; -- i ) {
  39619. actions[ i ].stop();
  39620. }
  39621. return this;
  39622. }
  39623. /**
  39624. * Advances the global mixer time and updates the animation.
  39625. *
  39626. * This is usually done in the render loop by passing the delta
  39627. * time from {@link Clock} or {@link Timer}.
  39628. *
  39629. * @param {number} deltaTime - The delta time in seconds.
  39630. * @return {AnimationMixer} A reference to this animation mixer.
  39631. */
  39632. update( deltaTime ) {
  39633. deltaTime *= this.timeScale;
  39634. const actions = this._actions,
  39635. nActions = this._nActiveActions,
  39636. time = this.time += deltaTime,
  39637. timeDirection = Math.sign( deltaTime ),
  39638. accuIndex = this._accuIndex ^= 1;
  39639. // run active actions
  39640. for ( let i = 0; i !== nActions; ++ i ) {
  39641. const action = actions[ i ];
  39642. action._update( time, deltaTime, timeDirection, accuIndex );
  39643. }
  39644. // update scene graph
  39645. const bindings = this._bindings,
  39646. nBindings = this._nActiveBindings;
  39647. for ( let i = 0; i !== nBindings; ++ i ) {
  39648. bindings[ i ].apply( accuIndex );
  39649. }
  39650. return this;
  39651. }
  39652. /**
  39653. * Sets the global mixer to a specific time and updates the animation accordingly.
  39654. *
  39655. * This is useful when you need to jump to an exact time in an animation. The
  39656. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39657. *
  39658. * @param {number} time - The time to set in seconds.
  39659. * @return {AnimationMixer} A reference to this animation mixer.
  39660. */
  39661. setTime( time ) {
  39662. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39663. for ( let i = 0; i < this._actions.length; i ++ ) {
  39664. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39665. }
  39666. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39667. }
  39668. /**
  39669. * Returns this mixer's root object.
  39670. *
  39671. * @return {Object3D} The mixer's root object.
  39672. */
  39673. getRoot() {
  39674. return this._root;
  39675. }
  39676. /**
  39677. * Deallocates all memory resources for a clip. Before using this method make
  39678. * sure to call {@link AnimationAction#stop} for all related actions.
  39679. *
  39680. * @param {AnimationClip} clip - The clip to uncache.
  39681. */
  39682. uncacheClip( clip ) {
  39683. const actions = this._actions,
  39684. clipUuid = clip.uuid,
  39685. actionsByClip = this._actionsByClip,
  39686. actionsForClip = actionsByClip[ clipUuid ];
  39687. if ( actionsForClip !== undefined ) {
  39688. // note: just calling _removeInactiveAction would mess up the
  39689. // iteration state and also require updating the state we can
  39690. // just throw away
  39691. const actionsToRemove = actionsForClip.knownActions;
  39692. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39693. const action = actionsToRemove[ i ];
  39694. this._deactivateAction( action );
  39695. const cacheIndex = action._cacheIndex,
  39696. lastInactiveAction = actions[ actions.length - 1 ];
  39697. action._cacheIndex = null;
  39698. action._byClipCacheIndex = null;
  39699. lastInactiveAction._cacheIndex = cacheIndex;
  39700. actions[ cacheIndex ] = lastInactiveAction;
  39701. actions.pop();
  39702. this._removeInactiveBindingsForAction( action );
  39703. }
  39704. delete actionsByClip[ clipUuid ];
  39705. }
  39706. }
  39707. /**
  39708. * Deallocates all memory resources for a root object. Before using this
  39709. * method make sure to call {@link AnimationAction#stop} for all related
  39710. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39711. * mixer operates on a single root.
  39712. *
  39713. * @param {Object3D} root - The root object to uncache.
  39714. */
  39715. uncacheRoot( root ) {
  39716. const rootUuid = root.uuid,
  39717. actionsByClip = this._actionsByClip;
  39718. for ( const clipUuid in actionsByClip ) {
  39719. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39720. action = actionByRoot[ rootUuid ];
  39721. if ( action !== undefined ) {
  39722. this._deactivateAction( action );
  39723. this._removeInactiveAction( action );
  39724. }
  39725. }
  39726. const bindingsByRoot = this._bindingsByRootAndName,
  39727. bindingByName = bindingsByRoot[ rootUuid ];
  39728. if ( bindingByName !== undefined ) {
  39729. for ( const trackName in bindingByName ) {
  39730. const binding = bindingByName[ trackName ];
  39731. binding.restoreOriginalState();
  39732. this._removeInactiveBinding( binding );
  39733. }
  39734. }
  39735. }
  39736. /**
  39737. * Deallocates all memory resources for an action. The action is identified by the
  39738. * given clip and an optional root object. Before using this method make
  39739. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39740. *
  39741. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39742. * @param {Object3D} [optionalRoot] - An alternative root object.
  39743. */
  39744. uncacheAction( clip, optionalRoot ) {
  39745. const action = this.existingAction( clip, optionalRoot );
  39746. if ( action !== null ) {
  39747. this._deactivateAction( action );
  39748. this._removeInactiveAction( action );
  39749. }
  39750. }
  39751. }
  39752. /**
  39753. * Represents a 3D render target.
  39754. *
  39755. * @augments RenderTarget
  39756. */
  39757. class RenderTarget3D extends RenderTarget {
  39758. /**
  39759. * Constructs a new 3D render target.
  39760. *
  39761. * @param {number} [width=1] - The width of the render target.
  39762. * @param {number} [height=1] - The height of the render target.
  39763. * @param {number} [depth=1] - The height of the render target.
  39764. * @param {RenderTarget~Options} [options] - The configuration object.
  39765. */
  39766. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39767. super( width, height, options );
  39768. /**
  39769. * This flag can be used for type testing.
  39770. *
  39771. * @type {boolean}
  39772. * @readonly
  39773. * @default true
  39774. */
  39775. this.isRenderTarget3D = true;
  39776. this.depth = depth;
  39777. /**
  39778. * Overwritten with a different texture type.
  39779. *
  39780. * @type {Data3DTexture}
  39781. */
  39782. this.texture = new Data3DTexture( null, width, height, depth );
  39783. this._setTextureOptions( options );
  39784. this.texture.isRenderTargetTexture = true;
  39785. }
  39786. }
  39787. /**
  39788. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39789. *
  39790. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39791. * ```js
  39792. * uniforms: {
  39793. * time: { value: 1.0 },
  39794. * resolution: new Uniform( new Vector2() )
  39795. * };
  39796. * ```
  39797. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39798. * in {@link WebGLRenderer}.
  39799. */
  39800. class Uniform {
  39801. /**
  39802. * Constructs a new uniform.
  39803. *
  39804. * @param {any} value - The uniform value.
  39805. */
  39806. constructor( value ) {
  39807. /**
  39808. * The uniform value.
  39809. *
  39810. * @type {any}
  39811. */
  39812. this.value = value;
  39813. }
  39814. /**
  39815. * Returns a new uniform with copied values from this instance.
  39816. * If the value has a `clone()` method, the value is cloned as well.
  39817. *
  39818. * @return {Uniform} A clone of this instance.
  39819. */
  39820. clone() {
  39821. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39822. }
  39823. }
  39824. let _id$1 = 0;
  39825. /**
  39826. * A class for managing multiple uniforms in a single group. The renderer will process
  39827. * such a definition as a single UBO.
  39828. *
  39829. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39830. * in {@link WebGLRenderer}.
  39831. *
  39832. * @augments EventDispatcher
  39833. */
  39834. class UniformsGroup extends EventDispatcher {
  39835. /**
  39836. * Constructs a new uniforms group.
  39837. */
  39838. constructor() {
  39839. super();
  39840. /**
  39841. * This flag can be used for type testing.
  39842. *
  39843. * @type {boolean}
  39844. * @readonly
  39845. * @default true
  39846. */
  39847. this.isUniformsGroup = true;
  39848. /**
  39849. * The ID of the 3D object.
  39850. *
  39851. * @name UniformsGroup#id
  39852. * @type {number}
  39853. * @readonly
  39854. */
  39855. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39856. /**
  39857. * The name of the uniforms group.
  39858. *
  39859. * @type {string}
  39860. */
  39861. this.name = '';
  39862. /**
  39863. * The buffer usage.
  39864. *
  39865. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39866. * @default StaticDrawUsage
  39867. */
  39868. this.usage = StaticDrawUsage;
  39869. /**
  39870. * An array holding the uniforms.
  39871. *
  39872. * @type {Array<Uniform>}
  39873. */
  39874. this.uniforms = [];
  39875. }
  39876. /**
  39877. * Adds the given uniform to this uniforms group.
  39878. *
  39879. * @param {Uniform} uniform - The uniform to add.
  39880. * @return {UniformsGroup} A reference to this uniforms group.
  39881. */
  39882. add( uniform ) {
  39883. this.uniforms.push( uniform );
  39884. return this;
  39885. }
  39886. /**
  39887. * Removes the given uniform from this uniforms group.
  39888. *
  39889. * @param {Uniform} uniform - The uniform to remove.
  39890. * @return {UniformsGroup} A reference to this uniforms group.
  39891. */
  39892. remove( uniform ) {
  39893. const index = this.uniforms.indexOf( uniform );
  39894. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39895. return this;
  39896. }
  39897. /**
  39898. * Sets the name of this uniforms group.
  39899. *
  39900. * @param {string} name - The name to set.
  39901. * @return {UniformsGroup} A reference to this uniforms group.
  39902. */
  39903. setName( name ) {
  39904. this.name = name;
  39905. return this;
  39906. }
  39907. /**
  39908. * Sets the usage of this uniforms group.
  39909. *
  39910. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39911. * @return {UniformsGroup} A reference to this uniforms group.
  39912. */
  39913. setUsage( value ) {
  39914. this.usage = value;
  39915. return this;
  39916. }
  39917. /**
  39918. * Frees the GPU-related resources allocated by this instance. Call this
  39919. * method whenever this instance is no longer used in your app.
  39920. *
  39921. * @fires Texture#dispose
  39922. */
  39923. dispose() {
  39924. this.dispatchEvent( { type: 'dispose' } );
  39925. }
  39926. /**
  39927. * Copies the values of the given uniforms group to this instance.
  39928. *
  39929. * @param {UniformsGroup} source - The uniforms group to copy.
  39930. * @return {UniformsGroup} A reference to this uniforms group.
  39931. */
  39932. copy( source ) {
  39933. this.name = source.name;
  39934. this.usage = source.usage;
  39935. const uniformsSource = source.uniforms;
  39936. this.uniforms.length = 0;
  39937. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39938. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39939. for ( let j = 0; j < uniforms.length; j ++ ) {
  39940. this.uniforms.push( uniforms[ j ].clone() );
  39941. }
  39942. }
  39943. return this;
  39944. }
  39945. /**
  39946. * Returns a new uniforms group with copied values from this instance.
  39947. *
  39948. * @return {UniformsGroup} A clone of this instance.
  39949. */
  39950. clone() {
  39951. return new this.constructor().copy( this );
  39952. }
  39953. }
  39954. /**
  39955. * An instanced version of an interleaved buffer.
  39956. *
  39957. * @augments InterleavedBuffer
  39958. */
  39959. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39960. /**
  39961. * Constructs a new instanced interleaved buffer.
  39962. *
  39963. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39964. * @param {number} stride - The number of typed-array elements per vertex.
  39965. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39966. */
  39967. constructor( array, stride, meshPerAttribute = 1 ) {
  39968. super( array, stride );
  39969. /**
  39970. * This flag can be used for type testing.
  39971. *
  39972. * @type {boolean}
  39973. * @readonly
  39974. * @default true
  39975. */
  39976. this.isInstancedInterleavedBuffer = true;
  39977. /**
  39978. * Defines how often a value of this buffer attribute should be repeated,
  39979. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39980. *
  39981. * @type {number}
  39982. * @default 1
  39983. */
  39984. this.meshPerAttribute = meshPerAttribute;
  39985. }
  39986. copy( source ) {
  39987. super.copy( source );
  39988. this.meshPerAttribute = source.meshPerAttribute;
  39989. return this;
  39990. }
  39991. clone( data ) {
  39992. const ib = super.clone( data );
  39993. ib.meshPerAttribute = this.meshPerAttribute;
  39994. return ib;
  39995. }
  39996. toJSON( data ) {
  39997. const json = super.toJSON( data );
  39998. json.isInstancedInterleavedBuffer = true;
  39999. json.meshPerAttribute = this.meshPerAttribute;
  40000. return json;
  40001. }
  40002. }
  40003. /**
  40004. * An alternative version of a buffer attribute with more control over the VBO.
  40005. *
  40006. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40007. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40008. *
  40009. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40010. * or even produces the VBOs in question.
  40011. *
  40012. * Notice that this class can only be used with {@link WebGLRenderer}.
  40013. */
  40014. class GLBufferAttribute {
  40015. /**
  40016. * Constructs a new GL buffer attribute.
  40017. *
  40018. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40019. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40020. * @param {number} itemSize - The item size.
  40021. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40022. * @param {number} count - The expected number of vertices in VBO.
  40023. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40024. */
  40025. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40026. /**
  40027. * This flag can be used for type testing.
  40028. *
  40029. * @type {boolean}
  40030. * @readonly
  40031. * @default true
  40032. */
  40033. this.isGLBufferAttribute = true;
  40034. /**
  40035. * The name of the buffer attribute.
  40036. *
  40037. * @type {string}
  40038. */
  40039. this.name = '';
  40040. /**
  40041. * The native WebGL buffer.
  40042. *
  40043. * @type {WebGLBuffer}
  40044. */
  40045. this.buffer = buffer;
  40046. /**
  40047. * The native data type.
  40048. *
  40049. * @type {number}
  40050. */
  40051. this.type = type;
  40052. /**
  40053. * The item size, see {@link BufferAttribute#itemSize}.
  40054. *
  40055. * @type {number}
  40056. */
  40057. this.itemSize = itemSize;
  40058. /**
  40059. * The corresponding size (in bytes) for the given `type` parameter.
  40060. *
  40061. * @type {number}
  40062. */
  40063. this.elementSize = elementSize;
  40064. /**
  40065. * The expected number of vertices in VBO.
  40066. *
  40067. * @type {number}
  40068. */
  40069. this.count = count;
  40070. /**
  40071. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40072. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40073. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40074. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40075. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40076. *
  40077. * @type {boolean}
  40078. */
  40079. this.normalized = normalized;
  40080. /**
  40081. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40082. *
  40083. * @type {number}
  40084. */
  40085. this.version = 0;
  40086. }
  40087. /**
  40088. * Flag to indicate that this attribute has changed and should be re-sent to
  40089. * the GPU. Set this to `true` when you modify the value of the array.
  40090. *
  40091. * @type {number}
  40092. * @default false
  40093. * @param {boolean} value
  40094. */
  40095. set needsUpdate( value ) {
  40096. if ( value === true ) this.version ++;
  40097. }
  40098. /**
  40099. * Sets the given native WebGL buffer.
  40100. *
  40101. * @param {WebGLBuffer} buffer - The buffer to set.
  40102. * @return {BufferAttribute} A reference to this instance.
  40103. */
  40104. setBuffer( buffer ) {
  40105. this.buffer = buffer;
  40106. return this;
  40107. }
  40108. /**
  40109. * Sets the given native data type and element size.
  40110. *
  40111. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40112. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40113. * @return {BufferAttribute} A reference to this instance.
  40114. */
  40115. setType( type, elementSize ) {
  40116. this.type = type;
  40117. this.elementSize = elementSize;
  40118. return this;
  40119. }
  40120. /**
  40121. * Sets the item size.
  40122. *
  40123. * @param {number} itemSize - The item size.
  40124. * @return {BufferAttribute} A reference to this instance.
  40125. */
  40126. setItemSize( itemSize ) {
  40127. this.itemSize = itemSize;
  40128. return this;
  40129. }
  40130. /**
  40131. * Sets the count (the expected number of vertices in VBO).
  40132. *
  40133. * @param {number} count - The count.
  40134. * @return {BufferAttribute} A reference to this instance.
  40135. */
  40136. setCount( count ) {
  40137. this.count = count;
  40138. return this;
  40139. }
  40140. }
  40141. const _matrix = /*@__PURE__*/ new Matrix4();
  40142. /**
  40143. * This class is designed to assist with raycasting. Raycasting is used for
  40144. * mouse picking (working out what objects in the 3d space the mouse is over)
  40145. * amongst other things.
  40146. */
  40147. class Raycaster {
  40148. /**
  40149. * Constructs a new raycaster.
  40150. *
  40151. * @param {Vector3} origin - The origin vector where the ray casts from.
  40152. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40153. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40154. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40155. */
  40156. constructor( origin, direction, near = 0, far = Infinity ) {
  40157. /**
  40158. * The ray used for raycasting.
  40159. *
  40160. * @type {Ray}
  40161. */
  40162. this.ray = new Ray( origin, direction );
  40163. /**
  40164. * All results returned are further away than near. Near can't be negative.
  40165. *
  40166. * @type {number}
  40167. * @default 0
  40168. */
  40169. this.near = near;
  40170. /**
  40171. * All results returned are closer than far. Far can't be lower than near.
  40172. *
  40173. * @type {number}
  40174. * @default Infinity
  40175. */
  40176. this.far = far;
  40177. /**
  40178. * The camera to use when raycasting against view-dependent objects such as
  40179. * billboarded objects like sprites. This field can be set manually or
  40180. * is set when calling `setFromCamera()`.
  40181. *
  40182. * @type {?Camera}
  40183. * @default null
  40184. */
  40185. this.camera = null;
  40186. /**
  40187. * Allows to selectively ignore 3D objects when performing intersection tests.
  40188. * The following code example ensures that only 3D objects on layer `1` will be
  40189. * honored by raycaster.
  40190. * ```js
  40191. * raycaster.layers.set( 1 );
  40192. * object.layers.enable( 1 );
  40193. * ```
  40194. *
  40195. * @type {Layers}
  40196. */
  40197. this.layers = new Layers();
  40198. /**
  40199. * A parameter object that configures the raycasting. It has the structure:
  40200. *
  40201. * ```
  40202. * {
  40203. * Mesh: {},
  40204. * Line: { threshold: 1 },
  40205. * LOD: {},
  40206. * Points: { threshold: 1 },
  40207. * Sprite: {}
  40208. * }
  40209. * ```
  40210. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40211. *
  40212. * @type {Object}
  40213. */
  40214. this.params = {
  40215. Mesh: {},
  40216. Line: { threshold: 1 },
  40217. LOD: {},
  40218. Points: { threshold: 1 },
  40219. Sprite: {}
  40220. };
  40221. }
  40222. /**
  40223. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40224. *
  40225. * @param {Vector3} origin - The origin vector where the ray casts from.
  40226. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40227. */
  40228. set( origin, direction ) {
  40229. // direction is assumed to be normalized (for accurate distance calculations)
  40230. this.ray.set( origin, direction );
  40231. }
  40232. /**
  40233. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40234. *
  40235. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40236. * X and Y components should be between `-1` and `1`.
  40237. * @param {Camera} camera - The camera from which the ray should originate.
  40238. */
  40239. setFromCamera( coords, camera ) {
  40240. if ( camera.isPerspectiveCamera ) {
  40241. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40242. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40243. this.camera = camera;
  40244. } else if ( camera.isOrthographicCamera ) {
  40245. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40246. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40247. this.camera = camera;
  40248. } else {
  40249. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40250. }
  40251. }
  40252. /**
  40253. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40254. *
  40255. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40256. * @return {Raycaster} A reference to this raycaster.
  40257. */
  40258. setFromXRController( controller ) {
  40259. _matrix.identity().extractRotation( controller.matrixWorld );
  40260. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40261. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40262. return this;
  40263. }
  40264. /**
  40265. * The intersection point of a raycaster intersection test.
  40266. * @typedef {Object} Raycaster~Intersection
  40267. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40268. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40269. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40270. * @property {Vector3} point - The intersection point, in world coordinates.
  40271. * @property {Object} face - The face that has been intersected.
  40272. * @property {number} faceIndex - The face index.
  40273. * @property {Object3D} object - The 3D object that has been intersected.
  40274. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40275. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40276. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40277. * @property {number} instanceId - The index number of the instance where the ray
  40278. * intersects the {@link InstancedMesh}.
  40279. */
  40280. /**
  40281. * Checks all intersection between the ray and the object with or without the
  40282. * descendants. Intersections are returned sorted by distance, closest first.
  40283. *
  40284. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40285. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40286. * differently to ray casting than lines or points.
  40287. *
  40288. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40289. * to be detected; intersections of the ray passing through the back of a face will not
  40290. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40291. * to `THREE.DoubleSide`.
  40292. *
  40293. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40294. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40295. * Otherwise it only checks intersection with the object.
  40296. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40297. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40298. */
  40299. intersectObject( object, recursive = true, intersects = [] ) {
  40300. intersect( object, this, intersects, recursive );
  40301. intersects.sort( ascSort );
  40302. return intersects;
  40303. }
  40304. /**
  40305. * Checks all intersection between the ray and the objects with or without
  40306. * the descendants. Intersections are returned sorted by distance, closest first.
  40307. *
  40308. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40309. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40310. * Otherwise it only checks intersection with the object.
  40311. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40312. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40313. */
  40314. intersectObjects( objects, recursive = true, intersects = [] ) {
  40315. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40316. intersect( objects[ i ], this, intersects, recursive );
  40317. }
  40318. intersects.sort( ascSort );
  40319. return intersects;
  40320. }
  40321. }
  40322. function ascSort( a, b ) {
  40323. return a.distance - b.distance;
  40324. }
  40325. function intersect( object, raycaster, intersects, recursive ) {
  40326. let propagate = true;
  40327. if ( object.layers.test( raycaster.layers ) ) {
  40328. const result = object.raycast( raycaster, intersects );
  40329. if ( result === false ) propagate = false;
  40330. }
  40331. if ( propagate === true && recursive === true ) {
  40332. const children = object.children;
  40333. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40334. intersect( children[ i ], raycaster, intersects, true );
  40335. }
  40336. }
  40337. }
  40338. /**
  40339. * Class for keeping track of time.
  40340. *
  40341. * @deprecated since r183.
  40342. */
  40343. class Clock {
  40344. /**
  40345. * Constructs a new clock.
  40346. *
  40347. * @deprecated since 183.
  40348. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  40349. * `getDelta()` is called for the first time.
  40350. */
  40351. constructor( autoStart = true ) {
  40352. /**
  40353. * If set to `true`, the clock starts automatically when `getDelta()` is called
  40354. * for the first time.
  40355. *
  40356. * @type {boolean}
  40357. * @default true
  40358. */
  40359. this.autoStart = autoStart;
  40360. /**
  40361. * Holds the time at which the clock's `start()` method was last called.
  40362. *
  40363. * @type {number}
  40364. * @default 0
  40365. */
  40366. this.startTime = 0;
  40367. /**
  40368. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  40369. * `getDelta()` methods were last called.
  40370. *
  40371. * @type {number}
  40372. * @default 0
  40373. */
  40374. this.oldTime = 0;
  40375. /**
  40376. * Keeps track of the total time that the clock has been running.
  40377. *
  40378. * @type {number}
  40379. * @default 0
  40380. */
  40381. this.elapsedTime = 0;
  40382. /**
  40383. * Whether the clock is running or not.
  40384. *
  40385. * @type {boolean}
  40386. * @default true
  40387. */
  40388. this.running = false;
  40389. warn( 'THREE.Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  40390. }
  40391. /**
  40392. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  40393. * called by the class.
  40394. */
  40395. start() {
  40396. this.startTime = performance.now();
  40397. this.oldTime = this.startTime;
  40398. this.elapsedTime = 0;
  40399. this.running = true;
  40400. }
  40401. /**
  40402. * Stops the clock.
  40403. */
  40404. stop() {
  40405. this.getElapsedTime();
  40406. this.running = false;
  40407. this.autoStart = false;
  40408. }
  40409. /**
  40410. * Returns the elapsed time in seconds.
  40411. *
  40412. * @return {number} The elapsed time.
  40413. */
  40414. getElapsedTime() {
  40415. this.getDelta();
  40416. return this.elapsedTime;
  40417. }
  40418. /**
  40419. * Returns the delta time in seconds.
  40420. *
  40421. * @return {number} The delta time.
  40422. */
  40423. getDelta() {
  40424. let diff = 0;
  40425. if ( this.autoStart && ! this.running ) {
  40426. this.start();
  40427. return 0;
  40428. }
  40429. if ( this.running ) {
  40430. const newTime = performance.now();
  40431. diff = ( newTime - this.oldTime ) / 1000;
  40432. this.oldTime = newTime;
  40433. this.elapsedTime += diff;
  40434. }
  40435. return diff;
  40436. }
  40437. }
  40438. /**
  40439. * This class can be used to represent points in 3D space as
  40440. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40441. */
  40442. class Spherical {
  40443. /**
  40444. * Constructs a new spherical.
  40445. *
  40446. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40447. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40448. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40449. */
  40450. constructor( radius = 1, phi = 0, theta = 0 ) {
  40451. /**
  40452. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40453. *
  40454. * @type {number}
  40455. * @default 1
  40456. */
  40457. this.radius = radius;
  40458. /**
  40459. * The polar angle in radians from the y (up) axis.
  40460. *
  40461. * @type {number}
  40462. * @default 0
  40463. */
  40464. this.phi = phi;
  40465. /**
  40466. * The equator/azimuthal angle in radians around the y (up) axis.
  40467. *
  40468. * @type {number}
  40469. * @default 0
  40470. */
  40471. this.theta = theta;
  40472. }
  40473. /**
  40474. * Sets the spherical components by copying the given values.
  40475. *
  40476. * @param {number} radius - The radius.
  40477. * @param {number} phi - The polar angle.
  40478. * @param {number} theta - The azimuthal angle.
  40479. * @return {Spherical} A reference to this spherical.
  40480. */
  40481. set( radius, phi, theta ) {
  40482. this.radius = radius;
  40483. this.phi = phi;
  40484. this.theta = theta;
  40485. return this;
  40486. }
  40487. /**
  40488. * Copies the values of the given spherical to this instance.
  40489. *
  40490. * @param {Spherical} other - The spherical to copy.
  40491. * @return {Spherical} A reference to this spherical.
  40492. */
  40493. copy( other ) {
  40494. this.radius = other.radius;
  40495. this.phi = other.phi;
  40496. this.theta = other.theta;
  40497. return this;
  40498. }
  40499. /**
  40500. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40501. * `0.000001`.
  40502. *
  40503. * @return {Spherical} A reference to this spherical.
  40504. */
  40505. makeSafe() {
  40506. const EPS = 0.000001;
  40507. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40508. return this;
  40509. }
  40510. /**
  40511. * Sets the spherical components from the given vector which is assumed to hold
  40512. * Cartesian coordinates.
  40513. *
  40514. * @param {Vector3} v - The vector to set.
  40515. * @return {Spherical} A reference to this spherical.
  40516. */
  40517. setFromVector3( v ) {
  40518. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40519. }
  40520. /**
  40521. * Sets the spherical components from the given Cartesian coordinates.
  40522. *
  40523. * @param {number} x - The x value.
  40524. * @param {number} y - The y value.
  40525. * @param {number} z - The z value.
  40526. * @return {Spherical} A reference to this spherical.
  40527. */
  40528. setFromCartesianCoords( x, y, z ) {
  40529. this.radius = Math.sqrt( x * x + y * y + z * z );
  40530. if ( this.radius === 0 ) {
  40531. this.theta = 0;
  40532. this.phi = 0;
  40533. } else {
  40534. this.theta = Math.atan2( x, z );
  40535. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40536. }
  40537. return this;
  40538. }
  40539. /**
  40540. * Returns a new spherical with copied values from this instance.
  40541. *
  40542. * @return {Spherical} A clone of this instance.
  40543. */
  40544. clone() {
  40545. return new this.constructor().copy( this );
  40546. }
  40547. }
  40548. /**
  40549. * This class can be used to represent points in 3D space as
  40550. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40551. */
  40552. class Cylindrical {
  40553. /**
  40554. * Constructs a new cylindrical.
  40555. *
  40556. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40557. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40558. * @param {number} [y=0] - The height above the x-z plane.
  40559. */
  40560. constructor( radius = 1, theta = 0, y = 0 ) {
  40561. /**
  40562. * The distance from the origin to a point in the x-z plane.
  40563. *
  40564. * @type {number}
  40565. * @default 1
  40566. */
  40567. this.radius = radius;
  40568. /**
  40569. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40570. *
  40571. * @type {number}
  40572. * @default 0
  40573. */
  40574. this.theta = theta;
  40575. /**
  40576. * The height above the x-z plane.
  40577. *
  40578. * @type {number}
  40579. * @default 0
  40580. */
  40581. this.y = y;
  40582. }
  40583. /**
  40584. * Sets the cylindrical components by copying the given values.
  40585. *
  40586. * @param {number} radius - The radius.
  40587. * @param {number} theta - The theta angle.
  40588. * @param {number} y - The height value.
  40589. * @return {Cylindrical} A reference to this cylindrical.
  40590. */
  40591. set( radius, theta, y ) {
  40592. this.radius = radius;
  40593. this.theta = theta;
  40594. this.y = y;
  40595. return this;
  40596. }
  40597. /**
  40598. * Copies the values of the given cylindrical to this instance.
  40599. *
  40600. * @param {Cylindrical} other - The cylindrical to copy.
  40601. * @return {Cylindrical} A reference to this cylindrical.
  40602. */
  40603. copy( other ) {
  40604. this.radius = other.radius;
  40605. this.theta = other.theta;
  40606. this.y = other.y;
  40607. return this;
  40608. }
  40609. /**
  40610. * Sets the cylindrical components from the given vector which is assumed to hold
  40611. * Cartesian coordinates.
  40612. *
  40613. * @param {Vector3} v - The vector to set.
  40614. * @return {Cylindrical} A reference to this cylindrical.
  40615. */
  40616. setFromVector3( v ) {
  40617. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40618. }
  40619. /**
  40620. * Sets the cylindrical components from the given Cartesian coordinates.
  40621. *
  40622. * @param {number} x - The x value.
  40623. * @param {number} y - The x value.
  40624. * @param {number} z - The x value.
  40625. * @return {Cylindrical} A reference to this cylindrical.
  40626. */
  40627. setFromCartesianCoords( x, y, z ) {
  40628. this.radius = Math.sqrt( x * x + z * z );
  40629. this.theta = Math.atan2( x, z );
  40630. this.y = y;
  40631. return this;
  40632. }
  40633. /**
  40634. * Returns a new cylindrical with copied values from this instance.
  40635. *
  40636. * @return {Cylindrical} A clone of this instance.
  40637. */
  40638. clone() {
  40639. return new this.constructor().copy( this );
  40640. }
  40641. }
  40642. /**
  40643. * Represents a 2x2 matrix.
  40644. *
  40645. * A Note on Row-Major and Column-Major Ordering:
  40646. *
  40647. * The constructor and {@link Matrix2#set} method take arguments in
  40648. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40649. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40650. * This means that calling:
  40651. * ```js
  40652. * const m = new THREE.Matrix2();
  40653. * m.set( 11, 12,
  40654. * 21, 22 );
  40655. * ```
  40656. * will result in the elements array containing:
  40657. * ```js
  40658. * m.elements = [ 11, 21,
  40659. * 12, 22 ];
  40660. * ```
  40661. * and internally all calculations are performed using column-major ordering.
  40662. * However, as the actual ordering makes no difference mathematically and
  40663. * most people are used to thinking about matrices in row-major order, the
  40664. * three.js documentation shows matrices in row-major order. Just bear in
  40665. * mind that if you are reading the source code, you'll have to take the
  40666. * transpose of any matrices outlined here to make sense of the calculations.
  40667. */
  40668. class Matrix2 {
  40669. /**
  40670. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40671. * in row-major order. If no arguments are provided, the constructor
  40672. * initializes the matrix as an identity matrix.
  40673. *
  40674. * @param {number} [n11] - 1-1 matrix element.
  40675. * @param {number} [n12] - 1-2 matrix element.
  40676. * @param {number} [n21] - 2-1 matrix element.
  40677. * @param {number} [n22] - 2-2 matrix element.
  40678. */
  40679. constructor( n11, n12, n21, n22 ) {
  40680. /**
  40681. * This flag can be used for type testing.
  40682. *
  40683. * @type {boolean}
  40684. * @readonly
  40685. * @default true
  40686. */
  40687. Matrix2.prototype.isMatrix2 = true;
  40688. /**
  40689. * A column-major list of matrix values.
  40690. *
  40691. * @type {Array<number>}
  40692. */
  40693. this.elements = [
  40694. 1, 0,
  40695. 0, 1,
  40696. ];
  40697. if ( n11 !== undefined ) {
  40698. this.set( n11, n12, n21, n22 );
  40699. }
  40700. }
  40701. /**
  40702. * Sets this matrix to the 2x2 identity matrix.
  40703. *
  40704. * @return {Matrix2} A reference to this matrix.
  40705. */
  40706. identity() {
  40707. this.set(
  40708. 1, 0,
  40709. 0, 1,
  40710. );
  40711. return this;
  40712. }
  40713. /**
  40714. * Sets the elements of the matrix from the given array.
  40715. *
  40716. * @param {Array<number>} array - The matrix elements in column-major order.
  40717. * @param {number} [offset=0] - Index of the first element in the array.
  40718. * @return {Matrix2} A reference to this matrix.
  40719. */
  40720. fromArray( array, offset = 0 ) {
  40721. for ( let i = 0; i < 4; i ++ ) {
  40722. this.elements[ i ] = array[ i + offset ];
  40723. }
  40724. return this;
  40725. }
  40726. /**
  40727. * Sets the elements of the matrix.The arguments are supposed to be
  40728. * in row-major order.
  40729. *
  40730. * @param {number} n11 - 1-1 matrix element.
  40731. * @param {number} n12 - 1-2 matrix element.
  40732. * @param {number} n21 - 2-1 matrix element.
  40733. * @param {number} n22 - 2-2 matrix element.
  40734. * @return {Matrix2} A reference to this matrix.
  40735. */
  40736. set( n11, n12, n21, n22 ) {
  40737. const te = this.elements;
  40738. te[ 0 ] = n11; te[ 2 ] = n12;
  40739. te[ 1 ] = n21; te[ 3 ] = n22;
  40740. return this;
  40741. }
  40742. }
  40743. const _vector$4 = /*@__PURE__*/ new Vector2();
  40744. /**
  40745. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40746. */
  40747. class Box2 {
  40748. /**
  40749. * Constructs a new bounding box.
  40750. *
  40751. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40752. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40753. */
  40754. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40755. /**
  40756. * This flag can be used for type testing.
  40757. *
  40758. * @type {boolean}
  40759. * @readonly
  40760. * @default true
  40761. */
  40762. this.isBox2 = true;
  40763. /**
  40764. * The lower boundary of the box.
  40765. *
  40766. * @type {Vector2}
  40767. */
  40768. this.min = min;
  40769. /**
  40770. * The upper boundary of the box.
  40771. *
  40772. * @type {Vector2}
  40773. */
  40774. this.max = max;
  40775. }
  40776. /**
  40777. * Sets the lower and upper boundaries of this box.
  40778. * Please note that this method only copies the values from the given objects.
  40779. *
  40780. * @param {Vector2} min - The lower boundary of the box.
  40781. * @param {Vector2} max - The upper boundary of the box.
  40782. * @return {Box2} A reference to this bounding box.
  40783. */
  40784. set( min, max ) {
  40785. this.min.copy( min );
  40786. this.max.copy( max );
  40787. return this;
  40788. }
  40789. /**
  40790. * Sets the upper and lower bounds of this box so it encloses the position data
  40791. * in the given array.
  40792. *
  40793. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40794. * @return {Box2} A reference to this bounding box.
  40795. */
  40796. setFromPoints( points ) {
  40797. this.makeEmpty();
  40798. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40799. this.expandByPoint( points[ i ] );
  40800. }
  40801. return this;
  40802. }
  40803. /**
  40804. * Centers this box on the given center vector and sets this box's width, height and
  40805. * depth to the given size values.
  40806. *
  40807. * @param {Vector2} center - The center of the box.
  40808. * @param {Vector2} size - The x and y dimensions of the box.
  40809. * @return {Box2} A reference to this bounding box.
  40810. */
  40811. setFromCenterAndSize( center, size ) {
  40812. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40813. this.min.copy( center ).sub( halfSize );
  40814. this.max.copy( center ).add( halfSize );
  40815. return this;
  40816. }
  40817. /**
  40818. * Returns a new box with copied values from this instance.
  40819. *
  40820. * @return {Box2} A clone of this instance.
  40821. */
  40822. clone() {
  40823. return new this.constructor().copy( this );
  40824. }
  40825. /**
  40826. * Copies the values of the given box to this instance.
  40827. *
  40828. * @param {Box2} box - The box to copy.
  40829. * @return {Box2} A reference to this bounding box.
  40830. */
  40831. copy( box ) {
  40832. this.min.copy( box.min );
  40833. this.max.copy( box.max );
  40834. return this;
  40835. }
  40836. /**
  40837. * Makes this box empty which means in encloses a zero space in 2D.
  40838. *
  40839. * @return {Box2} A reference to this bounding box.
  40840. */
  40841. makeEmpty() {
  40842. this.min.x = this.min.y = + Infinity;
  40843. this.max.x = this.max.y = - Infinity;
  40844. return this;
  40845. }
  40846. /**
  40847. * Returns true if this box includes zero points within its bounds.
  40848. * Note that a box with equal lower and upper bounds still includes one
  40849. * point, the one both bounds share.
  40850. *
  40851. * @return {boolean} Whether this box is empty or not.
  40852. */
  40853. isEmpty() {
  40854. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40855. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40856. }
  40857. /**
  40858. * Returns the center point of this box.
  40859. *
  40860. * @param {Vector2} target - The target vector that is used to store the method's result.
  40861. * @return {Vector2} The center point.
  40862. */
  40863. getCenter( target ) {
  40864. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40865. }
  40866. /**
  40867. * Returns the dimensions of this box.
  40868. *
  40869. * @param {Vector2} target - The target vector that is used to store the method's result.
  40870. * @return {Vector2} The size.
  40871. */
  40872. getSize( target ) {
  40873. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40874. }
  40875. /**
  40876. * Expands the boundaries of this box to include the given point.
  40877. *
  40878. * @param {Vector2} point - The point that should be included by the bounding box.
  40879. * @return {Box2} A reference to this bounding box.
  40880. */
  40881. expandByPoint( point ) {
  40882. this.min.min( point );
  40883. this.max.max( point );
  40884. return this;
  40885. }
  40886. /**
  40887. * Expands this box equilaterally by the given vector. The width of this
  40888. * box will be expanded by the x component of the vector in both
  40889. * directions. The height of this box will be expanded by the y component of
  40890. * the vector in both directions.
  40891. *
  40892. * @param {Vector2} vector - The vector that should expand the bounding box.
  40893. * @return {Box2} A reference to this bounding box.
  40894. */
  40895. expandByVector( vector ) {
  40896. this.min.sub( vector );
  40897. this.max.add( vector );
  40898. return this;
  40899. }
  40900. /**
  40901. * Expands each dimension of the box by the given scalar. If negative, the
  40902. * dimensions of the box will be contracted.
  40903. *
  40904. * @param {number} scalar - The scalar value that should expand the bounding box.
  40905. * @return {Box2} A reference to this bounding box.
  40906. */
  40907. expandByScalar( scalar ) {
  40908. this.min.addScalar( - scalar );
  40909. this.max.addScalar( scalar );
  40910. return this;
  40911. }
  40912. /**
  40913. * Returns `true` if the given point lies within or on the boundaries of this box.
  40914. *
  40915. * @param {Vector2} point - The point to test.
  40916. * @return {boolean} Whether the bounding box contains the given point or not.
  40917. */
  40918. containsPoint( point ) {
  40919. return point.x >= this.min.x && point.x <= this.max.x &&
  40920. point.y >= this.min.y && point.y <= this.max.y;
  40921. }
  40922. /**
  40923. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40924. * If this box and the given one are identical, this function also returns `true`.
  40925. *
  40926. * @param {Box2} box - The bounding box to test.
  40927. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40928. */
  40929. containsBox( box ) {
  40930. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40931. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40932. }
  40933. /**
  40934. * Returns a point as a proportion of this box's width and height.
  40935. *
  40936. * @param {Vector2} point - A point in 2D space.
  40937. * @param {Vector2} target - The target vector that is used to store the method's result.
  40938. * @return {Vector2} A point as a proportion of this box's width and height.
  40939. */
  40940. getParameter( point, target ) {
  40941. // This can potentially have a divide by zero if the box
  40942. // has a size dimension of 0.
  40943. return target.set(
  40944. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40945. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40946. );
  40947. }
  40948. /**
  40949. * Returns `true` if the given bounding box intersects with this bounding box.
  40950. *
  40951. * @param {Box2} box - The bounding box to test.
  40952. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40953. */
  40954. intersectsBox( box ) {
  40955. // using 4 splitting planes to rule out intersections
  40956. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40957. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40958. }
  40959. /**
  40960. * Clamps the given point within the bounds of this box.
  40961. *
  40962. * @param {Vector2} point - The point to clamp.
  40963. * @param {Vector2} target - The target vector that is used to store the method's result.
  40964. * @return {Vector2} The clamped point.
  40965. */
  40966. clampPoint( point, target ) {
  40967. return target.copy( point ).clamp( this.min, this.max );
  40968. }
  40969. /**
  40970. * Returns the euclidean distance from any edge of this box to the specified point. If
  40971. * the given point lies inside of this box, the distance will be `0`.
  40972. *
  40973. * @param {Vector2} point - The point to compute the distance to.
  40974. * @return {number} The euclidean distance.
  40975. */
  40976. distanceToPoint( point ) {
  40977. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40978. }
  40979. /**
  40980. * Computes the intersection of this bounding box and the given one, setting the upper
  40981. * bound of this box to the lesser of the two boxes' upper bounds and the
  40982. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40983. * there's no overlap, makes this box empty.
  40984. *
  40985. * @param {Box2} box - The bounding box to intersect with.
  40986. * @return {Box2} A reference to this bounding box.
  40987. */
  40988. intersect( box ) {
  40989. this.min.max( box.min );
  40990. this.max.min( box.max );
  40991. if ( this.isEmpty() ) this.makeEmpty();
  40992. return this;
  40993. }
  40994. /**
  40995. * Computes the union of this box and another and the given one, setting the upper
  40996. * bound of this box to the greater of the two boxes' upper bounds and the
  40997. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40998. *
  40999. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41000. * @return {Box2} A reference to this bounding box.
  41001. */
  41002. union( box ) {
  41003. this.min.min( box.min );
  41004. this.max.max( box.max );
  41005. return this;
  41006. }
  41007. /**
  41008. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41009. * effectively moving it in 2D space.
  41010. *
  41011. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41012. * @return {Box2} A reference to this bounding box.
  41013. */
  41014. translate( offset ) {
  41015. this.min.add( offset );
  41016. this.max.add( offset );
  41017. return this;
  41018. }
  41019. /**
  41020. * Returns `true` if this bounding box is equal with the given one.
  41021. *
  41022. * @param {Box2} box - The box to test for equality.
  41023. * @return {boolean} Whether this bounding box is equal with the given one.
  41024. */
  41025. equals( box ) {
  41026. return box.min.equals( this.min ) && box.max.equals( this.max );
  41027. }
  41028. }
  41029. const _startP = /*@__PURE__*/ new Vector3();
  41030. const _startEnd = /*@__PURE__*/ new Vector3();
  41031. const _d1 = /*@__PURE__*/ new Vector3();
  41032. const _d2 = /*@__PURE__*/ new Vector3();
  41033. const _r = /*@__PURE__*/ new Vector3();
  41034. const _c1 = /*@__PURE__*/ new Vector3();
  41035. const _c2 = /*@__PURE__*/ new Vector3();
  41036. /**
  41037. * An analytical line segment in 3D space represented by a start and end point.
  41038. */
  41039. class Line3 {
  41040. /**
  41041. * Constructs a new line segment.
  41042. *
  41043. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41044. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41045. */
  41046. constructor( start = new Vector3(), end = new Vector3() ) {
  41047. /**
  41048. * Start of the line segment.
  41049. *
  41050. * @type {Vector3}
  41051. */
  41052. this.start = start;
  41053. /**
  41054. * End of the line segment.
  41055. *
  41056. * @type {Vector3}
  41057. */
  41058. this.end = end;
  41059. }
  41060. /**
  41061. * Sets the start and end values by copying the given vectors.
  41062. *
  41063. * @param {Vector3} start - The start point.
  41064. * @param {Vector3} end - The end point.
  41065. * @return {Line3} A reference to this line segment.
  41066. */
  41067. set( start, end ) {
  41068. this.start.copy( start );
  41069. this.end.copy( end );
  41070. return this;
  41071. }
  41072. /**
  41073. * Copies the values of the given line segment to this instance.
  41074. *
  41075. * @param {Line3} line - The line segment to copy.
  41076. * @return {Line3} A reference to this line segment.
  41077. */
  41078. copy( line ) {
  41079. this.start.copy( line.start );
  41080. this.end.copy( line.end );
  41081. return this;
  41082. }
  41083. /**
  41084. * Returns the center of the line segment.
  41085. *
  41086. * @param {Vector3} target - The target vector that is used to store the method's result.
  41087. * @return {Vector3} The center point.
  41088. */
  41089. getCenter( target ) {
  41090. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41091. }
  41092. /**
  41093. * Returns the delta vector of the line segment's start and end point.
  41094. *
  41095. * @param {Vector3} target - The target vector that is used to store the method's result.
  41096. * @return {Vector3} The delta vector.
  41097. */
  41098. delta( target ) {
  41099. return target.subVectors( this.end, this.start );
  41100. }
  41101. /**
  41102. * Returns the squared Euclidean distance between the line' start and end point.
  41103. *
  41104. * @return {number} The squared Euclidean distance.
  41105. */
  41106. distanceSq() {
  41107. return this.start.distanceToSquared( this.end );
  41108. }
  41109. /**
  41110. * Returns the Euclidean distance between the line' start and end point.
  41111. *
  41112. * @return {number} The Euclidean distance.
  41113. */
  41114. distance() {
  41115. return this.start.distanceTo( this.end );
  41116. }
  41117. /**
  41118. * Returns a vector at a certain position along the line segment.
  41119. *
  41120. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41121. * @param {Vector3} target - The target vector that is used to store the method's result.
  41122. * @return {Vector3} The delta vector.
  41123. */
  41124. at( t, target ) {
  41125. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41126. }
  41127. /**
  41128. * Returns a point parameter based on the closest point as projected on the line segment.
  41129. *
  41130. * @param {Vector3} point - The point for which to return a point parameter.
  41131. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41132. * @return {number} The point parameter.
  41133. */
  41134. closestPointToPointParameter( point, clampToLine ) {
  41135. _startP.subVectors( point, this.start );
  41136. _startEnd.subVectors( this.end, this.start );
  41137. const startEnd2 = _startEnd.dot( _startEnd );
  41138. const startEnd_startP = _startEnd.dot( _startP );
  41139. let t = startEnd_startP / startEnd2;
  41140. if ( clampToLine ) {
  41141. t = clamp( t, 0, 1 );
  41142. }
  41143. return t;
  41144. }
  41145. /**
  41146. * Returns the closest point on the line for a given point.
  41147. *
  41148. * @param {Vector3} point - The point to compute the closest point on the line for.
  41149. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41150. * @param {Vector3} target - The target vector that is used to store the method's result.
  41151. * @return {Vector3} The closest point on the line.
  41152. */
  41153. closestPointToPoint( point, clampToLine, target ) {
  41154. const t = this.closestPointToPointParameter( point, clampToLine );
  41155. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41156. }
  41157. /**
  41158. * Returns the closest squared distance between this line segment and the given one.
  41159. *
  41160. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41161. * @param {Vector3} [c1] - The closest point on this line segment.
  41162. * @param {Vector3} [c2] - The closest point on the given line segment.
  41163. * @return {number} The squared distance between this line segment and the given one.
  41164. */
  41165. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41166. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41167. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41168. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41169. // distance between between S1(s) and S2(t)
  41170. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41171. let s, t;
  41172. const p1 = this.start;
  41173. const p2 = line.start;
  41174. const q1 = this.end;
  41175. const q2 = line.end;
  41176. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41177. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41178. _r.subVectors( p1, p2 );
  41179. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41180. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41181. const f = _d2.dot( _r );
  41182. // Check if either or both segments degenerate into points
  41183. if ( a <= EPSILON && e <= EPSILON ) {
  41184. // Both segments degenerate into points
  41185. c1.copy( p1 );
  41186. c2.copy( p2 );
  41187. c1.sub( c2 );
  41188. return c1.dot( c1 );
  41189. }
  41190. if ( a <= EPSILON ) {
  41191. // First segment degenerates into a point
  41192. s = 0;
  41193. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41194. t = clamp( t, 0, 1 );
  41195. } else {
  41196. const c = _d1.dot( _r );
  41197. if ( e <= EPSILON ) {
  41198. // Second segment degenerates into a point
  41199. t = 0;
  41200. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41201. } else {
  41202. // The general nondegenerate case starts here
  41203. const b = _d1.dot( _d2 );
  41204. const denom = a * e - b * b; // Always nonnegative
  41205. // If segments not parallel, compute closest point on L1 to L2 and
  41206. // clamp to segment S1. Else pick arbitrary s (here 0)
  41207. if ( denom !== 0 ) {
  41208. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41209. } else {
  41210. s = 0;
  41211. }
  41212. // Compute point on L2 closest to S1(s) using
  41213. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41214. t = ( b * s + f ) / e;
  41215. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41216. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41217. // and clamp s to [0, 1]
  41218. if ( t < 0 ) {
  41219. t = 0.;
  41220. s = clamp( - c / a, 0, 1 );
  41221. } else if ( t > 1 ) {
  41222. t = 1;
  41223. s = clamp( ( b - c ) / a, 0, 1 );
  41224. }
  41225. }
  41226. }
  41227. c1.copy( p1 ).addScaledVector( _d1, s );
  41228. c2.copy( p2 ).addScaledVector( _d2, t );
  41229. return c1.distanceToSquared( c2 );
  41230. }
  41231. /**
  41232. * Applies a 4x4 transformation matrix to this line segment.
  41233. *
  41234. * @param {Matrix4} matrix - The transformation matrix.
  41235. * @return {Line3} A reference to this line segment.
  41236. */
  41237. applyMatrix4( matrix ) {
  41238. this.start.applyMatrix4( matrix );
  41239. this.end.applyMatrix4( matrix );
  41240. return this;
  41241. }
  41242. /**
  41243. * Returns `true` if this line segment is equal with the given one.
  41244. *
  41245. * @param {Line3} line - The line segment to test for equality.
  41246. * @return {boolean} Whether this line segment is equal with the given one.
  41247. */
  41248. equals( line ) {
  41249. return line.start.equals( this.start ) && line.end.equals( this.end );
  41250. }
  41251. /**
  41252. * Returns a new line segment with copied values from this instance.
  41253. *
  41254. * @return {Line3} A clone of this instance.
  41255. */
  41256. clone() {
  41257. return new this.constructor().copy( this );
  41258. }
  41259. }
  41260. const _vector$3 = /*@__PURE__*/ new Vector3();
  41261. /**
  41262. * This displays a cone shaped helper object for a {@link SpotLight}.
  41263. *
  41264. * When the spot light or its target are transformed or light properties are
  41265. * changed, it's necessary to call the `update()` method of the respective helper.
  41266. *
  41267. * ```js
  41268. * const spotLight = new THREE.SpotLight( 0xffffff );
  41269. * spotLight.position.set( 10, 10, 10 );
  41270. * scene.add( spotLight );
  41271. *
  41272. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41273. * scene.add( spotLightHelper );
  41274. * ```
  41275. *
  41276. * @augments Object3D
  41277. */
  41278. class SpotLightHelper extends Object3D {
  41279. /**
  41280. * Constructs a new spot light helper.
  41281. *
  41282. * @param {HemisphereLight} light - The light to be visualized.
  41283. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41284. * the color of the light.
  41285. */
  41286. constructor( light, color ) {
  41287. super();
  41288. /**
  41289. * The light being visualized.
  41290. *
  41291. * @type {SpotLight}
  41292. */
  41293. this.light = light;
  41294. this.matrixAutoUpdate = false;
  41295. /**
  41296. * The color parameter passed in the constructor.
  41297. * If not set, the helper will take the color of the light.
  41298. *
  41299. * @type {number|Color|string}
  41300. */
  41301. this.color = color;
  41302. this.type = 'SpotLightHelper';
  41303. const geometry = new BufferGeometry();
  41304. const positions = [
  41305. 0, 0, 0, 0, 0, 1,
  41306. 0, 0, 0, 1, 0, 1,
  41307. 0, 0, 0, -1, 0, 1,
  41308. 0, 0, 0, 0, 1, 1,
  41309. 0, 0, 0, 0, -1, 1
  41310. ];
  41311. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41312. const p1 = ( i / l ) * Math.PI * 2;
  41313. const p2 = ( j / l ) * Math.PI * 2;
  41314. positions.push(
  41315. Math.cos( p1 ), Math.sin( p1 ), 1,
  41316. Math.cos( p2 ), Math.sin( p2 ), 1
  41317. );
  41318. }
  41319. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41320. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41321. this.cone = new LineSegments( geometry, material );
  41322. this.add( this.cone );
  41323. this.update();
  41324. }
  41325. /**
  41326. * Frees the GPU-related resources allocated by this instance. Call this
  41327. * method whenever this instance is no longer used in your app.
  41328. */
  41329. dispose() {
  41330. this.cone.geometry.dispose();
  41331. this.cone.material.dispose();
  41332. }
  41333. /**
  41334. * Updates the helper to match the position and direction of the
  41335. * light being visualized.
  41336. */
  41337. update() {
  41338. this.light.updateWorldMatrix( true, false );
  41339. this.light.target.updateWorldMatrix( true, false );
  41340. // update the local matrix based on the parent and light target transforms
  41341. if ( this.parent ) {
  41342. this.parent.updateWorldMatrix( true );
  41343. this.matrix
  41344. .copy( this.parent.matrixWorld )
  41345. .invert()
  41346. .multiply( this.light.matrixWorld );
  41347. } else {
  41348. this.matrix.copy( this.light.matrixWorld );
  41349. }
  41350. this.matrixWorld.copy( this.light.matrixWorld );
  41351. const coneLength = this.light.distance ? this.light.distance : 1000;
  41352. const coneWidth = coneLength * Math.tan( this.light.angle );
  41353. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41354. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41355. this.cone.lookAt( _vector$3 );
  41356. if ( this.color !== undefined ) {
  41357. this.cone.material.color.set( this.color );
  41358. } else {
  41359. this.cone.material.color.copy( this.light.color );
  41360. }
  41361. }
  41362. }
  41363. const _vector$2 = /*@__PURE__*/ new Vector3();
  41364. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41365. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41366. /**
  41367. * A helper object to assist with visualizing a {@link Skeleton}.
  41368. *
  41369. * ```js
  41370. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41371. * scene.add( helper );
  41372. * ```
  41373. *
  41374. * @augments LineSegments
  41375. */
  41376. class SkeletonHelper extends LineSegments {
  41377. /**
  41378. * Constructs a new skeleton helper.
  41379. *
  41380. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41381. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41382. */
  41383. constructor( object ) {
  41384. const bones = getBoneList( object );
  41385. const geometry = new BufferGeometry();
  41386. const vertices = [];
  41387. const colors = [];
  41388. for ( let i = 0; i < bones.length; i ++ ) {
  41389. const bone = bones[ i ];
  41390. if ( bone.parent && bone.parent.isBone ) {
  41391. vertices.push( 0, 0, 0 );
  41392. vertices.push( 0, 0, 0 );
  41393. colors.push( 0, 0, 0 );
  41394. colors.push( 0, 0, 0 );
  41395. }
  41396. }
  41397. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41398. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41399. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41400. super( geometry, material );
  41401. /**
  41402. * This flag can be used for type testing.
  41403. *
  41404. * @type {boolean}
  41405. * @readonly
  41406. * @default true
  41407. */
  41408. this.isSkeletonHelper = true;
  41409. this.type = 'SkeletonHelper';
  41410. /**
  41411. * The object being visualized.
  41412. *
  41413. * @type {Object3D}
  41414. */
  41415. this.root = object;
  41416. /**
  41417. * The list of bones that the helper visualizes.
  41418. *
  41419. * @type {Array<Bone>}
  41420. */
  41421. this.bones = bones;
  41422. this.matrix = object.matrixWorld;
  41423. this.matrixAutoUpdate = false;
  41424. // colors
  41425. const color1 = new Color( 0x0000ff );
  41426. const color2 = new Color( 0x00ff00 );
  41427. this.setColors( color1, color2 );
  41428. }
  41429. updateMatrixWorld( force ) {
  41430. const bones = this.bones;
  41431. const geometry = this.geometry;
  41432. const position = geometry.getAttribute( 'position' );
  41433. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41434. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41435. const bone = bones[ i ];
  41436. if ( bone.parent && bone.parent.isBone ) {
  41437. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41438. _vector$2.setFromMatrixPosition( _boneMatrix );
  41439. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41440. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41441. _vector$2.setFromMatrixPosition( _boneMatrix );
  41442. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41443. j += 2;
  41444. }
  41445. }
  41446. geometry.getAttribute( 'position' ).needsUpdate = true;
  41447. super.updateMatrixWorld( force );
  41448. }
  41449. /**
  41450. * Defines the colors of the helper.
  41451. *
  41452. * @param {Color} color1 - The first line color for each bone.
  41453. * @param {Color} color2 - The second line color for each bone.
  41454. * @return {SkeletonHelper} A reference to this helper.
  41455. */
  41456. setColors( color1, color2 ) {
  41457. const geometry = this.geometry;
  41458. const colorAttribute = geometry.getAttribute( 'color' );
  41459. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41460. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41461. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41462. }
  41463. colorAttribute.needsUpdate = true;
  41464. return this;
  41465. }
  41466. /**
  41467. * Frees the GPU-related resources allocated by this instance. Call this
  41468. * method whenever this instance is no longer used in your app.
  41469. */
  41470. dispose() {
  41471. this.geometry.dispose();
  41472. this.material.dispose();
  41473. }
  41474. }
  41475. function getBoneList( object ) {
  41476. const boneList = [];
  41477. if ( object.isBone === true ) {
  41478. boneList.push( object );
  41479. }
  41480. for ( let i = 0; i < object.children.length; i ++ ) {
  41481. boneList.push( ...getBoneList( object.children[ i ] ) );
  41482. }
  41483. return boneList;
  41484. }
  41485. /**
  41486. * This displays a helper object consisting of a spherical mesh for
  41487. * visualizing an instance of {@link PointLight}.
  41488. *
  41489. * ```js
  41490. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41491. * pointLight.position.set( 10, 10, 10 );
  41492. * scene.add( pointLight );
  41493. *
  41494. * const sphereSize = 1;
  41495. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41496. * scene.add( pointLightHelper );
  41497. * ```
  41498. *
  41499. * @augments Mesh
  41500. */
  41501. class PointLightHelper extends Mesh {
  41502. /**
  41503. * Constructs a new point light helper.
  41504. *
  41505. * @param {PointLight} light - The light to be visualized.
  41506. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41507. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41508. * the color of the light.
  41509. */
  41510. constructor( light, sphereSize, color ) {
  41511. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41512. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41513. super( geometry, material );
  41514. /**
  41515. * The light being visualized.
  41516. *
  41517. * @type {PointLight}
  41518. */
  41519. this.light = light;
  41520. /**
  41521. * The color parameter passed in the constructor.
  41522. * If not set, the helper will take the color of the light.
  41523. *
  41524. * @type {number|Color|string}
  41525. */
  41526. this.color = color;
  41527. this.type = 'PointLightHelper';
  41528. this.matrix = this.light.matrixWorld;
  41529. this.matrixAutoUpdate = false;
  41530. this.update();
  41531. }
  41532. /**
  41533. * Frees the GPU-related resources allocated by this instance. Call this
  41534. * method whenever this instance is no longer used in your app.
  41535. */
  41536. dispose() {
  41537. this.geometry.dispose();
  41538. this.material.dispose();
  41539. }
  41540. /**
  41541. * Updates the helper to match the position of the
  41542. * light being visualized.
  41543. */
  41544. update() {
  41545. this.light.updateWorldMatrix( true, false );
  41546. if ( this.color !== undefined ) {
  41547. this.material.color.set( this.color );
  41548. } else {
  41549. this.material.color.copy( this.light.color );
  41550. }
  41551. /*
  41552. const d = this.light.distance;
  41553. if ( d === 0.0 ) {
  41554. this.lightDistance.visible = false;
  41555. } else {
  41556. this.lightDistance.visible = true;
  41557. this.lightDistance.scale.set( d, d, d );
  41558. }
  41559. */
  41560. }
  41561. }
  41562. const _vector$1 = /*@__PURE__*/ new Vector3();
  41563. const _color1 = /*@__PURE__*/ new Color();
  41564. const _color2 = /*@__PURE__*/ new Color();
  41565. /**
  41566. * Creates a visual aid consisting of a spherical mesh for a
  41567. * given {@link HemisphereLight}.
  41568. *
  41569. * When the hemisphere light is transformed or its light properties are changed,
  41570. * it's necessary to call the `update()` method of the respective helper.
  41571. *
  41572. * ```js
  41573. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41574. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41575. * scene.add( helper );
  41576. * ```
  41577. *
  41578. * @augments Object3D
  41579. */
  41580. class HemisphereLightHelper extends Object3D {
  41581. /**
  41582. * Constructs a new hemisphere light helper.
  41583. *
  41584. * @param {HemisphereLight} light - The light to be visualized.
  41585. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41586. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41587. * the color of the light.
  41588. */
  41589. constructor( light, size, color ) {
  41590. super();
  41591. /**
  41592. * The light being visualized.
  41593. *
  41594. * @type {HemisphereLight}
  41595. */
  41596. this.light = light;
  41597. this.matrix = light.matrixWorld;
  41598. this.matrixAutoUpdate = false;
  41599. /**
  41600. * The color parameter passed in the constructor.
  41601. * If not set, the helper will take the color of the light.
  41602. *
  41603. * @type {number|Color|string}
  41604. */
  41605. this.color = color;
  41606. this.type = 'HemisphereLightHelper';
  41607. const geometry = new OctahedronGeometry( size );
  41608. geometry.rotateY( Math.PI * 0.5 );
  41609. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41610. if ( this.color === undefined ) this.material.vertexColors = true;
  41611. const position = geometry.getAttribute( 'position' );
  41612. const colors = new Float32Array( position.count * 3 );
  41613. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41614. this.add( new Mesh( geometry, this.material ) );
  41615. this.update();
  41616. }
  41617. /**
  41618. * Frees the GPU-related resources allocated by this instance. Call this
  41619. * method whenever this instance is no longer used in your app.
  41620. */
  41621. dispose() {
  41622. this.children[ 0 ].geometry.dispose();
  41623. this.children[ 0 ].material.dispose();
  41624. }
  41625. /**
  41626. * Updates the helper to match the position and direction of the
  41627. * light being visualized.
  41628. */
  41629. update() {
  41630. const mesh = this.children[ 0 ];
  41631. if ( this.color !== undefined ) {
  41632. this.material.color.set( this.color );
  41633. } else {
  41634. const colors = mesh.geometry.getAttribute( 'color' );
  41635. _color1.copy( this.light.color );
  41636. _color2.copy( this.light.groundColor );
  41637. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41638. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41639. colors.setXYZ( i, color.r, color.g, color.b );
  41640. }
  41641. colors.needsUpdate = true;
  41642. }
  41643. this.light.updateWorldMatrix( true, false );
  41644. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41645. }
  41646. }
  41647. /**
  41648. * The helper is an object to define grids. Grids are two-dimensional
  41649. * arrays of lines.
  41650. *
  41651. * ```js
  41652. * const size = 10;
  41653. * const divisions = 10;
  41654. *
  41655. * const gridHelper = new THREE.GridHelper( size, divisions );
  41656. * scene.add( gridHelper );
  41657. * ```
  41658. *
  41659. * @augments LineSegments
  41660. */
  41661. class GridHelper extends LineSegments {
  41662. /**
  41663. * Constructs a new grid helper.
  41664. *
  41665. * @param {number} [size=10] - The size of the grid.
  41666. * @param {number} [divisions=10] - The number of divisions across the grid.
  41667. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41668. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41669. */
  41670. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41671. color1 = new Color( color1 );
  41672. color2 = new Color( color2 );
  41673. const center = divisions / 2;
  41674. const step = size / divisions;
  41675. const halfSize = size / 2;
  41676. const vertices = [], colors = [];
  41677. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41678. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41679. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41680. const color = i === center ? color1 : color2;
  41681. color.toArray( colors, j ); j += 3;
  41682. color.toArray( colors, j ); j += 3;
  41683. color.toArray( colors, j ); j += 3;
  41684. color.toArray( colors, j ); j += 3;
  41685. }
  41686. const geometry = new BufferGeometry();
  41687. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41688. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41689. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41690. super( geometry, material );
  41691. this.type = 'GridHelper';
  41692. }
  41693. /**
  41694. * Frees the GPU-related resources allocated by this instance. Call this
  41695. * method whenever this instance is no longer used in your app.
  41696. */
  41697. dispose() {
  41698. this.geometry.dispose();
  41699. this.material.dispose();
  41700. }
  41701. }
  41702. /**
  41703. * This helper is an object to define polar grids. Grids are
  41704. * two-dimensional arrays of lines.
  41705. *
  41706. * ```js
  41707. * const radius = 10;
  41708. * const sectors = 16;
  41709. * const rings = 8;
  41710. * const divisions = 64;
  41711. *
  41712. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41713. * scene.add( helper );
  41714. * ```
  41715. *
  41716. * @augments LineSegments
  41717. */
  41718. class PolarGridHelper extends LineSegments {
  41719. /**
  41720. * Constructs a new polar grid helper.
  41721. *
  41722. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41723. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41724. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41725. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41726. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41727. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41728. */
  41729. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41730. color1 = new Color( color1 );
  41731. color2 = new Color( color2 );
  41732. const vertices = [];
  41733. const colors = [];
  41734. // create the sectors
  41735. if ( sectors > 1 ) {
  41736. for ( let i = 0; i < sectors; i ++ ) {
  41737. const v = ( i / sectors ) * ( Math.PI * 2 );
  41738. const x = Math.sin( v ) * radius;
  41739. const z = Math.cos( v ) * radius;
  41740. vertices.push( 0, 0, 0 );
  41741. vertices.push( x, 0, z );
  41742. const color = ( i & 1 ) ? color1 : color2;
  41743. colors.push( color.r, color.g, color.b );
  41744. colors.push( color.r, color.g, color.b );
  41745. }
  41746. }
  41747. // create the rings
  41748. for ( let i = 0; i < rings; i ++ ) {
  41749. const color = ( i & 1 ) ? color1 : color2;
  41750. const r = radius - ( radius / rings * i );
  41751. for ( let j = 0; j < divisions; j ++ ) {
  41752. // first vertex
  41753. let v = ( j / divisions ) * ( Math.PI * 2 );
  41754. let x = Math.sin( v ) * r;
  41755. let z = Math.cos( v ) * r;
  41756. vertices.push( x, 0, z );
  41757. colors.push( color.r, color.g, color.b );
  41758. // second vertex
  41759. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41760. x = Math.sin( v ) * r;
  41761. z = Math.cos( v ) * r;
  41762. vertices.push( x, 0, z );
  41763. colors.push( color.r, color.g, color.b );
  41764. }
  41765. }
  41766. const geometry = new BufferGeometry();
  41767. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41768. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41769. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41770. super( geometry, material );
  41771. this.type = 'PolarGridHelper';
  41772. }
  41773. /**
  41774. * Frees the GPU-related resources allocated by this instance. Call this
  41775. * method whenever this instance is no longer used in your app.
  41776. */
  41777. dispose() {
  41778. this.geometry.dispose();
  41779. this.material.dispose();
  41780. }
  41781. }
  41782. const _v1 = /*@__PURE__*/ new Vector3();
  41783. const _v2 = /*@__PURE__*/ new Vector3();
  41784. const _v3 = /*@__PURE__*/ new Vector3();
  41785. /**
  41786. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41787. * effect on the scene. This consists of a plane and a line representing the
  41788. * light's position and direction.
  41789. *
  41790. * When the directional light or its target are transformed or light properties
  41791. * are changed, it's necessary to call the `update()` method of the respective helper.
  41792. *
  41793. * ```js
  41794. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41795. * scene.add( light );
  41796. *
  41797. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41798. * scene.add( helper );
  41799. * ```
  41800. *
  41801. * @augments Object3D
  41802. */
  41803. class DirectionalLightHelper extends Object3D {
  41804. /**
  41805. * Constructs a new directional light helper.
  41806. *
  41807. * @param {DirectionalLight} light - The light to be visualized.
  41808. * @param {number} [size=1] - The dimensions of the plane.
  41809. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41810. * the color of the light.
  41811. */
  41812. constructor( light, size, color ) {
  41813. super();
  41814. /**
  41815. * The light being visualized.
  41816. *
  41817. * @type {DirectionalLight}
  41818. */
  41819. this.light = light;
  41820. this.matrix = light.matrixWorld;
  41821. this.matrixAutoUpdate = false;
  41822. /**
  41823. * The color parameter passed in the constructor.
  41824. * If not set, the helper will take the color of the light.
  41825. *
  41826. * @type {number|Color|string}
  41827. */
  41828. this.color = color;
  41829. this.type = 'DirectionalLightHelper';
  41830. if ( size === undefined ) size = 1;
  41831. let geometry = new BufferGeometry();
  41832. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41833. - size, size, 0,
  41834. size, size, 0,
  41835. size, - size, 0,
  41836. - size, - size, 0,
  41837. - size, size, 0
  41838. ], 3 ) );
  41839. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41840. /**
  41841. * Contains the line showing the location of the directional light.
  41842. *
  41843. * @type {Line}
  41844. */
  41845. this.lightPlane = new Line( geometry, material );
  41846. this.add( this.lightPlane );
  41847. geometry = new BufferGeometry();
  41848. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41849. /**
  41850. * Represents the target line of the directional light.
  41851. *
  41852. * @type {Line}
  41853. */
  41854. this.targetLine = new Line( geometry, material );
  41855. this.add( this.targetLine );
  41856. this.update();
  41857. }
  41858. /**
  41859. * Frees the GPU-related resources allocated by this instance. Call this
  41860. * method whenever this instance is no longer used in your app.
  41861. */
  41862. dispose() {
  41863. this.lightPlane.geometry.dispose();
  41864. this.lightPlane.material.dispose();
  41865. this.targetLine.geometry.dispose();
  41866. this.targetLine.material.dispose();
  41867. }
  41868. /**
  41869. * Updates the helper to match the position and direction of the
  41870. * light being visualized.
  41871. */
  41872. update() {
  41873. this.light.updateWorldMatrix( true, false );
  41874. this.light.target.updateWorldMatrix( true, false );
  41875. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41876. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41877. _v3.subVectors( _v2, _v1 );
  41878. this.lightPlane.lookAt( _v2 );
  41879. if ( this.color !== undefined ) {
  41880. this.lightPlane.material.color.set( this.color );
  41881. this.targetLine.material.color.set( this.color );
  41882. } else {
  41883. this.lightPlane.material.color.copy( this.light.color );
  41884. this.targetLine.material.color.copy( this.light.color );
  41885. }
  41886. this.targetLine.lookAt( _v2 );
  41887. this.targetLine.scale.z = _v3.length();
  41888. }
  41889. }
  41890. const _vector = /*@__PURE__*/ new Vector3();
  41891. const _camera = /*@__PURE__*/ new Camera();
  41892. /**
  41893. * This helps with visualizing what a camera contains in its frustum. It
  41894. * visualizes the frustum of a camera using a line segments.
  41895. *
  41896. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41897. *
  41898. * `CameraHelper` must be a child of the scene.
  41899. *
  41900. * When the camera is transformed or its projection matrix is changed, it's necessary
  41901. * to call the `update()` method of the respective helper.
  41902. *
  41903. * ```js
  41904. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41905. * const helper = new THREE.CameraHelper( camera );
  41906. * scene.add( helper );
  41907. * ```
  41908. *
  41909. * @augments LineSegments
  41910. */
  41911. class CameraHelper extends LineSegments {
  41912. /**
  41913. * Constructs a new arrow helper.
  41914. *
  41915. * @param {Camera} camera - The camera to visualize.
  41916. */
  41917. constructor( camera ) {
  41918. const geometry = new BufferGeometry();
  41919. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41920. const vertices = [];
  41921. const colors = [];
  41922. const pointMap = {};
  41923. // near
  41924. addLine( 'n1', 'n2' );
  41925. addLine( 'n2', 'n4' );
  41926. addLine( 'n4', 'n3' );
  41927. addLine( 'n3', 'n1' );
  41928. // far
  41929. addLine( 'f1', 'f2' );
  41930. addLine( 'f2', 'f4' );
  41931. addLine( 'f4', 'f3' );
  41932. addLine( 'f3', 'f1' );
  41933. // sides
  41934. addLine( 'n1', 'f1' );
  41935. addLine( 'n2', 'f2' );
  41936. addLine( 'n3', 'f3' );
  41937. addLine( 'n4', 'f4' );
  41938. // cone
  41939. addLine( 'p', 'n1' );
  41940. addLine( 'p', 'n2' );
  41941. addLine( 'p', 'n3' );
  41942. addLine( 'p', 'n4' );
  41943. // up
  41944. addLine( 'u1', 'u2' );
  41945. addLine( 'u2', 'u3' );
  41946. addLine( 'u3', 'u1' );
  41947. // target
  41948. addLine( 'c', 't' );
  41949. addLine( 'p', 'c' );
  41950. // cross
  41951. addLine( 'cn1', 'cn2' );
  41952. addLine( 'cn3', 'cn4' );
  41953. addLine( 'cf1', 'cf2' );
  41954. addLine( 'cf3', 'cf4' );
  41955. function addLine( a, b ) {
  41956. addPoint( a );
  41957. addPoint( b );
  41958. }
  41959. function addPoint( id ) {
  41960. vertices.push( 0, 0, 0 );
  41961. colors.push( 0, 0, 0 );
  41962. if ( pointMap[ id ] === undefined ) {
  41963. pointMap[ id ] = [];
  41964. }
  41965. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41966. }
  41967. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41968. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41969. super( geometry, material );
  41970. this.type = 'CameraHelper';
  41971. /**
  41972. * The camera being visualized.
  41973. *
  41974. * @type {Camera}
  41975. */
  41976. this.camera = camera;
  41977. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41978. this.matrix = camera.matrixWorld;
  41979. this.matrixAutoUpdate = false;
  41980. /**
  41981. * This contains the points used to visualize the camera.
  41982. *
  41983. * @type {Object<string,Array<number>>}
  41984. */
  41985. this.pointMap = pointMap;
  41986. this.update();
  41987. // colors
  41988. const colorFrustum = new Color( 0xffaa00 );
  41989. const colorCone = new Color( 0xff0000 );
  41990. const colorUp = new Color( 0x00aaff );
  41991. const colorTarget = new Color( 0xffffff );
  41992. const colorCross = new Color( 0x333333 );
  41993. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41994. }
  41995. /**
  41996. * Defines the colors of the helper.
  41997. *
  41998. * @param {Color} frustum - The frustum line color.
  41999. * @param {Color} cone - The cone line color.
  42000. * @param {Color} up - The up line color.
  42001. * @param {Color} target - The target line color.
  42002. * @param {Color} cross - The cross line color.
  42003. * @return {CameraHelper} A reference to this helper.
  42004. */
  42005. setColors( frustum, cone, up, target, cross ) {
  42006. const geometry = this.geometry;
  42007. const colorAttribute = geometry.getAttribute( 'color' );
  42008. // near
  42009. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42010. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42011. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42012. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42013. // far
  42014. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42015. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42016. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42017. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42018. // sides
  42019. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42020. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42021. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42022. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42023. // cone
  42024. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42025. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42026. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42027. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42028. // up
  42029. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42030. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42031. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42032. // target
  42033. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42034. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42035. // cross
  42036. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42037. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42038. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42039. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42040. colorAttribute.needsUpdate = true;
  42041. return this;
  42042. }
  42043. /**
  42044. * Updates the helper based on the projection matrix of the camera.
  42045. */
  42046. update() {
  42047. const geometry = this.geometry;
  42048. const pointMap = this.pointMap;
  42049. const w = 1, h = 1;
  42050. let nearZ, farZ;
  42051. // we need just camera projection matrix inverse
  42052. // world matrix must be identity
  42053. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42054. // Adjust z values based on coordinate system
  42055. if ( this.camera.reversedDepth === true ) {
  42056. nearZ = 1;
  42057. farZ = 0;
  42058. } else {
  42059. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42060. nearZ = -1;
  42061. farZ = 1;
  42062. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42063. nearZ = 0;
  42064. farZ = 1;
  42065. } else {
  42066. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42067. }
  42068. }
  42069. // center / target
  42070. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42071. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42072. // near
  42073. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42074. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42075. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42076. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42077. // far
  42078. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42079. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42080. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42081. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42082. // up
  42083. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42084. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42085. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42086. // cross
  42087. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42088. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42089. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42090. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42091. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42092. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42093. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42094. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42095. geometry.getAttribute( 'position' ).needsUpdate = true;
  42096. }
  42097. /**
  42098. * Frees the GPU-related resources allocated by this instance. Call this
  42099. * method whenever this instance is no longer used in your app.
  42100. */
  42101. dispose() {
  42102. this.geometry.dispose();
  42103. this.material.dispose();
  42104. }
  42105. }
  42106. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42107. _vector.set( x, y, z ).unproject( camera );
  42108. const points = pointMap[ point ];
  42109. if ( points !== undefined ) {
  42110. const position = geometry.getAttribute( 'position' );
  42111. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42112. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42113. }
  42114. }
  42115. }
  42116. const _box = /*@__PURE__*/ new Box3();
  42117. /**
  42118. * Helper object to graphically show the world-axis-aligned bounding box
  42119. * around an object. The actual bounding box is handled with {@link Box3},
  42120. * this is just a visual helper for debugging. It can be automatically
  42121. * resized with {@link BoxHelper#update} when the object it's created from
  42122. * is transformed. Note that the object must have a geometry for this to work,
  42123. * so it won't work with sprites.
  42124. *
  42125. * ```js
  42126. * const sphere = new THREE.SphereGeometry();
  42127. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42128. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42129. * scene.add( box );
  42130. * ```
  42131. *
  42132. * @augments LineSegments
  42133. */
  42134. class BoxHelper extends LineSegments {
  42135. /**
  42136. * Constructs a new box helper.
  42137. *
  42138. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42139. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42140. */
  42141. constructor( object, color = 0xffff00 ) {
  42142. 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 ] );
  42143. const positions = new Float32Array( 8 * 3 );
  42144. const geometry = new BufferGeometry();
  42145. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42146. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42147. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42148. /**
  42149. * The 3D object being visualized.
  42150. *
  42151. * @type {Object3D}
  42152. */
  42153. this.object = object;
  42154. this.type = 'BoxHelper';
  42155. this.matrixAutoUpdate = false;
  42156. this.update();
  42157. }
  42158. /**
  42159. * Updates the helper's geometry to match the dimensions of the object,
  42160. * including any children.
  42161. */
  42162. update() {
  42163. if ( this.object !== undefined ) {
  42164. _box.setFromObject( this.object );
  42165. }
  42166. if ( _box.isEmpty() ) return;
  42167. const min = _box.min;
  42168. const max = _box.max;
  42169. /*
  42170. 5____4
  42171. 1/___0/|
  42172. | 6__|_7
  42173. 2/___3/
  42174. 0: max.x, max.y, max.z
  42175. 1: min.x, max.y, max.z
  42176. 2: min.x, min.y, max.z
  42177. 3: max.x, min.y, max.z
  42178. 4: max.x, max.y, min.z
  42179. 5: min.x, max.y, min.z
  42180. 6: min.x, min.y, min.z
  42181. 7: max.x, min.y, min.z
  42182. */
  42183. const position = this.geometry.attributes.position;
  42184. const array = position.array;
  42185. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42186. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42187. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42188. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42189. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42190. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42191. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42192. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42193. position.needsUpdate = true;
  42194. this.geometry.computeBoundingSphere();
  42195. }
  42196. /**
  42197. * Updates the wireframe box for the passed object.
  42198. *
  42199. * @param {Object3D} object - The 3D object to create the helper for.
  42200. * @return {BoxHelper} A reference to this instance.
  42201. */
  42202. setFromObject( object ) {
  42203. this.object = object;
  42204. this.update();
  42205. return this;
  42206. }
  42207. copy( source, recursive ) {
  42208. super.copy( source, recursive );
  42209. this.object = source.object;
  42210. return this;
  42211. }
  42212. /**
  42213. * Frees the GPU-related resources allocated by this instance. Call this
  42214. * method whenever this instance is no longer used in your app.
  42215. */
  42216. dispose() {
  42217. this.geometry.dispose();
  42218. this.material.dispose();
  42219. }
  42220. }
  42221. /**
  42222. * A helper object to visualize an instance of {@link Box3}.
  42223. *
  42224. * ```js
  42225. * const box = new THREE.Box3();
  42226. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42227. *
  42228. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42229. * scene.add( helper )
  42230. * ```
  42231. *
  42232. * @augments LineSegments
  42233. */
  42234. class Box3Helper extends LineSegments {
  42235. /**
  42236. * Constructs a new box3 helper.
  42237. *
  42238. * @param {Box3} box - The box to visualize.
  42239. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42240. */
  42241. constructor( box, color = 0xffff00 ) {
  42242. 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 ] );
  42243. 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 ];
  42244. const geometry = new BufferGeometry();
  42245. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42246. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42247. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42248. /**
  42249. * The box being visualized.
  42250. *
  42251. * @type {Box3}
  42252. */
  42253. this.box = box;
  42254. this.type = 'Box3Helper';
  42255. this.geometry.computeBoundingSphere();
  42256. }
  42257. updateMatrixWorld( force ) {
  42258. const box = this.box;
  42259. if ( box.isEmpty() ) return;
  42260. box.getCenter( this.position );
  42261. box.getSize( this.scale );
  42262. this.scale.multiplyScalar( 0.5 );
  42263. super.updateMatrixWorld( force );
  42264. }
  42265. /**
  42266. * Frees the GPU-related resources allocated by this instance. Call this
  42267. * method whenever this instance is no longer used in your app.
  42268. */
  42269. dispose() {
  42270. this.geometry.dispose();
  42271. this.material.dispose();
  42272. }
  42273. }
  42274. /**
  42275. * A helper object to visualize an instance of {@link Plane}.
  42276. *
  42277. * ```js
  42278. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42279. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42280. * scene.add( helper );
  42281. * ```
  42282. *
  42283. * @augments Line
  42284. */
  42285. class PlaneHelper extends Line {
  42286. /**
  42287. * Constructs a new plane helper.
  42288. *
  42289. * @param {Plane} plane - The plane to be visualized.
  42290. * @param {number} [size=1] - The side length of plane helper.
  42291. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42292. */
  42293. constructor( plane, size = 1, hex = 0xffff00 ) {
  42294. const color = hex;
  42295. 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 ];
  42296. const geometry = new BufferGeometry();
  42297. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42298. geometry.computeBoundingSphere();
  42299. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42300. this.type = 'PlaneHelper';
  42301. /**
  42302. * The plane being visualized.
  42303. *
  42304. * @type {Plane}
  42305. */
  42306. this.plane = plane;
  42307. /**
  42308. * The side length of plane helper.
  42309. *
  42310. * @type {number}
  42311. * @default 1
  42312. */
  42313. this.size = size;
  42314. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42315. const geometry2 = new BufferGeometry();
  42316. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42317. geometry2.computeBoundingSphere();
  42318. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42319. }
  42320. updateMatrixWorld( force ) {
  42321. this.position.set( 0, 0, 0 );
  42322. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42323. this.lookAt( this.plane.normal );
  42324. this.translateZ( - this.plane.constant );
  42325. super.updateMatrixWorld( force );
  42326. }
  42327. /**
  42328. * Updates the helper to match the position and direction of the
  42329. * light being visualized.
  42330. */
  42331. dispose() {
  42332. this.geometry.dispose();
  42333. this.material.dispose();
  42334. this.children[ 0 ].geometry.dispose();
  42335. this.children[ 0 ].material.dispose();
  42336. }
  42337. }
  42338. const _axis = /*@__PURE__*/ new Vector3();
  42339. let _lineGeometry, _coneGeometry;
  42340. /**
  42341. * An 3D arrow object for visualizing directions.
  42342. *
  42343. * ```js
  42344. * const dir = new THREE.Vector3( 1, 2, 0 );
  42345. *
  42346. * //normalize the direction vector (convert to vector of length 1)
  42347. * dir.normalize();
  42348. *
  42349. * const origin = new THREE.Vector3( 0, 0, 0 );
  42350. * const length = 1;
  42351. * const hex = 0xffff00;
  42352. *
  42353. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42354. * scene.add( arrowHelper );
  42355. * ```
  42356. *
  42357. * @augments Object3D
  42358. */
  42359. class ArrowHelper extends Object3D {
  42360. /**
  42361. * Constructs a new arrow helper.
  42362. *
  42363. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42364. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42365. * @param {number} [length=1] - Length of the arrow in world units.
  42366. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42367. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42368. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42369. */
  42370. 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 ) {
  42371. super();
  42372. this.type = 'ArrowHelper';
  42373. if ( _lineGeometry === undefined ) {
  42374. _lineGeometry = new BufferGeometry();
  42375. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42376. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42377. _coneGeometry.translate( 0, -0.5, 0 );
  42378. }
  42379. this.position.copy( origin );
  42380. /**
  42381. * The line part of the arrow helper.
  42382. *
  42383. * @type {Line}
  42384. */
  42385. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42386. this.line.matrixAutoUpdate = false;
  42387. this.add( this.line );
  42388. /**
  42389. * The cone part of the arrow helper.
  42390. *
  42391. * @type {Mesh}
  42392. */
  42393. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42394. this.cone.matrixAutoUpdate = false;
  42395. this.add( this.cone );
  42396. this.setDirection( dir );
  42397. this.setLength( length, headLength, headWidth );
  42398. }
  42399. /**
  42400. * Sets the direction of the helper.
  42401. *
  42402. * @param {Vector3} dir - The normalized direction vector.
  42403. */
  42404. setDirection( dir ) {
  42405. // dir is assumed to be normalized
  42406. if ( dir.y > 0.99999 ) {
  42407. this.quaternion.set( 0, 0, 0, 1 );
  42408. } else if ( dir.y < -0.99999 ) {
  42409. this.quaternion.set( 1, 0, 0, 0 );
  42410. } else {
  42411. _axis.set( dir.z, 0, - dir.x ).normalize();
  42412. const radians = Math.acos( dir.y );
  42413. this.quaternion.setFromAxisAngle( _axis, radians );
  42414. }
  42415. }
  42416. /**
  42417. * Sets the length of the helper.
  42418. *
  42419. * @param {number} length - Length of the arrow in world units.
  42420. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42421. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42422. */
  42423. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42424. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42425. this.line.updateMatrix();
  42426. this.cone.scale.set( headWidth, headLength, headWidth );
  42427. this.cone.position.y = length;
  42428. this.cone.updateMatrix();
  42429. }
  42430. /**
  42431. * Sets the color of the helper.
  42432. *
  42433. * @param {number|Color|string} color - The color to set.
  42434. */
  42435. setColor( color ) {
  42436. this.line.material.color.set( color );
  42437. this.cone.material.color.set( color );
  42438. }
  42439. copy( source ) {
  42440. super.copy( source, false );
  42441. this.line.copy( source.line );
  42442. this.cone.copy( source.cone );
  42443. return this;
  42444. }
  42445. /**
  42446. * Frees the GPU-related resources allocated by this instance. Call this
  42447. * method whenever this instance is no longer used in your app.
  42448. */
  42449. dispose() {
  42450. this.line.geometry.dispose();
  42451. this.line.material.dispose();
  42452. this.cone.geometry.dispose();
  42453. this.cone.material.dispose();
  42454. }
  42455. }
  42456. /**
  42457. * An axis object to visualize the 3 axes in a simple way.
  42458. * The X axis is red. The Y axis is green. The Z axis is blue.
  42459. *
  42460. * ```js
  42461. * const axesHelper = new THREE.AxesHelper( 5 );
  42462. * scene.add( axesHelper );
  42463. * ```
  42464. *
  42465. * @augments LineSegments
  42466. */
  42467. class AxesHelper extends LineSegments {
  42468. /**
  42469. * Constructs a new axes helper.
  42470. *
  42471. * @param {number} [size=1] - Size of the lines representing the axes.
  42472. */
  42473. constructor( size = 1 ) {
  42474. const vertices = [
  42475. 0, 0, 0, size, 0, 0,
  42476. 0, 0, 0, 0, size, 0,
  42477. 0, 0, 0, 0, 0, size
  42478. ];
  42479. const colors = [
  42480. 1, 0, 0, 1, 0.6, 0,
  42481. 0, 1, 0, 0.6, 1, 0,
  42482. 0, 0, 1, 0, 0.6, 1
  42483. ];
  42484. const geometry = new BufferGeometry();
  42485. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42486. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42487. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42488. super( geometry, material );
  42489. this.type = 'AxesHelper';
  42490. }
  42491. /**
  42492. * Defines the colors of the axes helper.
  42493. *
  42494. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42495. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42496. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42497. * @return {AxesHelper} A reference to this axes helper.
  42498. */
  42499. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42500. const color = new Color();
  42501. const array = this.geometry.attributes.color.array;
  42502. color.set( xAxisColor );
  42503. color.toArray( array, 0 );
  42504. color.toArray( array, 3 );
  42505. color.set( yAxisColor );
  42506. color.toArray( array, 6 );
  42507. color.toArray( array, 9 );
  42508. color.set( zAxisColor );
  42509. color.toArray( array, 12 );
  42510. color.toArray( array, 15 );
  42511. this.geometry.attributes.color.needsUpdate = true;
  42512. return this;
  42513. }
  42514. /**
  42515. * Frees the GPU-related resources allocated by this instance. Call this
  42516. * method whenever this instance is no longer used in your app.
  42517. */
  42518. dispose() {
  42519. this.geometry.dispose();
  42520. this.material.dispose();
  42521. }
  42522. }
  42523. /**
  42524. * This class is used to convert a series of paths to an array of
  42525. * shapes. It is specifically used in context of fonts and SVG.
  42526. */
  42527. class ShapePath {
  42528. /**
  42529. * Constructs a new shape path.
  42530. */
  42531. constructor() {
  42532. this.type = 'ShapePath';
  42533. /**
  42534. * The color of the shape.
  42535. *
  42536. * @type {Color}
  42537. */
  42538. this.color = new Color();
  42539. /**
  42540. * The paths that have been generated for this shape.
  42541. *
  42542. * @type {Array<Path>}
  42543. * @default null
  42544. */
  42545. this.subPaths = [];
  42546. /**
  42547. * The current path that is being generated.
  42548. *
  42549. * @type {?Path}
  42550. * @default null
  42551. */
  42552. this.currentPath = null;
  42553. }
  42554. /**
  42555. * Creates a new path and moves it current point to the given one.
  42556. *
  42557. * @param {number} x - The x coordinate.
  42558. * @param {number} y - The y coordinate.
  42559. * @return {ShapePath} A reference to this shape path.
  42560. */
  42561. moveTo( x, y ) {
  42562. this.currentPath = new Path();
  42563. this.subPaths.push( this.currentPath );
  42564. this.currentPath.moveTo( x, y );
  42565. return this;
  42566. }
  42567. /**
  42568. * Adds an instance of {@link LineCurve} to the path by connecting
  42569. * the current point with the given one.
  42570. *
  42571. * @param {number} x - The x coordinate of the end point.
  42572. * @param {number} y - The y coordinate of the end point.
  42573. * @return {ShapePath} A reference to this shape path.
  42574. */
  42575. lineTo( x, y ) {
  42576. this.currentPath.lineTo( x, y );
  42577. return this;
  42578. }
  42579. /**
  42580. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42581. * the current point with the given one.
  42582. *
  42583. * @param {number} aCPx - The x coordinate of the control point.
  42584. * @param {number} aCPy - The y coordinate of the control point.
  42585. * @param {number} aX - The x coordinate of the end point.
  42586. * @param {number} aY - The y coordinate of the end point.
  42587. * @return {ShapePath} A reference to this shape path.
  42588. */
  42589. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42590. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42591. return this;
  42592. }
  42593. /**
  42594. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42595. * the current point with the given one.
  42596. *
  42597. * @param {number} aCP1x - The x coordinate of the first control point.
  42598. * @param {number} aCP1y - The y coordinate of the first control point.
  42599. * @param {number} aCP2x - The x coordinate of the second control point.
  42600. * @param {number} aCP2y - The y coordinate of the second control point.
  42601. * @param {number} aX - The x coordinate of the end point.
  42602. * @param {number} aY - The y coordinate of the end point.
  42603. * @return {ShapePath} A reference to this shape path.
  42604. */
  42605. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42606. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42607. return this;
  42608. }
  42609. /**
  42610. * Adds an instance of {@link SplineCurve} to the path by connecting
  42611. * the current point with the given list of points.
  42612. *
  42613. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42614. * @return {ShapePath} A reference to this shape path.
  42615. */
  42616. splineThru( pts ) {
  42617. this.currentPath.splineThru( pts );
  42618. return this;
  42619. }
  42620. /**
  42621. * Converts the paths into an array of shapes.
  42622. *
  42623. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42624. * If this flag is set to `true`, then those are flipped.
  42625. * @return {Array<Shape>} An array of shapes.
  42626. */
  42627. toShapes( isCCW ) {
  42628. function toShapesNoHoles( inSubpaths ) {
  42629. const shapes = [];
  42630. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42631. const tmpPath = inSubpaths[ i ];
  42632. const tmpShape = new Shape();
  42633. tmpShape.curves = tmpPath.curves;
  42634. shapes.push( tmpShape );
  42635. }
  42636. return shapes;
  42637. }
  42638. function isPointInsidePolygon( inPt, inPolygon ) {
  42639. const polyLen = inPolygon.length;
  42640. // inPt on polygon contour => immediate success or
  42641. // toggling of inside/outside at every single! intersection point of an edge
  42642. // with the horizontal line through inPt, left of inPt
  42643. // not counting lowerY endpoints of edges and whole edges on that line
  42644. let inside = false;
  42645. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42646. let edgeLowPt = inPolygon[ p ];
  42647. let edgeHighPt = inPolygon[ q ];
  42648. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42649. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42650. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42651. // not parallel
  42652. if ( edgeDy < 0 ) {
  42653. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42654. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42655. }
  42656. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42657. if ( inPt.y === edgeLowPt.y ) {
  42658. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42659. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42660. } else {
  42661. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42662. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42663. if ( perpEdge < 0 ) continue;
  42664. inside = ! inside; // true intersection left of inPt
  42665. }
  42666. } else {
  42667. // parallel or collinear
  42668. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42669. // edge lies on the same horizontal line as inPt
  42670. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42671. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42672. // continue;
  42673. }
  42674. }
  42675. return inside;
  42676. }
  42677. const isClockWise = ShapeUtils.isClockWise;
  42678. const subPaths = this.subPaths;
  42679. if ( subPaths.length === 0 ) return [];
  42680. let solid, tmpPath, tmpShape;
  42681. const shapes = [];
  42682. if ( subPaths.length === 1 ) {
  42683. tmpPath = subPaths[ 0 ];
  42684. tmpShape = new Shape();
  42685. tmpShape.curves = tmpPath.curves;
  42686. shapes.push( tmpShape );
  42687. return shapes;
  42688. }
  42689. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42690. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42691. // log("Holes first", holesFirst);
  42692. const betterShapeHoles = [];
  42693. const newShapes = [];
  42694. let newShapeHoles = [];
  42695. let mainIdx = 0;
  42696. let tmpPoints;
  42697. newShapes[ mainIdx ] = undefined;
  42698. newShapeHoles[ mainIdx ] = [];
  42699. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42700. tmpPath = subPaths[ i ];
  42701. tmpPoints = tmpPath.getPoints();
  42702. solid = isClockWise( tmpPoints );
  42703. solid = isCCW ? ! solid : solid;
  42704. if ( solid ) {
  42705. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42706. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42707. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42708. if ( holesFirst ) mainIdx ++;
  42709. newShapeHoles[ mainIdx ] = [];
  42710. //log('cw', i);
  42711. } else {
  42712. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42713. //log('ccw', i);
  42714. }
  42715. }
  42716. // only Holes? -> probably all Shapes with wrong orientation
  42717. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42718. if ( newShapes.length > 1 ) {
  42719. let ambiguous = false;
  42720. let toChange = 0;
  42721. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42722. betterShapeHoles[ sIdx ] = [];
  42723. }
  42724. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42725. const sho = newShapeHoles[ sIdx ];
  42726. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42727. const ho = sho[ hIdx ];
  42728. let hole_unassigned = true;
  42729. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42730. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42731. if ( sIdx !== s2Idx ) toChange ++;
  42732. if ( hole_unassigned ) {
  42733. hole_unassigned = false;
  42734. betterShapeHoles[ s2Idx ].push( ho );
  42735. } else {
  42736. ambiguous = true;
  42737. }
  42738. }
  42739. }
  42740. if ( hole_unassigned ) {
  42741. betterShapeHoles[ sIdx ].push( ho );
  42742. }
  42743. }
  42744. }
  42745. if ( toChange > 0 && ambiguous === false ) {
  42746. newShapeHoles = betterShapeHoles;
  42747. }
  42748. }
  42749. let tmpHoles;
  42750. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42751. tmpShape = newShapes[ i ].s;
  42752. shapes.push( tmpShape );
  42753. tmpHoles = newShapeHoles[ i ];
  42754. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42755. tmpShape.holes.push( tmpHoles[ j ].h );
  42756. }
  42757. }
  42758. //log("shape", shapes);
  42759. return shapes;
  42760. }
  42761. }
  42762. /**
  42763. * Abstract base class for controls.
  42764. *
  42765. * @abstract
  42766. * @augments EventDispatcher
  42767. */
  42768. class Controls extends EventDispatcher {
  42769. /**
  42770. * Constructs a new controls instance.
  42771. *
  42772. * @param {Object3D} object - The object that is managed by the controls.
  42773. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42774. */
  42775. constructor( object, domElement = null ) {
  42776. super();
  42777. /**
  42778. * The object that is managed by the controls.
  42779. *
  42780. * @type {Object3D}
  42781. */
  42782. this.object = object;
  42783. /**
  42784. * The HTML element used for event listeners.
  42785. *
  42786. * @type {?HTMLElement}
  42787. * @default null
  42788. */
  42789. this.domElement = domElement;
  42790. /**
  42791. * Whether the controls responds to user input or not.
  42792. *
  42793. * @type {boolean}
  42794. * @default true
  42795. */
  42796. this.enabled = true;
  42797. /**
  42798. * The internal state of the controls.
  42799. *
  42800. * @type {number}
  42801. * @default -1
  42802. */
  42803. this.state = -1;
  42804. /**
  42805. * This object defines the keyboard input of the controls.
  42806. *
  42807. * @type {Object}
  42808. */
  42809. this.keys = {};
  42810. /**
  42811. * This object defines what type of actions are assigned to the available mouse buttons.
  42812. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42813. *
  42814. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42815. */
  42816. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42817. /**
  42818. * This object defines what type of actions are assigned to what kind of touch interaction.
  42819. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42820. *
  42821. * @type {{ONE: ?number, TWO: ?number}}
  42822. */
  42823. this.touches = { ONE: null, TWO: null };
  42824. }
  42825. /**
  42826. * Connects the controls to the DOM. This method has so called "side effects" since
  42827. * it adds the module's event listeners to the DOM.
  42828. *
  42829. * @param {HTMLElement} element - The DOM element to connect to.
  42830. */
  42831. connect( element ) {
  42832. if ( element === undefined ) {
  42833. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42834. return;
  42835. }
  42836. if ( this.domElement !== null ) this.disconnect();
  42837. this.domElement = element;
  42838. }
  42839. /**
  42840. * Disconnects the controls from the DOM.
  42841. */
  42842. disconnect() {}
  42843. /**
  42844. * Call this method if you no longer want use to the controls. It frees all internal
  42845. * resources and removes all event listeners.
  42846. */
  42847. dispose() {}
  42848. /**
  42849. * Controls should implement this method if they have to update their internal state
  42850. * per simulation step.
  42851. *
  42852. * @param {number} [delta] - The time delta in seconds.
  42853. */
  42854. update( /* delta */ ) {}
  42855. }
  42856. /**
  42857. * Scales the texture as large as possible within its surface without cropping
  42858. * or stretching the texture. The method preserves the original aspect ratio of
  42859. * the texture. Akin to CSS `object-fit: contain`
  42860. *
  42861. * @param {Texture} texture - The texture.
  42862. * @param {number} aspect - The texture's aspect ratio.
  42863. * @return {Texture} The updated texture.
  42864. */
  42865. function contain( texture, aspect ) {
  42866. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42867. if ( imageAspect > aspect ) {
  42868. texture.repeat.x = 1;
  42869. texture.repeat.y = imageAspect / aspect;
  42870. texture.offset.x = 0;
  42871. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42872. } else {
  42873. texture.repeat.x = aspect / imageAspect;
  42874. texture.repeat.y = 1;
  42875. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42876. texture.offset.y = 0;
  42877. }
  42878. return texture;
  42879. }
  42880. /**
  42881. * Scales the texture to the smallest possible size to fill the surface, leaving
  42882. * no empty space. The method preserves the original aspect ratio of the texture.
  42883. * Akin to CSS `object-fit: cover`.
  42884. *
  42885. * @param {Texture} texture - The texture.
  42886. * @param {number} aspect - The texture's aspect ratio.
  42887. * @return {Texture} The updated texture.
  42888. */
  42889. function cover( texture, aspect ) {
  42890. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42891. if ( imageAspect > aspect ) {
  42892. texture.repeat.x = aspect / imageAspect;
  42893. texture.repeat.y = 1;
  42894. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42895. texture.offset.y = 0;
  42896. } else {
  42897. texture.repeat.x = 1;
  42898. texture.repeat.y = imageAspect / aspect;
  42899. texture.offset.x = 0;
  42900. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42901. }
  42902. return texture;
  42903. }
  42904. /**
  42905. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42906. *
  42907. * @param {Texture} texture - The texture.
  42908. * @return {Texture} The updated texture.
  42909. */
  42910. function fill( texture ) {
  42911. texture.repeat.x = 1;
  42912. texture.repeat.y = 1;
  42913. texture.offset.x = 0;
  42914. texture.offset.y = 0;
  42915. return texture;
  42916. }
  42917. /**
  42918. * Determines how many bytes must be used to represent the texture.
  42919. *
  42920. * @param {number} width - The width of the texture.
  42921. * @param {number} height - The height of the texture.
  42922. * @param {number} format - The texture's format.
  42923. * @param {number} type - The texture's type.
  42924. * @return {number} The byte length.
  42925. */
  42926. function getByteLength( width, height, format, type ) {
  42927. const typeByteLength = getTextureTypeByteLength( type );
  42928. switch ( format ) {
  42929. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42930. case AlphaFormat:
  42931. return width * height;
  42932. case RedFormat:
  42933. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42934. case RedIntegerFormat:
  42935. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42936. case RGFormat:
  42937. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42938. case RGIntegerFormat:
  42939. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42940. case RGBFormat:
  42941. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42942. case RGBAFormat:
  42943. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42944. case RGBAIntegerFormat:
  42945. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42946. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42947. case RGB_S3TC_DXT1_Format:
  42948. case RGBA_S3TC_DXT1_Format:
  42949. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42950. case RGBA_S3TC_DXT3_Format:
  42951. case RGBA_S3TC_DXT5_Format:
  42952. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42953. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42954. case RGB_PVRTC_2BPPV1_Format:
  42955. case RGBA_PVRTC_2BPPV1_Format:
  42956. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42957. case RGB_PVRTC_4BPPV1_Format:
  42958. case RGBA_PVRTC_4BPPV1_Format:
  42959. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42960. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42961. case RGB_ETC1_Format:
  42962. case RGB_ETC2_Format:
  42963. case R11_EAC_Format:
  42964. case SIGNED_R11_EAC_Format:
  42965. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42966. case RGBA_ETC2_EAC_Format:
  42967. case RG11_EAC_Format:
  42968. case SIGNED_RG11_EAC_Format:
  42969. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42970. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42971. case RGBA_ASTC_4x4_Format:
  42972. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42973. case RGBA_ASTC_5x4_Format:
  42974. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42975. case RGBA_ASTC_5x5_Format:
  42976. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42977. case RGBA_ASTC_6x5_Format:
  42978. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42979. case RGBA_ASTC_6x6_Format:
  42980. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42981. case RGBA_ASTC_8x5_Format:
  42982. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42983. case RGBA_ASTC_8x6_Format:
  42984. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42985. case RGBA_ASTC_8x8_Format:
  42986. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42987. case RGBA_ASTC_10x5_Format:
  42988. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42989. case RGBA_ASTC_10x6_Format:
  42990. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42991. case RGBA_ASTC_10x8_Format:
  42992. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42993. case RGBA_ASTC_10x10_Format:
  42994. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42995. case RGBA_ASTC_12x10_Format:
  42996. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42997. case RGBA_ASTC_12x12_Format:
  42998. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42999. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43000. case RGBA_BPTC_Format:
  43001. case RGB_BPTC_SIGNED_Format:
  43002. case RGB_BPTC_UNSIGNED_Format:
  43003. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43004. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43005. case RED_RGTC1_Format:
  43006. case SIGNED_RED_RGTC1_Format:
  43007. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43008. case RED_GREEN_RGTC2_Format:
  43009. case SIGNED_RED_GREEN_RGTC2_Format:
  43010. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43011. }
  43012. throw new Error(
  43013. `Unable to determine texture byte length for ${format} format.`,
  43014. );
  43015. }
  43016. function getTextureTypeByteLength( type ) {
  43017. switch ( type ) {
  43018. case UnsignedByteType:
  43019. case ByteType:
  43020. return { byteLength: 1, components: 1 };
  43021. case UnsignedShortType:
  43022. case ShortType:
  43023. case HalfFloatType:
  43024. return { byteLength: 2, components: 1 };
  43025. case UnsignedShort4444Type:
  43026. case UnsignedShort5551Type:
  43027. return { byteLength: 2, components: 4 };
  43028. case UnsignedIntType:
  43029. case IntType:
  43030. case FloatType:
  43031. return { byteLength: 4, components: 1 };
  43032. case UnsignedInt5999Type:
  43033. case UnsignedInt101111Type:
  43034. return { byteLength: 4, components: 3 };
  43035. }
  43036. throw new Error( `Unknown texture type ${type}.` );
  43037. }
  43038. /**
  43039. * A class containing utility functions for textures.
  43040. *
  43041. * @hideconstructor
  43042. */
  43043. class TextureUtils {
  43044. /**
  43045. * Scales the texture as large as possible within its surface without cropping
  43046. * or stretching the texture. The method preserves the original aspect ratio of
  43047. * the texture. Akin to CSS `object-fit: contain`
  43048. *
  43049. * @param {Texture} texture - The texture.
  43050. * @param {number} aspect - The texture's aspect ratio.
  43051. * @return {Texture} The updated texture.
  43052. */
  43053. static contain( texture, aspect ) {
  43054. return contain( texture, aspect );
  43055. }
  43056. /**
  43057. * Scales the texture to the smallest possible size to fill the surface, leaving
  43058. * no empty space. The method preserves the original aspect ratio of the texture.
  43059. * Akin to CSS `object-fit: cover`.
  43060. *
  43061. * @param {Texture} texture - The texture.
  43062. * @param {number} aspect - The texture's aspect ratio.
  43063. * @return {Texture} The updated texture.
  43064. */
  43065. static cover( texture, aspect ) {
  43066. return cover( texture, aspect );
  43067. }
  43068. /**
  43069. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43070. *
  43071. * @param {Texture} texture - The texture.
  43072. * @return {Texture} The updated texture.
  43073. */
  43074. static fill( texture ) {
  43075. return fill( texture );
  43076. }
  43077. /**
  43078. * Determines how many bytes must be used to represent the texture.
  43079. *
  43080. * @param {number} width - The width of the texture.
  43081. * @param {number} height - The height of the texture.
  43082. * @param {number} format - The texture's format.
  43083. * @param {number} type - The texture's type.
  43084. * @return {number} The byte length.
  43085. */
  43086. static getByteLength( width, height, format, type ) {
  43087. return getByteLength( width, height, format, type );
  43088. }
  43089. }
  43090. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43091. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43092. revision: REVISION,
  43093. } } ) );
  43094. }
  43095. if ( typeof window !== 'undefined' ) {
  43096. if ( window.__THREE__ ) {
  43097. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43098. } else {
  43099. window.__THREE__ = REVISION;
  43100. }
  43101. }
  43102. function WebGLAnimation() {
  43103. let context = null;
  43104. let isAnimating = false;
  43105. let animationLoop = null;
  43106. let requestId = null;
  43107. function onAnimationFrame( time, frame ) {
  43108. animationLoop( time, frame );
  43109. requestId = context.requestAnimationFrame( onAnimationFrame );
  43110. }
  43111. return {
  43112. start: function () {
  43113. if ( isAnimating === true ) return;
  43114. if ( animationLoop === null ) return;
  43115. requestId = context.requestAnimationFrame( onAnimationFrame );
  43116. isAnimating = true;
  43117. },
  43118. stop: function () {
  43119. context.cancelAnimationFrame( requestId );
  43120. isAnimating = false;
  43121. },
  43122. setAnimationLoop: function ( callback ) {
  43123. animationLoop = callback;
  43124. },
  43125. setContext: function ( value ) {
  43126. context = value;
  43127. }
  43128. };
  43129. }
  43130. function WebGLAttributes( gl ) {
  43131. const buffers = new WeakMap();
  43132. function createBuffer( attribute, bufferType ) {
  43133. const array = attribute.array;
  43134. const usage = attribute.usage;
  43135. const size = array.byteLength;
  43136. const buffer = gl.createBuffer();
  43137. gl.bindBuffer( bufferType, buffer );
  43138. gl.bufferData( bufferType, array, usage );
  43139. attribute.onUploadCallback();
  43140. let type;
  43141. if ( array instanceof Float32Array ) {
  43142. type = gl.FLOAT;
  43143. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  43144. type = gl.HALF_FLOAT;
  43145. } else if ( array instanceof Uint16Array ) {
  43146. if ( attribute.isFloat16BufferAttribute ) {
  43147. type = gl.HALF_FLOAT;
  43148. } else {
  43149. type = gl.UNSIGNED_SHORT;
  43150. }
  43151. } else if ( array instanceof Int16Array ) {
  43152. type = gl.SHORT;
  43153. } else if ( array instanceof Uint32Array ) {
  43154. type = gl.UNSIGNED_INT;
  43155. } else if ( array instanceof Int32Array ) {
  43156. type = gl.INT;
  43157. } else if ( array instanceof Int8Array ) {
  43158. type = gl.BYTE;
  43159. } else if ( array instanceof Uint8Array ) {
  43160. type = gl.UNSIGNED_BYTE;
  43161. } else if ( array instanceof Uint8ClampedArray ) {
  43162. type = gl.UNSIGNED_BYTE;
  43163. } else {
  43164. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  43165. }
  43166. return {
  43167. buffer: buffer,
  43168. type: type,
  43169. bytesPerElement: array.BYTES_PER_ELEMENT,
  43170. version: attribute.version,
  43171. size: size
  43172. };
  43173. }
  43174. function updateBuffer( buffer, attribute, bufferType ) {
  43175. const array = attribute.array;
  43176. const updateRanges = attribute.updateRanges;
  43177. gl.bindBuffer( bufferType, buffer );
  43178. if ( updateRanges.length === 0 ) {
  43179. // Not using update ranges
  43180. gl.bufferSubData( bufferType, 0, array );
  43181. } else {
  43182. // Before applying update ranges, we merge any adjacent / overlapping
  43183. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  43184. // to performance improvements for applications which make heavy use of
  43185. // update ranges. Likely due to GPU command overhead.
  43186. //
  43187. // Note that to reduce garbage collection between frames, we merge the
  43188. // update ranges in-place. This is safe because this method will clear the
  43189. // update ranges once updated.
  43190. updateRanges.sort( ( a, b ) => a.start - b.start );
  43191. // To merge the update ranges in-place, we work from left to right in the
  43192. // existing updateRanges array, merging ranges. This may result in a final
  43193. // array which is smaller than the original. This index tracks the last
  43194. // index representing a merged range, any data after this index can be
  43195. // trimmed once the merge algorithm is completed.
  43196. let mergeIndex = 0;
  43197. for ( let i = 1; i < updateRanges.length; i ++ ) {
  43198. const previousRange = updateRanges[ mergeIndex ];
  43199. const range = updateRanges[ i ];
  43200. // We add one here to merge adjacent ranges. This is safe because ranges
  43201. // operate over positive integers.
  43202. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  43203. previousRange.count = Math.max(
  43204. previousRange.count,
  43205. range.start + range.count - previousRange.start
  43206. );
  43207. } else {
  43208. ++ mergeIndex;
  43209. updateRanges[ mergeIndex ] = range;
  43210. }
  43211. }
  43212. // Trim the array to only contain the merged ranges.
  43213. updateRanges.length = mergeIndex + 1;
  43214. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43215. const range = updateRanges[ i ];
  43216. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  43217. array, range.start, range.count );
  43218. }
  43219. attribute.clearUpdateRanges();
  43220. }
  43221. attribute.onUploadCallback();
  43222. }
  43223. //
  43224. function get( attribute ) {
  43225. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43226. return buffers.get( attribute );
  43227. }
  43228. function remove( attribute ) {
  43229. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43230. const data = buffers.get( attribute );
  43231. if ( data ) {
  43232. gl.deleteBuffer( data.buffer );
  43233. buffers.delete( attribute );
  43234. }
  43235. }
  43236. function update( attribute, bufferType ) {
  43237. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43238. if ( attribute.isGLBufferAttribute ) {
  43239. const cached = buffers.get( attribute );
  43240. if ( ! cached || cached.version < attribute.version ) {
  43241. buffers.set( attribute, {
  43242. buffer: attribute.buffer,
  43243. type: attribute.type,
  43244. bytesPerElement: attribute.elementSize,
  43245. version: attribute.version
  43246. } );
  43247. }
  43248. return;
  43249. }
  43250. const data = buffers.get( attribute );
  43251. if ( data === undefined ) {
  43252. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  43253. } else if ( data.version < attribute.version ) {
  43254. if ( data.size !== attribute.array.byteLength ) {
  43255. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  43256. }
  43257. updateBuffer( data.buffer, attribute, bufferType );
  43258. data.version = attribute.version;
  43259. }
  43260. }
  43261. return {
  43262. get: get,
  43263. remove: remove,
  43264. update: update
  43265. };
  43266. }
  43267. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  43268. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  43269. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  43270. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  43271. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  43272. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  43273. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  43274. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  43275. var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec4 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 );\n\t}\n#endif";
  43276. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  43277. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  43278. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  43279. var bsdfs = "float 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} // validated";
  43280. 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\treturn 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 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";
  43281. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + 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 = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( 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";
  43282. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  43283. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  43284. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  43285. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  43286. var color_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif";
  43287. var color_pars_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif";
  43288. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif";
  43289. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif";
  43290. 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};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\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}\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}\nvec3 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} // validated";
  43291. 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_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\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";
  43292. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  43293. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  43294. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  43295. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  43296. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  43297. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  43298. var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( 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}";
  43299. 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, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\n\t#endif\n#endif";
  43300. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif";
  43301. 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";
  43302. 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";
  43303. 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";
  43304. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  43305. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  43306. 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";
  43307. 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";
  43308. 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}";
  43309. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  43310. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  43311. 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  43312. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\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\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\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, 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 vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\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 vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\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";
  43313. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * 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\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  43314. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  43315. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  43316. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  43317. 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  43318. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\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 USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\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 = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, 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, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).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_DISPERSION\n\tmaterial.dispersion = dispersion;\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, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).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_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  43319. var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\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\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\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\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\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}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\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 = F_Schlick( f0, f90, dotVH );\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\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.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\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( 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}\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\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 rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\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.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\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}";
  43320. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\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.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\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, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, geometryPosition, 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 *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\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 ], geometryNormal );\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";
  43321. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  43322. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  43323. var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  43324. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43325. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43326. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  43327. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  43328. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  43329. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\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";
  43330. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  43331. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  43332. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  43333. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  43334. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\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";
  43335. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  43336. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif";
  43337. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  43338. 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 *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  43339. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).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( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  43340. 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";
  43341. 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";
  43342. 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";
  43343. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.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 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  43344. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  43345. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  43346. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  43347. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43348. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  43349. 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.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in 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( const in 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 depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\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 depth, const in float near, const in float far ) {\n\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\n}";
  43350. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43351. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  43352. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43353. 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";
  43354. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43355. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43356. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  43357. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying 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 shadowIntensity;\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 shadowIntensity;\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 shadowIntensity;\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";
  43358. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#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#endif";
  43359. 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.shadowIntensity, 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.shadowIntensity, 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 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\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.shadowIntensity, 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}";
  43360. 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";
  43361. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  43362. 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";
  43363. 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";
  43364. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  43365. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43366. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43367. 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 saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( 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}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  43368. 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, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  43369. 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\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\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 lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\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 dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  43370. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  43371. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  43372. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  43373. 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_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  43374. 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}";
  43375. 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 <colorspace_fragment>\n}";
  43376. 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}";
  43377. 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;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * 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 <colorspace_fragment>\n}";
  43378. 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}";
  43379. 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 <colorspace_fragment>\n}";
  43380. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_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}";
  43381. 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 <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\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 <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\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#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  43382. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_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}";
  43383. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\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 <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}";
  43384. 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}";
  43385. 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 <colorspace_fragment>\n}";
  43386. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\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 <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_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}";
  43387. 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 <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43388. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  43389. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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, vLightMapUv );\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43390. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  43391. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\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 <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43392. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\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 <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  43393. 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 <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43394. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  43395. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\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\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\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( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  43396. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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}";
  43397. 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 <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 <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43398. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  43399. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_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 USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\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_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\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 <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43400. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  43401. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\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 <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43402. 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>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_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}";
  43403. 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 <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43404. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43405. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43406. 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[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\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}";
  43407. 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 <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  43408. const ShaderChunk = {
  43409. alphahash_fragment: alphahash_fragment,
  43410. alphahash_pars_fragment: alphahash_pars_fragment,
  43411. alphamap_fragment: alphamap_fragment,
  43412. alphamap_pars_fragment: alphamap_pars_fragment,
  43413. alphatest_fragment: alphatest_fragment,
  43414. alphatest_pars_fragment: alphatest_pars_fragment,
  43415. aomap_fragment: aomap_fragment,
  43416. aomap_pars_fragment: aomap_pars_fragment,
  43417. batching_pars_vertex: batching_pars_vertex,
  43418. batching_vertex: batching_vertex,
  43419. begin_vertex: begin_vertex,
  43420. beginnormal_vertex: beginnormal_vertex,
  43421. bsdfs: bsdfs,
  43422. iridescence_fragment: iridescence_fragment,
  43423. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43424. clipping_planes_fragment: clipping_planes_fragment,
  43425. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43426. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43427. clipping_planes_vertex: clipping_planes_vertex,
  43428. color_fragment: color_fragment,
  43429. color_pars_fragment: color_pars_fragment,
  43430. color_pars_vertex: color_pars_vertex,
  43431. color_vertex: color_vertex,
  43432. common: common,
  43433. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43434. defaultnormal_vertex: defaultnormal_vertex,
  43435. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43436. displacementmap_vertex: displacementmap_vertex,
  43437. emissivemap_fragment: emissivemap_fragment,
  43438. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43439. colorspace_fragment: colorspace_fragment,
  43440. colorspace_pars_fragment: colorspace_pars_fragment,
  43441. envmap_fragment: envmap_fragment,
  43442. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43443. envmap_pars_fragment: envmap_pars_fragment,
  43444. envmap_pars_vertex: envmap_pars_vertex,
  43445. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43446. envmap_vertex: envmap_vertex,
  43447. fog_vertex: fog_vertex,
  43448. fog_pars_vertex: fog_pars_vertex,
  43449. fog_fragment: fog_fragment,
  43450. fog_pars_fragment: fog_pars_fragment,
  43451. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43452. lightmap_pars_fragment: lightmap_pars_fragment,
  43453. lights_lambert_fragment: lights_lambert_fragment,
  43454. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43455. lights_pars_begin: lights_pars_begin,
  43456. lights_toon_fragment: lights_toon_fragment,
  43457. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43458. lights_phong_fragment: lights_phong_fragment,
  43459. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43460. lights_physical_fragment: lights_physical_fragment,
  43461. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43462. lights_fragment_begin: lights_fragment_begin,
  43463. lights_fragment_maps: lights_fragment_maps,
  43464. lights_fragment_end: lights_fragment_end,
  43465. logdepthbuf_fragment: logdepthbuf_fragment,
  43466. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43467. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43468. logdepthbuf_vertex: logdepthbuf_vertex,
  43469. map_fragment: map_fragment,
  43470. map_pars_fragment: map_pars_fragment,
  43471. map_particle_fragment: map_particle_fragment,
  43472. map_particle_pars_fragment: map_particle_pars_fragment,
  43473. metalnessmap_fragment: metalnessmap_fragment,
  43474. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43475. morphinstance_vertex: morphinstance_vertex,
  43476. morphcolor_vertex: morphcolor_vertex,
  43477. morphnormal_vertex: morphnormal_vertex,
  43478. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43479. morphtarget_vertex: morphtarget_vertex,
  43480. normal_fragment_begin: normal_fragment_begin,
  43481. normal_fragment_maps: normal_fragment_maps,
  43482. normal_pars_fragment: normal_pars_fragment,
  43483. normal_pars_vertex: normal_pars_vertex,
  43484. normal_vertex: normal_vertex,
  43485. normalmap_pars_fragment: normalmap_pars_fragment,
  43486. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43487. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43488. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43489. iridescence_pars_fragment: iridescence_pars_fragment,
  43490. opaque_fragment: opaque_fragment,
  43491. packing: packing,
  43492. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43493. project_vertex: project_vertex,
  43494. dithering_fragment: dithering_fragment,
  43495. dithering_pars_fragment: dithering_pars_fragment,
  43496. roughnessmap_fragment: roughnessmap_fragment,
  43497. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43498. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43499. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43500. shadowmap_vertex: shadowmap_vertex,
  43501. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43502. skinbase_vertex: skinbase_vertex,
  43503. skinning_pars_vertex: skinning_pars_vertex,
  43504. skinning_vertex: skinning_vertex,
  43505. skinnormal_vertex: skinnormal_vertex,
  43506. specularmap_fragment: specularmap_fragment,
  43507. specularmap_pars_fragment: specularmap_pars_fragment,
  43508. tonemapping_fragment: tonemapping_fragment,
  43509. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43510. transmission_fragment: transmission_fragment,
  43511. transmission_pars_fragment: transmission_pars_fragment,
  43512. uv_pars_fragment: uv_pars_fragment,
  43513. uv_pars_vertex: uv_pars_vertex,
  43514. uv_vertex: uv_vertex,
  43515. worldpos_vertex: worldpos_vertex,
  43516. background_vert: vertex$h,
  43517. background_frag: fragment$h,
  43518. backgroundCube_vert: vertex$g,
  43519. backgroundCube_frag: fragment$g,
  43520. cube_vert: vertex$f,
  43521. cube_frag: fragment$f,
  43522. depth_vert: vertex$e,
  43523. depth_frag: fragment$e,
  43524. distance_vert: vertex$d,
  43525. distance_frag: fragment$d,
  43526. equirect_vert: vertex$c,
  43527. equirect_frag: fragment$c,
  43528. linedashed_vert: vertex$b,
  43529. linedashed_frag: fragment$b,
  43530. meshbasic_vert: vertex$a,
  43531. meshbasic_frag: fragment$a,
  43532. meshlambert_vert: vertex$9,
  43533. meshlambert_frag: fragment$9,
  43534. meshmatcap_vert: vertex$8,
  43535. meshmatcap_frag: fragment$8,
  43536. meshnormal_vert: vertex$7,
  43537. meshnormal_frag: fragment$7,
  43538. meshphong_vert: vertex$6,
  43539. meshphong_frag: fragment$6,
  43540. meshphysical_vert: vertex$5,
  43541. meshphysical_frag: fragment$5,
  43542. meshtoon_vert: vertex$4,
  43543. meshtoon_frag: fragment$4,
  43544. points_vert: vertex$3,
  43545. points_frag: fragment$3,
  43546. shadow_vert: vertex$2,
  43547. shadow_frag: fragment$2,
  43548. sprite_vert: vertex$1,
  43549. sprite_frag: fragment$1
  43550. };
  43551. // Uniforms library for shared webgl shaders
  43552. const UniformsLib = {
  43553. common: {
  43554. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43555. opacity: { value: 1.0 },
  43556. map: { value: null },
  43557. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43558. alphaMap: { value: null },
  43559. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43560. alphaTest: { value: 0 }
  43561. },
  43562. specularmap: {
  43563. specularMap: { value: null },
  43564. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43565. },
  43566. envmap: {
  43567. envMap: { value: null },
  43568. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43569. flipEnvMap: { value: -1 },
  43570. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43571. ior: { value: 1.5 }, // physical
  43572. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43573. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43574. },
  43575. aomap: {
  43576. aoMap: { value: null },
  43577. aoMapIntensity: { value: 1 },
  43578. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43579. },
  43580. lightmap: {
  43581. lightMap: { value: null },
  43582. lightMapIntensity: { value: 1 },
  43583. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43584. },
  43585. bumpmap: {
  43586. bumpMap: { value: null },
  43587. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43588. bumpScale: { value: 1 }
  43589. },
  43590. normalmap: {
  43591. normalMap: { value: null },
  43592. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43593. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43594. },
  43595. displacementmap: {
  43596. displacementMap: { value: null },
  43597. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43598. displacementScale: { value: 1 },
  43599. displacementBias: { value: 0 }
  43600. },
  43601. emissivemap: {
  43602. emissiveMap: { value: null },
  43603. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43604. },
  43605. metalnessmap: {
  43606. metalnessMap: { value: null },
  43607. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43608. },
  43609. roughnessmap: {
  43610. roughnessMap: { value: null },
  43611. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43612. },
  43613. gradientmap: {
  43614. gradientMap: { value: null }
  43615. },
  43616. fog: {
  43617. fogDensity: { value: 0.00025 },
  43618. fogNear: { value: 1 },
  43619. fogFar: { value: 2000 },
  43620. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43621. },
  43622. lights: {
  43623. ambientLightColor: { value: [] },
  43624. lightProbe: { value: [] },
  43625. directionalLights: { value: [], properties: {
  43626. direction: {},
  43627. color: {}
  43628. } },
  43629. directionalLightShadows: { value: [], properties: {
  43630. shadowIntensity: 1,
  43631. shadowBias: {},
  43632. shadowNormalBias: {},
  43633. shadowRadius: {},
  43634. shadowMapSize: {}
  43635. } },
  43636. directionalShadowMatrix: { value: [] },
  43637. spotLights: { value: [], properties: {
  43638. color: {},
  43639. position: {},
  43640. direction: {},
  43641. distance: {},
  43642. coneCos: {},
  43643. penumbraCos: {},
  43644. decay: {}
  43645. } },
  43646. spotLightShadows: { value: [], properties: {
  43647. shadowIntensity: 1,
  43648. shadowBias: {},
  43649. shadowNormalBias: {},
  43650. shadowRadius: {},
  43651. shadowMapSize: {}
  43652. } },
  43653. spotLightMap: { value: [] },
  43654. spotLightMatrix: { value: [] },
  43655. pointLights: { value: [], properties: {
  43656. color: {},
  43657. position: {},
  43658. decay: {},
  43659. distance: {}
  43660. } },
  43661. pointLightShadows: { value: [], properties: {
  43662. shadowIntensity: 1,
  43663. shadowBias: {},
  43664. shadowNormalBias: {},
  43665. shadowRadius: {},
  43666. shadowMapSize: {},
  43667. shadowCameraNear: {},
  43668. shadowCameraFar: {}
  43669. } },
  43670. pointShadowMatrix: { value: [] },
  43671. hemisphereLights: { value: [], properties: {
  43672. direction: {},
  43673. skyColor: {},
  43674. groundColor: {}
  43675. } },
  43676. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43677. rectAreaLights: { value: [], properties: {
  43678. color: {},
  43679. position: {},
  43680. width: {},
  43681. height: {}
  43682. } },
  43683. ltc_1: { value: null },
  43684. ltc_2: { value: null }
  43685. },
  43686. points: {
  43687. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43688. opacity: { value: 1.0 },
  43689. size: { value: 1.0 },
  43690. scale: { value: 1.0 },
  43691. map: { value: null },
  43692. alphaMap: { value: null },
  43693. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43694. alphaTest: { value: 0 },
  43695. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43696. },
  43697. sprite: {
  43698. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43699. opacity: { value: 1.0 },
  43700. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43701. rotation: { value: 0.0 },
  43702. map: { value: null },
  43703. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43704. alphaMap: { value: null },
  43705. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43706. alphaTest: { value: 0 }
  43707. }
  43708. };
  43709. const ShaderLib = {
  43710. basic: {
  43711. uniforms: /*@__PURE__*/ mergeUniforms( [
  43712. UniformsLib.common,
  43713. UniformsLib.specularmap,
  43714. UniformsLib.envmap,
  43715. UniformsLib.aomap,
  43716. UniformsLib.lightmap,
  43717. UniformsLib.fog
  43718. ] ),
  43719. vertexShader: ShaderChunk.meshbasic_vert,
  43720. fragmentShader: ShaderChunk.meshbasic_frag
  43721. },
  43722. lambert: {
  43723. uniforms: /*@__PURE__*/ mergeUniforms( [
  43724. UniformsLib.common,
  43725. UniformsLib.specularmap,
  43726. UniformsLib.envmap,
  43727. UniformsLib.aomap,
  43728. UniformsLib.lightmap,
  43729. UniformsLib.emissivemap,
  43730. UniformsLib.bumpmap,
  43731. UniformsLib.normalmap,
  43732. UniformsLib.displacementmap,
  43733. UniformsLib.fog,
  43734. UniformsLib.lights,
  43735. {
  43736. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43737. envMapIntensity: { value: 1 }
  43738. }
  43739. ] ),
  43740. vertexShader: ShaderChunk.meshlambert_vert,
  43741. fragmentShader: ShaderChunk.meshlambert_frag
  43742. },
  43743. phong: {
  43744. uniforms: /*@__PURE__*/ mergeUniforms( [
  43745. UniformsLib.common,
  43746. UniformsLib.specularmap,
  43747. UniformsLib.envmap,
  43748. UniformsLib.aomap,
  43749. UniformsLib.lightmap,
  43750. UniformsLib.emissivemap,
  43751. UniformsLib.bumpmap,
  43752. UniformsLib.normalmap,
  43753. UniformsLib.displacementmap,
  43754. UniformsLib.fog,
  43755. UniformsLib.lights,
  43756. {
  43757. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43758. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43759. shininess: { value: 30 },
  43760. envMapIntensity: { value: 1 }
  43761. }
  43762. ] ),
  43763. vertexShader: ShaderChunk.meshphong_vert,
  43764. fragmentShader: ShaderChunk.meshphong_frag
  43765. },
  43766. standard: {
  43767. uniforms: /*@__PURE__*/ mergeUniforms( [
  43768. UniformsLib.common,
  43769. UniformsLib.envmap,
  43770. UniformsLib.aomap,
  43771. UniformsLib.lightmap,
  43772. UniformsLib.emissivemap,
  43773. UniformsLib.bumpmap,
  43774. UniformsLib.normalmap,
  43775. UniformsLib.displacementmap,
  43776. UniformsLib.roughnessmap,
  43777. UniformsLib.metalnessmap,
  43778. UniformsLib.fog,
  43779. UniformsLib.lights,
  43780. {
  43781. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43782. roughness: { value: 1.0 },
  43783. metalness: { value: 0.0 },
  43784. envMapIntensity: { value: 1 }
  43785. }
  43786. ] ),
  43787. vertexShader: ShaderChunk.meshphysical_vert,
  43788. fragmentShader: ShaderChunk.meshphysical_frag
  43789. },
  43790. toon: {
  43791. uniforms: /*@__PURE__*/ mergeUniforms( [
  43792. UniformsLib.common,
  43793. UniformsLib.aomap,
  43794. UniformsLib.lightmap,
  43795. UniformsLib.emissivemap,
  43796. UniformsLib.bumpmap,
  43797. UniformsLib.normalmap,
  43798. UniformsLib.displacementmap,
  43799. UniformsLib.gradientmap,
  43800. UniformsLib.fog,
  43801. UniformsLib.lights,
  43802. {
  43803. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43804. }
  43805. ] ),
  43806. vertexShader: ShaderChunk.meshtoon_vert,
  43807. fragmentShader: ShaderChunk.meshtoon_frag
  43808. },
  43809. matcap: {
  43810. uniforms: /*@__PURE__*/ mergeUniforms( [
  43811. UniformsLib.common,
  43812. UniformsLib.bumpmap,
  43813. UniformsLib.normalmap,
  43814. UniformsLib.displacementmap,
  43815. UniformsLib.fog,
  43816. {
  43817. matcap: { value: null }
  43818. }
  43819. ] ),
  43820. vertexShader: ShaderChunk.meshmatcap_vert,
  43821. fragmentShader: ShaderChunk.meshmatcap_frag
  43822. },
  43823. points: {
  43824. uniforms: /*@__PURE__*/ mergeUniforms( [
  43825. UniformsLib.points,
  43826. UniformsLib.fog
  43827. ] ),
  43828. vertexShader: ShaderChunk.points_vert,
  43829. fragmentShader: ShaderChunk.points_frag
  43830. },
  43831. dashed: {
  43832. uniforms: /*@__PURE__*/ mergeUniforms( [
  43833. UniformsLib.common,
  43834. UniformsLib.fog,
  43835. {
  43836. scale: { value: 1 },
  43837. dashSize: { value: 1 },
  43838. totalSize: { value: 2 }
  43839. }
  43840. ] ),
  43841. vertexShader: ShaderChunk.linedashed_vert,
  43842. fragmentShader: ShaderChunk.linedashed_frag
  43843. },
  43844. depth: {
  43845. uniforms: /*@__PURE__*/ mergeUniforms( [
  43846. UniformsLib.common,
  43847. UniformsLib.displacementmap
  43848. ] ),
  43849. vertexShader: ShaderChunk.depth_vert,
  43850. fragmentShader: ShaderChunk.depth_frag
  43851. },
  43852. normal: {
  43853. uniforms: /*@__PURE__*/ mergeUniforms( [
  43854. UniformsLib.common,
  43855. UniformsLib.bumpmap,
  43856. UniformsLib.normalmap,
  43857. UniformsLib.displacementmap,
  43858. {
  43859. opacity: { value: 1.0 }
  43860. }
  43861. ] ),
  43862. vertexShader: ShaderChunk.meshnormal_vert,
  43863. fragmentShader: ShaderChunk.meshnormal_frag
  43864. },
  43865. sprite: {
  43866. uniforms: /*@__PURE__*/ mergeUniforms( [
  43867. UniformsLib.sprite,
  43868. UniformsLib.fog
  43869. ] ),
  43870. vertexShader: ShaderChunk.sprite_vert,
  43871. fragmentShader: ShaderChunk.sprite_frag
  43872. },
  43873. background: {
  43874. uniforms: {
  43875. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43876. t2D: { value: null },
  43877. backgroundIntensity: { value: 1 }
  43878. },
  43879. vertexShader: ShaderChunk.background_vert,
  43880. fragmentShader: ShaderChunk.background_frag
  43881. },
  43882. backgroundCube: {
  43883. uniforms: {
  43884. envMap: { value: null },
  43885. flipEnvMap: { value: -1 },
  43886. backgroundBlurriness: { value: 0 },
  43887. backgroundIntensity: { value: 1 },
  43888. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43889. },
  43890. vertexShader: ShaderChunk.backgroundCube_vert,
  43891. fragmentShader: ShaderChunk.backgroundCube_frag
  43892. },
  43893. cube: {
  43894. uniforms: {
  43895. tCube: { value: null },
  43896. tFlip: { value: -1 },
  43897. opacity: { value: 1.0 }
  43898. },
  43899. vertexShader: ShaderChunk.cube_vert,
  43900. fragmentShader: ShaderChunk.cube_frag
  43901. },
  43902. equirect: {
  43903. uniforms: {
  43904. tEquirect: { value: null },
  43905. },
  43906. vertexShader: ShaderChunk.equirect_vert,
  43907. fragmentShader: ShaderChunk.equirect_frag
  43908. },
  43909. distance: {
  43910. uniforms: /*@__PURE__*/ mergeUniforms( [
  43911. UniformsLib.common,
  43912. UniformsLib.displacementmap,
  43913. {
  43914. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43915. nearDistance: { value: 1 },
  43916. farDistance: { value: 1000 }
  43917. }
  43918. ] ),
  43919. vertexShader: ShaderChunk.distance_vert,
  43920. fragmentShader: ShaderChunk.distance_frag
  43921. },
  43922. shadow: {
  43923. uniforms: /*@__PURE__*/ mergeUniforms( [
  43924. UniformsLib.lights,
  43925. UniformsLib.fog,
  43926. {
  43927. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43928. opacity: { value: 1.0 }
  43929. },
  43930. ] ),
  43931. vertexShader: ShaderChunk.shadow_vert,
  43932. fragmentShader: ShaderChunk.shadow_frag
  43933. }
  43934. };
  43935. ShaderLib.physical = {
  43936. uniforms: /*@__PURE__*/ mergeUniforms( [
  43937. ShaderLib.standard.uniforms,
  43938. {
  43939. clearcoat: { value: 0 },
  43940. clearcoatMap: { value: null },
  43941. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43942. clearcoatNormalMap: { value: null },
  43943. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43944. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43945. clearcoatRoughness: { value: 0 },
  43946. clearcoatRoughnessMap: { value: null },
  43947. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43948. dispersion: { value: 0 },
  43949. iridescence: { value: 0 },
  43950. iridescenceMap: { value: null },
  43951. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43952. iridescenceIOR: { value: 1.3 },
  43953. iridescenceThicknessMinimum: { value: 100 },
  43954. iridescenceThicknessMaximum: { value: 400 },
  43955. iridescenceThicknessMap: { value: null },
  43956. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43957. sheen: { value: 0 },
  43958. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43959. sheenColorMap: { value: null },
  43960. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43961. sheenRoughness: { value: 1 },
  43962. sheenRoughnessMap: { value: null },
  43963. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43964. transmission: { value: 0 },
  43965. transmissionMap: { value: null },
  43966. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43967. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43968. transmissionSamplerMap: { value: null },
  43969. thickness: { value: 0 },
  43970. thicknessMap: { value: null },
  43971. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43972. attenuationDistance: { value: 0 },
  43973. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43974. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43975. specularColorMap: { value: null },
  43976. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43977. specularIntensity: { value: 1 },
  43978. specularIntensityMap: { value: null },
  43979. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43980. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43981. anisotropyMap: { value: null },
  43982. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43983. }
  43984. ] ),
  43985. vertexShader: ShaderChunk.meshphysical_vert,
  43986. fragmentShader: ShaderChunk.meshphysical_frag
  43987. };
  43988. const _rgb = { r: 0, b: 0, g: 0 };
  43989. const _e1$1 = /*@__PURE__*/ new Euler();
  43990. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43991. function WebGLBackground( renderer, environments, state, objects, alpha, premultipliedAlpha ) {
  43992. const clearColor = new Color( 0x000000 );
  43993. let clearAlpha = alpha === true ? 0 : 1;
  43994. let planeMesh;
  43995. let boxMesh;
  43996. let currentBackground = null;
  43997. let currentBackgroundVersion = 0;
  43998. let currentTonemapping = null;
  43999. function getBackground( scene ) {
  44000. let background = scene.isScene === true ? scene.background : null;
  44001. if ( background && background.isTexture ) {
  44002. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  44003. background = environments.get( background, usePMREM );
  44004. }
  44005. return background;
  44006. }
  44007. function render( scene ) {
  44008. let forceClear = false;
  44009. const background = getBackground( scene );
  44010. if ( background === null ) {
  44011. setClear( clearColor, clearAlpha );
  44012. } else if ( background && background.isColor ) {
  44013. setClear( background, 1 );
  44014. forceClear = true;
  44015. }
  44016. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  44017. if ( environmentBlendMode === 'additive' ) {
  44018. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  44019. } else if ( environmentBlendMode === 'alpha-blend' ) {
  44020. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  44021. }
  44022. if ( renderer.autoClear || forceClear ) {
  44023. // buffers might not be writable which is required to ensure a correct clear
  44024. state.buffers.depth.setTest( true );
  44025. state.buffers.depth.setMask( true );
  44026. state.buffers.color.setMask( true );
  44027. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  44028. }
  44029. }
  44030. function addToRenderList( renderList, scene ) {
  44031. const background = getBackground( scene );
  44032. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  44033. if ( boxMesh === undefined ) {
  44034. boxMesh = new Mesh(
  44035. new BoxGeometry( 1, 1, 1 ),
  44036. new ShaderMaterial( {
  44037. name: 'BackgroundCubeMaterial',
  44038. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  44039. vertexShader: ShaderLib.backgroundCube.vertexShader,
  44040. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  44041. side: BackSide,
  44042. depthTest: false,
  44043. depthWrite: false,
  44044. fog: false,
  44045. allowOverride: false
  44046. } )
  44047. );
  44048. boxMesh.geometry.deleteAttribute( 'normal' );
  44049. boxMesh.geometry.deleteAttribute( 'uv' );
  44050. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  44051. this.matrixWorld.copyPosition( camera.matrixWorld );
  44052. };
  44053. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  44054. Object.defineProperty( boxMesh.material, 'envMap', {
  44055. get: function () {
  44056. return this.uniforms.envMap.value;
  44057. }
  44058. } );
  44059. objects.update( boxMesh );
  44060. }
  44061. _e1$1.copy( scene.backgroundRotation );
  44062. // accommodate left-handed frame
  44063. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  44064. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  44065. // environment maps which are not cube render targets or PMREMs follow a different convention
  44066. _e1$1.y *= -1;
  44067. _e1$1.z *= -1;
  44068. }
  44069. boxMesh.material.uniforms.envMap.value = background;
  44070. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  44071. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  44072. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  44073. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  44074. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  44075. if ( currentBackground !== background ||
  44076. currentBackgroundVersion !== background.version ||
  44077. currentTonemapping !== renderer.toneMapping ) {
  44078. boxMesh.material.needsUpdate = true;
  44079. currentBackground = background;
  44080. currentBackgroundVersion = background.version;
  44081. currentTonemapping = renderer.toneMapping;
  44082. }
  44083. boxMesh.layers.enableAll();
  44084. // push to the pre-sorted opaque render list
  44085. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  44086. } else if ( background && background.isTexture ) {
  44087. if ( planeMesh === undefined ) {
  44088. planeMesh = new Mesh(
  44089. new PlaneGeometry( 2, 2 ),
  44090. new ShaderMaterial( {
  44091. name: 'BackgroundMaterial',
  44092. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  44093. vertexShader: ShaderLib.background.vertexShader,
  44094. fragmentShader: ShaderLib.background.fragmentShader,
  44095. side: FrontSide,
  44096. depthTest: false,
  44097. depthWrite: false,
  44098. fog: false,
  44099. allowOverride: false
  44100. } )
  44101. );
  44102. planeMesh.geometry.deleteAttribute( 'normal' );
  44103. // add "map" material property so the renderer can evaluate it like for built-in materials
  44104. Object.defineProperty( planeMesh.material, 'map', {
  44105. get: function () {
  44106. return this.uniforms.t2D.value;
  44107. }
  44108. } );
  44109. objects.update( planeMesh );
  44110. }
  44111. planeMesh.material.uniforms.t2D.value = background;
  44112. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  44113. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  44114. if ( background.matrixAutoUpdate === true ) {
  44115. background.updateMatrix();
  44116. }
  44117. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  44118. if ( currentBackground !== background ||
  44119. currentBackgroundVersion !== background.version ||
  44120. currentTonemapping !== renderer.toneMapping ) {
  44121. planeMesh.material.needsUpdate = true;
  44122. currentBackground = background;
  44123. currentBackgroundVersion = background.version;
  44124. currentTonemapping = renderer.toneMapping;
  44125. }
  44126. planeMesh.layers.enableAll();
  44127. // push to the pre-sorted opaque render list
  44128. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  44129. }
  44130. }
  44131. function setClear( color, alpha ) {
  44132. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  44133. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  44134. }
  44135. function dispose() {
  44136. if ( boxMesh !== undefined ) {
  44137. boxMesh.geometry.dispose();
  44138. boxMesh.material.dispose();
  44139. boxMesh = undefined;
  44140. }
  44141. if ( planeMesh !== undefined ) {
  44142. planeMesh.geometry.dispose();
  44143. planeMesh.material.dispose();
  44144. planeMesh = undefined;
  44145. }
  44146. }
  44147. return {
  44148. getClearColor: function () {
  44149. return clearColor;
  44150. },
  44151. setClearColor: function ( color, alpha = 1 ) {
  44152. clearColor.set( color );
  44153. clearAlpha = alpha;
  44154. setClear( clearColor, clearAlpha );
  44155. },
  44156. getClearAlpha: function () {
  44157. return clearAlpha;
  44158. },
  44159. setClearAlpha: function ( alpha ) {
  44160. clearAlpha = alpha;
  44161. setClear( clearColor, clearAlpha );
  44162. },
  44163. render: render,
  44164. addToRenderList: addToRenderList,
  44165. dispose: dispose
  44166. };
  44167. }
  44168. function WebGLBindingStates( gl, attributes ) {
  44169. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44170. const bindingStates = {};
  44171. const defaultState = createBindingState( null );
  44172. let currentState = defaultState;
  44173. let forceUpdate = false;
  44174. function setup( object, material, program, geometry, index ) {
  44175. let updateBuffers = false;
  44176. const state = getBindingState( object, geometry, program, material );
  44177. if ( currentState !== state ) {
  44178. currentState = state;
  44179. bindVertexArrayObject( currentState.object );
  44180. }
  44181. updateBuffers = needsUpdate( object, geometry, program, index );
  44182. if ( updateBuffers ) saveCache( object, geometry, program, index );
  44183. if ( index !== null ) {
  44184. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  44185. }
  44186. if ( updateBuffers || forceUpdate ) {
  44187. forceUpdate = false;
  44188. setupVertexAttributes( object, material, program, geometry );
  44189. if ( index !== null ) {
  44190. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  44191. }
  44192. }
  44193. }
  44194. function createVertexArrayObject() {
  44195. return gl.createVertexArray();
  44196. }
  44197. function bindVertexArrayObject( vao ) {
  44198. return gl.bindVertexArray( vao );
  44199. }
  44200. function deleteVertexArrayObject( vao ) {
  44201. return gl.deleteVertexArray( vao );
  44202. }
  44203. function getBindingState( object, geometry, program, material ) {
  44204. const wireframe = ( material.wireframe === true );
  44205. let objectMap = bindingStates[ geometry.id ];
  44206. if ( objectMap === undefined ) {
  44207. objectMap = {};
  44208. bindingStates[ geometry.id ] = objectMap;
  44209. }
  44210. // Each InstancedMesh requires unique binding states because it contains instanced attributes.
  44211. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44212. let programMap = objectMap[ objectId ];
  44213. if ( programMap === undefined ) {
  44214. programMap = {};
  44215. objectMap[ objectId ] = programMap;
  44216. }
  44217. let stateMap = programMap[ program.id ];
  44218. if ( stateMap === undefined ) {
  44219. stateMap = {};
  44220. programMap[ program.id ] = stateMap;
  44221. }
  44222. let state = stateMap[ wireframe ];
  44223. if ( state === undefined ) {
  44224. state = createBindingState( createVertexArrayObject() );
  44225. stateMap[ wireframe ] = state;
  44226. }
  44227. return state;
  44228. }
  44229. function createBindingState( vao ) {
  44230. const newAttributes = [];
  44231. const enabledAttributes = [];
  44232. const attributeDivisors = [];
  44233. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  44234. newAttributes[ i ] = 0;
  44235. enabledAttributes[ i ] = 0;
  44236. attributeDivisors[ i ] = 0;
  44237. }
  44238. return {
  44239. // for backward compatibility on non-VAO support browser
  44240. geometry: null,
  44241. program: null,
  44242. wireframe: false,
  44243. newAttributes: newAttributes,
  44244. enabledAttributes: enabledAttributes,
  44245. attributeDivisors: attributeDivisors,
  44246. object: vao,
  44247. attributes: {},
  44248. index: null
  44249. };
  44250. }
  44251. function needsUpdate( object, geometry, program, index ) {
  44252. const cachedAttributes = currentState.attributes;
  44253. const geometryAttributes = geometry.attributes;
  44254. let attributesNum = 0;
  44255. const programAttributes = program.getAttributes();
  44256. for ( const name in programAttributes ) {
  44257. const programAttribute = programAttributes[ name ];
  44258. if ( programAttribute.location >= 0 ) {
  44259. const cachedAttribute = cachedAttributes[ name ];
  44260. let geometryAttribute = geometryAttributes[ name ];
  44261. if ( geometryAttribute === undefined ) {
  44262. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44263. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44264. }
  44265. if ( cachedAttribute === undefined ) return true;
  44266. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  44267. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  44268. attributesNum ++;
  44269. }
  44270. }
  44271. if ( currentState.attributesNum !== attributesNum ) return true;
  44272. if ( currentState.index !== index ) return true;
  44273. return false;
  44274. }
  44275. function saveCache( object, geometry, program, index ) {
  44276. const cache = {};
  44277. const attributes = geometry.attributes;
  44278. let attributesNum = 0;
  44279. const programAttributes = program.getAttributes();
  44280. for ( const name in programAttributes ) {
  44281. const programAttribute = programAttributes[ name ];
  44282. if ( programAttribute.location >= 0 ) {
  44283. let attribute = attributes[ name ];
  44284. if ( attribute === undefined ) {
  44285. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  44286. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  44287. }
  44288. const data = {};
  44289. data.attribute = attribute;
  44290. if ( attribute && attribute.data ) {
  44291. data.data = attribute.data;
  44292. }
  44293. cache[ name ] = data;
  44294. attributesNum ++;
  44295. }
  44296. }
  44297. currentState.attributes = cache;
  44298. currentState.attributesNum = attributesNum;
  44299. currentState.index = index;
  44300. }
  44301. function initAttributes() {
  44302. const newAttributes = currentState.newAttributes;
  44303. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  44304. newAttributes[ i ] = 0;
  44305. }
  44306. }
  44307. function enableAttribute( attribute ) {
  44308. enableAttributeAndDivisor( attribute, 0 );
  44309. }
  44310. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  44311. const newAttributes = currentState.newAttributes;
  44312. const enabledAttributes = currentState.enabledAttributes;
  44313. const attributeDivisors = currentState.attributeDivisors;
  44314. newAttributes[ attribute ] = 1;
  44315. if ( enabledAttributes[ attribute ] === 0 ) {
  44316. gl.enableVertexAttribArray( attribute );
  44317. enabledAttributes[ attribute ] = 1;
  44318. }
  44319. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  44320. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  44321. attributeDivisors[ attribute ] = meshPerAttribute;
  44322. }
  44323. }
  44324. function disableUnusedAttributes() {
  44325. const newAttributes = currentState.newAttributes;
  44326. const enabledAttributes = currentState.enabledAttributes;
  44327. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  44328. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  44329. gl.disableVertexAttribArray( i );
  44330. enabledAttributes[ i ] = 0;
  44331. }
  44332. }
  44333. }
  44334. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  44335. if ( integer === true ) {
  44336. gl.vertexAttribIPointer( index, size, type, stride, offset );
  44337. } else {
  44338. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  44339. }
  44340. }
  44341. function setupVertexAttributes( object, material, program, geometry ) {
  44342. initAttributes();
  44343. const geometryAttributes = geometry.attributes;
  44344. const programAttributes = program.getAttributes();
  44345. const materialDefaultAttributeValues = material.defaultAttributeValues;
  44346. for ( const name in programAttributes ) {
  44347. const programAttribute = programAttributes[ name ];
  44348. if ( programAttribute.location >= 0 ) {
  44349. let geometryAttribute = geometryAttributes[ name ];
  44350. if ( geometryAttribute === undefined ) {
  44351. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44352. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44353. }
  44354. if ( geometryAttribute !== undefined ) {
  44355. const normalized = geometryAttribute.normalized;
  44356. const size = geometryAttribute.itemSize;
  44357. const attribute = attributes.get( geometryAttribute );
  44358. // TODO Attribute may not be available on context restore
  44359. if ( attribute === undefined ) continue;
  44360. const buffer = attribute.buffer;
  44361. const type = attribute.type;
  44362. const bytesPerElement = attribute.bytesPerElement;
  44363. // check for integer attributes
  44364. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44365. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44366. const data = geometryAttribute.data;
  44367. const stride = data.stride;
  44368. const offset = geometryAttribute.offset;
  44369. if ( data.isInstancedInterleavedBuffer ) {
  44370. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44371. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44372. }
  44373. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44374. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44375. }
  44376. } else {
  44377. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44378. enableAttribute( programAttribute.location + i );
  44379. }
  44380. }
  44381. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44382. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44383. vertexAttribPointer(
  44384. programAttribute.location + i,
  44385. size / programAttribute.locationSize,
  44386. type,
  44387. normalized,
  44388. stride * bytesPerElement,
  44389. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44390. integer
  44391. );
  44392. }
  44393. } else {
  44394. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44395. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44396. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44397. }
  44398. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44399. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44400. }
  44401. } else {
  44402. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44403. enableAttribute( programAttribute.location + i );
  44404. }
  44405. }
  44406. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44407. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44408. vertexAttribPointer(
  44409. programAttribute.location + i,
  44410. size / programAttribute.locationSize,
  44411. type,
  44412. normalized,
  44413. size * bytesPerElement,
  44414. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44415. integer
  44416. );
  44417. }
  44418. }
  44419. } else if ( materialDefaultAttributeValues !== undefined ) {
  44420. const value = materialDefaultAttributeValues[ name ];
  44421. if ( value !== undefined ) {
  44422. switch ( value.length ) {
  44423. case 2:
  44424. gl.vertexAttrib2fv( programAttribute.location, value );
  44425. break;
  44426. case 3:
  44427. gl.vertexAttrib3fv( programAttribute.location, value );
  44428. break;
  44429. case 4:
  44430. gl.vertexAttrib4fv( programAttribute.location, value );
  44431. break;
  44432. default:
  44433. gl.vertexAttrib1fv( programAttribute.location, value );
  44434. }
  44435. }
  44436. }
  44437. }
  44438. }
  44439. disableUnusedAttributes();
  44440. }
  44441. function dispose() {
  44442. reset();
  44443. for ( const geometryId in bindingStates ) {
  44444. const objectMap = bindingStates[ geometryId ];
  44445. for ( const objectId in objectMap ) {
  44446. const programMap = objectMap[ objectId ];
  44447. for ( const programId in programMap ) {
  44448. const stateMap = programMap[ programId ];
  44449. for ( const wireframe in stateMap ) {
  44450. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44451. delete stateMap[ wireframe ];
  44452. }
  44453. delete programMap[ programId ];
  44454. }
  44455. }
  44456. delete bindingStates[ geometryId ];
  44457. }
  44458. }
  44459. function releaseStatesOfGeometry( geometry ) {
  44460. if ( bindingStates[ geometry.id ] === undefined ) return;
  44461. const objectMap = bindingStates[ geometry.id ];
  44462. for ( const objectId in objectMap ) {
  44463. const programMap = objectMap[ objectId ];
  44464. for ( const programId in programMap ) {
  44465. const stateMap = programMap[ programId ];
  44466. for ( const wireframe in stateMap ) {
  44467. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44468. delete stateMap[ wireframe ];
  44469. }
  44470. delete programMap[ programId ];
  44471. }
  44472. }
  44473. delete bindingStates[ geometry.id ];
  44474. }
  44475. function releaseStatesOfProgram( program ) {
  44476. for ( const geometryId in bindingStates ) {
  44477. const objectMap = bindingStates[ geometryId ];
  44478. for ( const objectId in objectMap ) {
  44479. const programMap = objectMap[ objectId ];
  44480. if ( programMap[ program.id ] === undefined ) continue;
  44481. const stateMap = programMap[ program.id ];
  44482. for ( const wireframe in stateMap ) {
  44483. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44484. delete stateMap[ wireframe ];
  44485. }
  44486. delete programMap[ program.id ];
  44487. }
  44488. }
  44489. }
  44490. function releaseStatesOfObject( object ) {
  44491. for ( const geometryId in bindingStates ) {
  44492. const objectMap = bindingStates[ geometryId ];
  44493. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44494. const programMap = objectMap[ objectId ];
  44495. if ( programMap === undefined ) continue;
  44496. for ( const programId in programMap ) {
  44497. const stateMap = programMap[ programId ];
  44498. for ( const wireframe in stateMap ) {
  44499. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44500. delete stateMap[ wireframe ];
  44501. }
  44502. delete programMap[ programId ];
  44503. }
  44504. delete objectMap[ objectId ];
  44505. if ( Object.keys( objectMap ).length === 0 ) {
  44506. delete bindingStates[ geometryId ];
  44507. }
  44508. }
  44509. }
  44510. function reset() {
  44511. resetDefaultState();
  44512. forceUpdate = true;
  44513. if ( currentState === defaultState ) return;
  44514. currentState = defaultState;
  44515. bindVertexArrayObject( currentState.object );
  44516. }
  44517. // for backward-compatibility
  44518. function resetDefaultState() {
  44519. defaultState.geometry = null;
  44520. defaultState.program = null;
  44521. defaultState.wireframe = false;
  44522. }
  44523. return {
  44524. setup: setup,
  44525. reset: reset,
  44526. resetDefaultState: resetDefaultState,
  44527. dispose: dispose,
  44528. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44529. releaseStatesOfObject: releaseStatesOfObject,
  44530. releaseStatesOfProgram: releaseStatesOfProgram,
  44531. initAttributes: initAttributes,
  44532. enableAttribute: enableAttribute,
  44533. disableUnusedAttributes: disableUnusedAttributes
  44534. };
  44535. }
  44536. function WebGLBufferRenderer( gl, extensions, info ) {
  44537. let mode;
  44538. function setMode( value ) {
  44539. mode = value;
  44540. }
  44541. function render( start, count ) {
  44542. gl.drawArrays( mode, start, count );
  44543. info.update( count, mode, 1 );
  44544. }
  44545. function renderInstances( start, count, primcount ) {
  44546. if ( primcount === 0 ) return;
  44547. gl.drawArraysInstanced( mode, start, count, primcount );
  44548. info.update( count, mode, primcount );
  44549. }
  44550. function renderMultiDraw( starts, counts, drawCount ) {
  44551. if ( drawCount === 0 ) return;
  44552. const extension = extensions.get( 'WEBGL_multi_draw' );
  44553. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44554. let elementCount = 0;
  44555. for ( let i = 0; i < drawCount; i ++ ) {
  44556. elementCount += counts[ i ];
  44557. }
  44558. info.update( elementCount, mode, 1 );
  44559. }
  44560. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44561. if ( drawCount === 0 ) return;
  44562. const extension = extensions.get( 'WEBGL_multi_draw' );
  44563. if ( extension === null ) {
  44564. for ( let i = 0; i < starts.length; i ++ ) {
  44565. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44566. }
  44567. } else {
  44568. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44569. let elementCount = 0;
  44570. for ( let i = 0; i < drawCount; i ++ ) {
  44571. elementCount += counts[ i ] * primcount[ i ];
  44572. }
  44573. info.update( elementCount, mode, 1 );
  44574. }
  44575. }
  44576. //
  44577. this.setMode = setMode;
  44578. this.render = render;
  44579. this.renderInstances = renderInstances;
  44580. this.renderMultiDraw = renderMultiDraw;
  44581. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44582. }
  44583. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44584. let maxAnisotropy;
  44585. function getMaxAnisotropy() {
  44586. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44587. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44588. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44589. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44590. } else {
  44591. maxAnisotropy = 0;
  44592. }
  44593. return maxAnisotropy;
  44594. }
  44595. function textureFormatReadable( textureFormat ) {
  44596. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44597. return false;
  44598. }
  44599. return true;
  44600. }
  44601. function textureTypeReadable( textureType ) {
  44602. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44603. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44604. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44605. return false;
  44606. }
  44607. return true;
  44608. }
  44609. function getMaxPrecision( precision ) {
  44610. if ( precision === 'highp' ) {
  44611. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44612. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44613. return 'highp';
  44614. }
  44615. precision = 'mediump';
  44616. }
  44617. if ( precision === 'mediump' ) {
  44618. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44619. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44620. return 'mediump';
  44621. }
  44622. }
  44623. return 'lowp';
  44624. }
  44625. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44626. const maxPrecision = getMaxPrecision( precision );
  44627. if ( maxPrecision !== precision ) {
  44628. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44629. precision = maxPrecision;
  44630. }
  44631. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44632. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44633. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44634. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44635. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44636. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44637. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44638. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44639. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44640. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44641. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44642. const samples = gl.getParameter( gl.SAMPLES );
  44643. return {
  44644. isWebGL2: true, // keeping this for backwards compatibility
  44645. getMaxAnisotropy: getMaxAnisotropy,
  44646. getMaxPrecision: getMaxPrecision,
  44647. textureFormatReadable: textureFormatReadable,
  44648. textureTypeReadable: textureTypeReadable,
  44649. precision: precision,
  44650. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44651. reversedDepthBuffer: reversedDepthBuffer,
  44652. maxTextures: maxTextures,
  44653. maxVertexTextures: maxVertexTextures,
  44654. maxTextureSize: maxTextureSize,
  44655. maxCubemapSize: maxCubemapSize,
  44656. maxAttributes: maxAttributes,
  44657. maxVertexUniforms: maxVertexUniforms,
  44658. maxVaryings: maxVaryings,
  44659. maxFragmentUniforms: maxFragmentUniforms,
  44660. maxSamples: maxSamples,
  44661. samples: samples
  44662. };
  44663. }
  44664. function WebGLClipping( properties ) {
  44665. const scope = this;
  44666. let globalState = null,
  44667. numGlobalPlanes = 0,
  44668. localClippingEnabled = false,
  44669. renderingShadows = false;
  44670. const plane = new Plane(),
  44671. viewNormalMatrix = new Matrix3(),
  44672. uniform = { value: null, needsUpdate: false };
  44673. this.uniform = uniform;
  44674. this.numPlanes = 0;
  44675. this.numIntersection = 0;
  44676. this.init = function ( planes, enableLocalClipping ) {
  44677. const enabled =
  44678. planes.length !== 0 ||
  44679. enableLocalClipping ||
  44680. // enable state of previous frame - the clipping code has to
  44681. // run another frame in order to reset the state:
  44682. numGlobalPlanes !== 0 ||
  44683. localClippingEnabled;
  44684. localClippingEnabled = enableLocalClipping;
  44685. numGlobalPlanes = planes.length;
  44686. return enabled;
  44687. };
  44688. this.beginShadows = function () {
  44689. renderingShadows = true;
  44690. projectPlanes( null );
  44691. };
  44692. this.endShadows = function () {
  44693. renderingShadows = false;
  44694. };
  44695. this.setGlobalState = function ( planes, camera ) {
  44696. globalState = projectPlanes( planes, camera, 0 );
  44697. };
  44698. this.setState = function ( material, camera, useCache ) {
  44699. const planes = material.clippingPlanes,
  44700. clipIntersection = material.clipIntersection,
  44701. clipShadows = material.clipShadows;
  44702. const materialProperties = properties.get( material );
  44703. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44704. // there's no local clipping
  44705. if ( renderingShadows ) {
  44706. // there's no global clipping
  44707. projectPlanes( null );
  44708. } else {
  44709. resetGlobalState();
  44710. }
  44711. } else {
  44712. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44713. lGlobal = nGlobal * 4;
  44714. let dstArray = materialProperties.clippingState || null;
  44715. uniform.value = dstArray; // ensure unique state
  44716. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44717. for ( let i = 0; i !== lGlobal; ++ i ) {
  44718. dstArray[ i ] = globalState[ i ];
  44719. }
  44720. materialProperties.clippingState = dstArray;
  44721. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44722. this.numPlanes += nGlobal;
  44723. }
  44724. };
  44725. function resetGlobalState() {
  44726. if ( uniform.value !== globalState ) {
  44727. uniform.value = globalState;
  44728. uniform.needsUpdate = numGlobalPlanes > 0;
  44729. }
  44730. scope.numPlanes = numGlobalPlanes;
  44731. scope.numIntersection = 0;
  44732. }
  44733. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44734. const nPlanes = planes !== null ? planes.length : 0;
  44735. let dstArray = null;
  44736. if ( nPlanes !== 0 ) {
  44737. dstArray = uniform.value;
  44738. if ( skipTransform !== true || dstArray === null ) {
  44739. const flatSize = dstOffset + nPlanes * 4,
  44740. viewMatrix = camera.matrixWorldInverse;
  44741. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44742. if ( dstArray === null || dstArray.length < flatSize ) {
  44743. dstArray = new Float32Array( flatSize );
  44744. }
  44745. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44746. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44747. plane.normal.toArray( dstArray, i4 );
  44748. dstArray[ i4 + 3 ] = plane.constant;
  44749. }
  44750. }
  44751. uniform.value = dstArray;
  44752. uniform.needsUpdate = true;
  44753. }
  44754. scope.numPlanes = nPlanes;
  44755. scope.numIntersection = 0;
  44756. return dstArray;
  44757. }
  44758. }
  44759. const LOD_MIN = 4;
  44760. // The standard deviations (radians) associated with the extra mips.
  44761. // Used for scene blur in fromScene() method.
  44762. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44763. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44764. // samples and exit early, but not recompile the shader.
  44765. // Used for scene blur in fromScene() method.
  44766. const MAX_SAMPLES = 20;
  44767. // GGX VNDF importance sampling configuration
  44768. const GGX_SAMPLES = 256;
  44769. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44770. const _clearColor = /*@__PURE__*/ new Color();
  44771. let _oldTarget = null;
  44772. let _oldActiveCubeFace = 0;
  44773. let _oldActiveMipmapLevel = 0;
  44774. let _oldXrEnabled = false;
  44775. const _origin = /*@__PURE__*/ new Vector3();
  44776. /**
  44777. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44778. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44779. * blur to be quickly accessed based on material roughness. It is packed into a
  44780. * special CubeUV format that allows us to perform custom interpolation so that
  44781. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44782. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44783. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44784. * higher roughness levels. In this way we maintain resolution to smoothly
  44785. * interpolate diffuse lighting while limiting sampling computation.
  44786. *
  44787. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44788. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44789. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44790. * used in material rendering for physically-based image-based lighting.
  44791. */
  44792. class PMREMGenerator {
  44793. /**
  44794. * Constructs a new PMREM generator.
  44795. *
  44796. * @param {WebGLRenderer} renderer - The renderer.
  44797. */
  44798. constructor( renderer ) {
  44799. this._renderer = renderer;
  44800. this._pingPongRenderTarget = null;
  44801. this._lodMax = 0;
  44802. this._cubeSize = 0;
  44803. this._sizeLods = [];
  44804. this._sigmas = [];
  44805. this._lodMeshes = [];
  44806. this._backgroundBox = null;
  44807. this._cubemapMaterial = null;
  44808. this._equirectMaterial = null;
  44809. this._blurMaterial = null;
  44810. this._ggxMaterial = null;
  44811. }
  44812. /**
  44813. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44814. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44815. * in radians to be applied to the scene before PMREM generation. Optional near
  44816. * and far planes ensure the scene is rendered in its entirety.
  44817. *
  44818. * @param {Scene} scene - The scene to be captured.
  44819. * @param {number} [sigma=0] - The blur radius in radians.
  44820. * @param {number} [near=0.1] - The near plane distance.
  44821. * @param {number} [far=100] - The far plane distance.
  44822. * @param {Object} [options={}] - The configuration options.
  44823. * @param {number} [options.size=256] - The texture size of the PMREM.
  44824. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44825. * @return {WebGLRenderTarget} The resulting PMREM.
  44826. */
  44827. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44828. const {
  44829. size = 256,
  44830. position = _origin,
  44831. } = options;
  44832. _oldTarget = this._renderer.getRenderTarget();
  44833. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44834. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44835. _oldXrEnabled = this._renderer.xr.enabled;
  44836. this._renderer.xr.enabled = false;
  44837. this._setSize( size );
  44838. const cubeUVRenderTarget = this._allocateTargets();
  44839. cubeUVRenderTarget.depthBuffer = true;
  44840. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44841. if ( sigma > 0 ) {
  44842. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44843. }
  44844. this._applyPMREM( cubeUVRenderTarget );
  44845. this._cleanup( cubeUVRenderTarget );
  44846. return cubeUVRenderTarget;
  44847. }
  44848. /**
  44849. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44850. * or HDR. The ideal input image size is 1k (1024 x 512),
  44851. * as this matches best with the 256 x 256 cubemap output.
  44852. *
  44853. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44854. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44855. * @return {WebGLRenderTarget} The resulting PMREM.
  44856. */
  44857. fromEquirectangular( equirectangular, renderTarget = null ) {
  44858. return this._fromTexture( equirectangular, renderTarget );
  44859. }
  44860. /**
  44861. * Generates a PMREM from an cubemap texture, which can be either LDR
  44862. * or HDR. The ideal input cube size is 256 x 256,
  44863. * as this matches best with the 256 x 256 cubemap output.
  44864. *
  44865. * @param {Texture} cubemap - The cubemap texture to be converted.
  44866. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44867. * @return {WebGLRenderTarget} The resulting PMREM.
  44868. */
  44869. fromCubemap( cubemap, renderTarget = null ) {
  44870. return this._fromTexture( cubemap, renderTarget );
  44871. }
  44872. /**
  44873. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44874. * your texture's network fetch for increased concurrency.
  44875. */
  44876. compileCubemapShader() {
  44877. if ( this._cubemapMaterial === null ) {
  44878. this._cubemapMaterial = _getCubemapMaterial();
  44879. this._compileMaterial( this._cubemapMaterial );
  44880. }
  44881. }
  44882. /**
  44883. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44884. * your texture's network fetch for increased concurrency.
  44885. */
  44886. compileEquirectangularShader() {
  44887. if ( this._equirectMaterial === null ) {
  44888. this._equirectMaterial = _getEquirectMaterial();
  44889. this._compileMaterial( this._equirectMaterial );
  44890. }
  44891. }
  44892. /**
  44893. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44894. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44895. * one of them will cause any others to also become unusable.
  44896. */
  44897. dispose() {
  44898. this._dispose();
  44899. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44900. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44901. if ( this._backgroundBox !== null ) {
  44902. this._backgroundBox.geometry.dispose();
  44903. this._backgroundBox.material.dispose();
  44904. }
  44905. }
  44906. // private interface
  44907. _setSize( cubeSize ) {
  44908. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44909. this._cubeSize = Math.pow( 2, this._lodMax );
  44910. }
  44911. _dispose() {
  44912. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44913. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44914. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44915. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44916. this._lodMeshes[ i ].geometry.dispose();
  44917. }
  44918. }
  44919. _cleanup( outputTarget ) {
  44920. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44921. this._renderer.xr.enabled = _oldXrEnabled;
  44922. outputTarget.scissorTest = false;
  44923. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44924. }
  44925. _fromTexture( texture, renderTarget ) {
  44926. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44927. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44928. } else { // Equirectangular
  44929. this._setSize( texture.image.width / 4 );
  44930. }
  44931. _oldTarget = this._renderer.getRenderTarget();
  44932. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44933. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44934. _oldXrEnabled = this._renderer.xr.enabled;
  44935. this._renderer.xr.enabled = false;
  44936. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44937. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44938. this._applyPMREM( cubeUVRenderTarget );
  44939. this._cleanup( cubeUVRenderTarget );
  44940. return cubeUVRenderTarget;
  44941. }
  44942. _allocateTargets() {
  44943. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44944. const height = 4 * this._cubeSize;
  44945. const params = {
  44946. magFilter: LinearFilter,
  44947. minFilter: LinearFilter,
  44948. generateMipmaps: false,
  44949. type: HalfFloatType,
  44950. format: RGBAFormat,
  44951. colorSpace: LinearSRGBColorSpace,
  44952. depthBuffer: false
  44953. };
  44954. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44955. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44956. if ( this._pingPongRenderTarget !== null ) {
  44957. this._dispose();
  44958. }
  44959. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44960. const { _lodMax } = this;
  44961. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44962. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44963. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  44964. }
  44965. return cubeUVRenderTarget;
  44966. }
  44967. _compileMaterial( material ) {
  44968. const mesh = new Mesh( new BufferGeometry(), material );
  44969. this._renderer.compile( mesh, _flatCamera );
  44970. }
  44971. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44972. const fov = 90;
  44973. const aspect = 1;
  44974. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44975. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44976. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44977. const renderer = this._renderer;
  44978. const originalAutoClear = renderer.autoClear;
  44979. const toneMapping = renderer.toneMapping;
  44980. renderer.getClearColor( _clearColor );
  44981. renderer.toneMapping = NoToneMapping;
  44982. renderer.autoClear = false;
  44983. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44984. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44985. if ( reversedDepthBuffer ) {
  44986. renderer.setRenderTarget( cubeUVRenderTarget );
  44987. renderer.clearDepth();
  44988. renderer.setRenderTarget( null );
  44989. }
  44990. if ( this._backgroundBox === null ) {
  44991. this._backgroundBox = new Mesh(
  44992. new BoxGeometry(),
  44993. new MeshBasicMaterial( {
  44994. name: 'PMREM.Background',
  44995. side: BackSide,
  44996. depthWrite: false,
  44997. depthTest: false,
  44998. } )
  44999. );
  45000. }
  45001. const backgroundBox = this._backgroundBox;
  45002. const backgroundMaterial = backgroundBox.material;
  45003. let useSolidColor = false;
  45004. const background = scene.background;
  45005. if ( background ) {
  45006. if ( background.isColor ) {
  45007. backgroundMaterial.color.copy( background );
  45008. scene.background = null;
  45009. useSolidColor = true;
  45010. }
  45011. } else {
  45012. backgroundMaterial.color.copy( _clearColor );
  45013. useSolidColor = true;
  45014. }
  45015. for ( let i = 0; i < 6; i ++ ) {
  45016. const col = i % 3;
  45017. if ( col === 0 ) {
  45018. cubeCamera.up.set( 0, upSign[ i ], 0 );
  45019. cubeCamera.position.set( position.x, position.y, position.z );
  45020. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  45021. } else if ( col === 1 ) {
  45022. cubeCamera.up.set( 0, 0, upSign[ i ] );
  45023. cubeCamera.position.set( position.x, position.y, position.z );
  45024. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  45025. } else {
  45026. cubeCamera.up.set( 0, upSign[ i ], 0 );
  45027. cubeCamera.position.set( position.x, position.y, position.z );
  45028. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  45029. }
  45030. const size = this._cubeSize;
  45031. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  45032. renderer.setRenderTarget( cubeUVRenderTarget );
  45033. if ( useSolidColor ) {
  45034. renderer.render( backgroundBox, cubeCamera );
  45035. }
  45036. renderer.render( scene, cubeCamera );
  45037. }
  45038. renderer.toneMapping = toneMapping;
  45039. renderer.autoClear = originalAutoClear;
  45040. scene.background = background;
  45041. }
  45042. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  45043. const renderer = this._renderer;
  45044. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  45045. if ( isCubeTexture ) {
  45046. if ( this._cubemapMaterial === null ) {
  45047. this._cubemapMaterial = _getCubemapMaterial();
  45048. }
  45049. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  45050. } else {
  45051. if ( this._equirectMaterial === null ) {
  45052. this._equirectMaterial = _getEquirectMaterial();
  45053. }
  45054. }
  45055. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  45056. const mesh = this._lodMeshes[ 0 ];
  45057. mesh.material = material;
  45058. const uniforms = material.uniforms;
  45059. uniforms[ 'envMap' ].value = texture;
  45060. const size = this._cubeSize;
  45061. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  45062. renderer.setRenderTarget( cubeUVRenderTarget );
  45063. renderer.render( mesh, _flatCamera );
  45064. }
  45065. _applyPMREM( cubeUVRenderTarget ) {
  45066. const renderer = this._renderer;
  45067. const autoClear = renderer.autoClear;
  45068. renderer.autoClear = false;
  45069. const n = this._lodMeshes.length;
  45070. // Use GGX VNDF importance sampling
  45071. for ( let i = 1; i < n; i ++ ) {
  45072. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  45073. }
  45074. renderer.autoClear = autoClear;
  45075. }
  45076. /**
  45077. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  45078. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  45079. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  45080. * applies incremental roughness filtering to avoid over-blurring.
  45081. *
  45082. * @private
  45083. * @param {WebGLRenderTarget} cubeUVRenderTarget
  45084. * @param {number} lodIn - Source LOD level to read from
  45085. * @param {number} lodOut - Target LOD level to write to
  45086. */
  45087. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  45088. const renderer = this._renderer;
  45089. const pingPongRenderTarget = this._pingPongRenderTarget;
  45090. const ggxMaterial = this._ggxMaterial;
  45091. const ggxMesh = this._lodMeshes[ lodOut ];
  45092. ggxMesh.material = ggxMaterial;
  45093. const ggxUniforms = ggxMaterial.uniforms;
  45094. // Calculate incremental roughness between LOD levels
  45095. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  45096. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  45097. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  45098. // Apply blur strength mapping for better quality across the roughness range
  45099. const blurStrength = 0.0 + targetRoughness * 1.25;
  45100. const adjustedRoughness = incrementalRoughness * blurStrength;
  45101. // Calculate viewport position based on output LOD level
  45102. const { _lodMax } = this;
  45103. const outputSize = this._sizeLods[ lodOut ];
  45104. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45105. const y = 4 * ( this._cubeSize - outputSize );
  45106. // Read from previous LOD with incremental roughness
  45107. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  45108. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  45109. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  45110. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  45111. renderer.setRenderTarget( pingPongRenderTarget );
  45112. renderer.render( ggxMesh, _flatCamera );
  45113. // Copy from pingPong back to cubeUV (simple direct copy)
  45114. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  45115. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  45116. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  45117. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  45118. renderer.setRenderTarget( cubeUVRenderTarget );
  45119. renderer.render( ggxMesh, _flatCamera );
  45120. }
  45121. /**
  45122. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  45123. * vertically and horizontally, but this breaks down on a cube. Here we apply
  45124. * the blur latitudinally (around the poles), and then longitudinally (towards
  45125. * the poles) to approximate the orthogonally-separable blur. It is least
  45126. * accurate at the poles, but still does a decent job.
  45127. *
  45128. * Used for initial scene blur in fromScene() method when sigma > 0.
  45129. *
  45130. * @private
  45131. * @param {WebGLRenderTarget} cubeUVRenderTarget
  45132. * @param {number} lodIn
  45133. * @param {number} lodOut
  45134. * @param {number} sigma
  45135. * @param {Vector3} [poleAxis]
  45136. */
  45137. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  45138. const pingPongRenderTarget = this._pingPongRenderTarget;
  45139. this._halfBlur(
  45140. cubeUVRenderTarget,
  45141. pingPongRenderTarget,
  45142. lodIn,
  45143. lodOut,
  45144. sigma,
  45145. 'latitudinal',
  45146. poleAxis );
  45147. this._halfBlur(
  45148. pingPongRenderTarget,
  45149. cubeUVRenderTarget,
  45150. lodOut,
  45151. lodOut,
  45152. sigma,
  45153. 'longitudinal',
  45154. poleAxis );
  45155. }
  45156. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  45157. const renderer = this._renderer;
  45158. const blurMaterial = this._blurMaterial;
  45159. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  45160. error(
  45161. 'blur direction must be either latitudinal or longitudinal!' );
  45162. }
  45163. // Number of standard deviations at which to cut off the discrete approximation.
  45164. const STANDARD_DEVIATIONS = 3;
  45165. const blurMesh = this._lodMeshes[ lodOut ];
  45166. blurMesh.material = blurMaterial;
  45167. const blurUniforms = blurMaterial.uniforms;
  45168. const pixels = this._sizeLods[ lodIn ] - 1;
  45169. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  45170. const sigmaPixels = sigmaRadians / radiansPerPixel;
  45171. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  45172. if ( samples > MAX_SAMPLES ) {
  45173. warn( `sigmaRadians, ${
  45174. sigmaRadians}, is too large and will clip, as it requested ${
  45175. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  45176. }
  45177. const weights = [];
  45178. let sum = 0;
  45179. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  45180. const x = i / sigmaPixels;
  45181. const weight = Math.exp( - x * x / 2 );
  45182. weights.push( weight );
  45183. if ( i === 0 ) {
  45184. sum += weight;
  45185. } else if ( i < samples ) {
  45186. sum += 2 * weight;
  45187. }
  45188. }
  45189. for ( let i = 0; i < weights.length; i ++ ) {
  45190. weights[ i ] = weights[ i ] / sum;
  45191. }
  45192. blurUniforms[ 'envMap' ].value = targetIn.texture;
  45193. blurUniforms[ 'samples' ].value = samples;
  45194. blurUniforms[ 'weights' ].value = weights;
  45195. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  45196. if ( poleAxis ) {
  45197. blurUniforms[ 'poleAxis' ].value = poleAxis;
  45198. }
  45199. const { _lodMax } = this;
  45200. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  45201. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  45202. const outputSize = this._sizeLods[ lodOut ];
  45203. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45204. const y = 4 * ( this._cubeSize - outputSize );
  45205. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  45206. renderer.setRenderTarget( targetOut );
  45207. renderer.render( blurMesh, _flatCamera );
  45208. }
  45209. }
  45210. function _createPlanes( lodMax ) {
  45211. const sizeLods = [];
  45212. const sigmas = [];
  45213. const lodMeshes = [];
  45214. let lod = lodMax;
  45215. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  45216. for ( let i = 0; i < totalLods; i ++ ) {
  45217. const sizeLod = Math.pow( 2, lod );
  45218. sizeLods.push( sizeLod );
  45219. let sigma = 1.0 / sizeLod;
  45220. if ( i > lodMax - LOD_MIN ) {
  45221. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  45222. } else if ( i === 0 ) {
  45223. sigma = 0;
  45224. }
  45225. sigmas.push( sigma );
  45226. const texelSize = 1.0 / ( sizeLod - 2 );
  45227. const min = - texelSize;
  45228. const max = 1 + texelSize;
  45229. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  45230. const cubeFaces = 6;
  45231. const vertices = 6;
  45232. const positionSize = 3;
  45233. const uvSize = 2;
  45234. const faceIndexSize = 1;
  45235. const position = new Float32Array( positionSize * vertices * cubeFaces );
  45236. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  45237. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  45238. for ( let face = 0; face < cubeFaces; face ++ ) {
  45239. const x = ( face % 3 ) * 2 / 3 - 1;
  45240. const y = face > 2 ? 0 : -1;
  45241. const coordinates = [
  45242. x, y, 0,
  45243. x + 2 / 3, y, 0,
  45244. x + 2 / 3, y + 1, 0,
  45245. x, y, 0,
  45246. x + 2 / 3, y + 1, 0,
  45247. x, y + 1, 0
  45248. ];
  45249. position.set( coordinates, positionSize * vertices * face );
  45250. uv.set( uv1, uvSize * vertices * face );
  45251. const fill = [ face, face, face, face, face, face ];
  45252. faceIndex.set( fill, faceIndexSize * vertices * face );
  45253. }
  45254. const planes = new BufferGeometry();
  45255. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  45256. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  45257. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  45258. lodMeshes.push( new Mesh( planes, null ) );
  45259. if ( lod > LOD_MIN ) {
  45260. lod --;
  45261. }
  45262. }
  45263. return { lodMeshes, sizeLods, sigmas };
  45264. }
  45265. function _createRenderTarget( width, height, params ) {
  45266. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  45267. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  45268. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  45269. cubeUVRenderTarget.scissorTest = true;
  45270. return cubeUVRenderTarget;
  45271. }
  45272. function _setViewport( target, x, y, width, height ) {
  45273. target.viewport.set( x, y, width, height );
  45274. target.scissor.set( x, y, width, height );
  45275. }
  45276. function _getGGXShader( lodMax, width, height ) {
  45277. const shaderMaterial = new ShaderMaterial( {
  45278. name: 'PMREMGGXConvolution',
  45279. defines: {
  45280. 'GGX_SAMPLES': GGX_SAMPLES,
  45281. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45282. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45283. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45284. },
  45285. uniforms: {
  45286. 'envMap': { value: null },
  45287. 'roughness': { value: 0.0 },
  45288. 'mipInt': { value: 0 }
  45289. },
  45290. vertexShader: _getCommonVertexShader(),
  45291. fragmentShader: /* glsl */`
  45292. precision highp float;
  45293. precision highp int;
  45294. varying vec3 vOutputDirection;
  45295. uniform sampler2D envMap;
  45296. uniform float roughness;
  45297. uniform float mipInt;
  45298. #define ENVMAP_TYPE_CUBE_UV
  45299. #include <cube_uv_reflection_fragment>
  45300. #define PI 3.14159265359
  45301. // Van der Corput radical inverse
  45302. float radicalInverse_VdC(uint bits) {
  45303. bits = (bits << 16u) | (bits >> 16u);
  45304. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  45305. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  45306. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  45307. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  45308. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  45309. }
  45310. // Hammersley sequence
  45311. vec2 hammersley(uint i, uint N) {
  45312. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  45313. }
  45314. // GGX VNDF importance sampling (Eric Heitz 2018)
  45315. // "Sampling the GGX Distribution of Visible Normals"
  45316. // https://jcgt.org/published/0007/04/01/
  45317. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  45318. float alpha = roughness * roughness;
  45319. // Section 4.1: Orthonormal basis
  45320. vec3 T1 = vec3(1.0, 0.0, 0.0);
  45321. vec3 T2 = cross(V, T1);
  45322. // Section 4.2: Parameterization of projected area
  45323. float r = sqrt(Xi.x);
  45324. float phi = 2.0 * PI * Xi.y;
  45325. float t1 = r * cos(phi);
  45326. float t2 = r * sin(phi);
  45327. float s = 0.5 * (1.0 + V.z);
  45328. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45329. // Section 4.3: Reprojection onto hemisphere
  45330. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;
  45331. // Section 3.4: Transform back to ellipsoid configuration
  45332. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45333. }
  45334. void main() {
  45335. vec3 N = normalize(vOutputDirection);
  45336. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45337. vec3 prefilteredColor = vec3(0.0);
  45338. float totalWeight = 0.0;
  45339. // For very low roughness, just sample the environment directly
  45340. if (roughness < 0.001) {
  45341. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45342. return;
  45343. }
  45344. // Tangent space basis for VNDF sampling
  45345. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45346. vec3 tangent = normalize(cross(up, N));
  45347. vec3 bitangent = cross(N, tangent);
  45348. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45349. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45350. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45351. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45352. // Transform H back to world space
  45353. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45354. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45355. float NdotL = max(dot(N, L), 0.0);
  45356. if(NdotL > 0.0) {
  45357. // Sample environment at fixed mip level
  45358. // VNDF importance sampling handles the distribution filtering
  45359. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45360. // Weight by NdotL for the split-sum approximation
  45361. // VNDF PDF naturally accounts for the visible microfacet distribution
  45362. prefilteredColor += sampleColor * NdotL;
  45363. totalWeight += NdotL;
  45364. }
  45365. }
  45366. if (totalWeight > 0.0) {
  45367. prefilteredColor = prefilteredColor / totalWeight;
  45368. }
  45369. gl_FragColor = vec4(prefilteredColor, 1.0);
  45370. }
  45371. `,
  45372. blending: NoBlending,
  45373. depthTest: false,
  45374. depthWrite: false
  45375. } );
  45376. return shaderMaterial;
  45377. }
  45378. function _getBlurShader( lodMax, width, height ) {
  45379. const weights = new Float32Array( MAX_SAMPLES );
  45380. const poleAxis = new Vector3( 0, 1, 0 );
  45381. const shaderMaterial = new ShaderMaterial( {
  45382. name: 'SphericalGaussianBlur',
  45383. defines: {
  45384. 'n': MAX_SAMPLES,
  45385. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45386. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45387. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45388. },
  45389. uniforms: {
  45390. 'envMap': { value: null },
  45391. 'samples': { value: 1 },
  45392. 'weights': { value: weights },
  45393. 'latitudinal': { value: false },
  45394. 'dTheta': { value: 0 },
  45395. 'mipInt': { value: 0 },
  45396. 'poleAxis': { value: poleAxis }
  45397. },
  45398. vertexShader: _getCommonVertexShader(),
  45399. fragmentShader: /* glsl */`
  45400. precision mediump float;
  45401. precision mediump int;
  45402. varying vec3 vOutputDirection;
  45403. uniform sampler2D envMap;
  45404. uniform int samples;
  45405. uniform float weights[ n ];
  45406. uniform bool latitudinal;
  45407. uniform float dTheta;
  45408. uniform float mipInt;
  45409. uniform vec3 poleAxis;
  45410. #define ENVMAP_TYPE_CUBE_UV
  45411. #include <cube_uv_reflection_fragment>
  45412. vec3 getSample( float theta, vec3 axis ) {
  45413. float cosTheta = cos( theta );
  45414. // Rodrigues' axis-angle rotation
  45415. vec3 sampleDirection = vOutputDirection * cosTheta
  45416. + cross( axis, vOutputDirection ) * sin( theta )
  45417. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45418. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45419. }
  45420. void main() {
  45421. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45422. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45423. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45424. }
  45425. axis = normalize( axis );
  45426. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45427. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45428. for ( int i = 1; i < n; i++ ) {
  45429. if ( i >= samples ) {
  45430. break;
  45431. }
  45432. float theta = dTheta * float( i );
  45433. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45434. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45435. }
  45436. }
  45437. `,
  45438. blending: NoBlending,
  45439. depthTest: false,
  45440. depthWrite: false
  45441. } );
  45442. return shaderMaterial;
  45443. }
  45444. function _getEquirectMaterial() {
  45445. return new ShaderMaterial( {
  45446. name: 'EquirectangularToCubeUV',
  45447. uniforms: {
  45448. 'envMap': { value: null }
  45449. },
  45450. vertexShader: _getCommonVertexShader(),
  45451. fragmentShader: /* glsl */`
  45452. precision mediump float;
  45453. precision mediump int;
  45454. varying vec3 vOutputDirection;
  45455. uniform sampler2D envMap;
  45456. #include <common>
  45457. void main() {
  45458. vec3 outputDirection = normalize( vOutputDirection );
  45459. vec2 uv = equirectUv( outputDirection );
  45460. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45461. }
  45462. `,
  45463. blending: NoBlending,
  45464. depthTest: false,
  45465. depthWrite: false
  45466. } );
  45467. }
  45468. function _getCubemapMaterial() {
  45469. return new ShaderMaterial( {
  45470. name: 'CubemapToCubeUV',
  45471. uniforms: {
  45472. 'envMap': { value: null },
  45473. 'flipEnvMap': { value: -1 }
  45474. },
  45475. vertexShader: _getCommonVertexShader(),
  45476. fragmentShader: /* glsl */`
  45477. precision mediump float;
  45478. precision mediump int;
  45479. uniform float flipEnvMap;
  45480. varying vec3 vOutputDirection;
  45481. uniform samplerCube envMap;
  45482. void main() {
  45483. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45484. }
  45485. `,
  45486. blending: NoBlending,
  45487. depthTest: false,
  45488. depthWrite: false
  45489. } );
  45490. }
  45491. function _getCommonVertexShader() {
  45492. return /* glsl */`
  45493. precision mediump float;
  45494. precision mediump int;
  45495. attribute float faceIndex;
  45496. varying vec3 vOutputDirection;
  45497. // RH coordinate system; PMREM face-indexing convention
  45498. vec3 getDirection( vec2 uv, float face ) {
  45499. uv = 2.0 * uv - 1.0;
  45500. vec3 direction = vec3( uv, 1.0 );
  45501. if ( face == 0.0 ) {
  45502. direction = direction.zyx; // ( 1, v, u ) pos x
  45503. } else if ( face == 1.0 ) {
  45504. direction = direction.xzy;
  45505. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45506. } else if ( face == 2.0 ) {
  45507. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45508. } else if ( face == 3.0 ) {
  45509. direction = direction.zyx;
  45510. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45511. } else if ( face == 4.0 ) {
  45512. direction = direction.xzy;
  45513. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45514. } else if ( face == 5.0 ) {
  45515. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45516. }
  45517. return direction;
  45518. }
  45519. void main() {
  45520. vOutputDirection = getDirection( uv, faceIndex );
  45521. gl_Position = vec4( position, 1.0 );
  45522. }
  45523. `;
  45524. }
  45525. /**
  45526. * A cube render target used in context of {@link WebGLRenderer}.
  45527. *
  45528. * @augments WebGLRenderTarget
  45529. */
  45530. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  45531. /**
  45532. * Constructs a new cube render target.
  45533. *
  45534. * @param {number} [size=1] - The size of the render target.
  45535. * @param {RenderTarget~Options} [options] - The configuration object.
  45536. */
  45537. constructor( size = 1, options = {} ) {
  45538. super( size, size, options );
  45539. /**
  45540. * This flag can be used for type testing.
  45541. *
  45542. * @type {boolean}
  45543. * @readonly
  45544. * @default true
  45545. */
  45546. this.isWebGLCubeRenderTarget = true;
  45547. const image = { width: size, height: size, depth: 1 };
  45548. const images = [ image, image, image, image, image, image ];
  45549. /**
  45550. * Overwritten with a different texture type.
  45551. *
  45552. * @type {DataArrayTexture}
  45553. */
  45554. this.texture = new CubeTexture( images );
  45555. this._setTextureOptions( options );
  45556. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  45557. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  45558. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  45559. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  45560. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  45561. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  45562. this.texture.isRenderTargetTexture = true;
  45563. }
  45564. /**
  45565. * Converts the given equirectangular texture to a cube map.
  45566. *
  45567. * @param {WebGLRenderer} renderer - The renderer.
  45568. * @param {Texture} texture - The equirectangular texture.
  45569. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  45570. */
  45571. fromEquirectangularTexture( renderer, texture ) {
  45572. this.texture.type = texture.type;
  45573. this.texture.colorSpace = texture.colorSpace;
  45574. this.texture.generateMipmaps = texture.generateMipmaps;
  45575. this.texture.minFilter = texture.minFilter;
  45576. this.texture.magFilter = texture.magFilter;
  45577. const shader = {
  45578. uniforms: {
  45579. tEquirect: { value: null },
  45580. },
  45581. vertexShader: /* glsl */`
  45582. varying vec3 vWorldDirection;
  45583. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  45584. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  45585. }
  45586. void main() {
  45587. vWorldDirection = transformDirection( position, modelMatrix );
  45588. #include <begin_vertex>
  45589. #include <project_vertex>
  45590. }
  45591. `,
  45592. fragmentShader: /* glsl */`
  45593. uniform sampler2D tEquirect;
  45594. varying vec3 vWorldDirection;
  45595. #include <common>
  45596. void main() {
  45597. vec3 direction = normalize( vWorldDirection );
  45598. vec2 sampleUV = equirectUv( direction );
  45599. gl_FragColor = texture2D( tEquirect, sampleUV );
  45600. }
  45601. `
  45602. };
  45603. const geometry = new BoxGeometry( 5, 5, 5 );
  45604. const material = new ShaderMaterial( {
  45605. name: 'CubemapFromEquirect',
  45606. uniforms: cloneUniforms( shader.uniforms ),
  45607. vertexShader: shader.vertexShader,
  45608. fragmentShader: shader.fragmentShader,
  45609. side: BackSide,
  45610. blending: NoBlending
  45611. } );
  45612. material.uniforms.tEquirect.value = texture;
  45613. const mesh = new Mesh( geometry, material );
  45614. const currentMinFilter = texture.minFilter;
  45615. // Avoid blurred poles
  45616. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  45617. const camera = new CubeCamera( 1, 10, this );
  45618. camera.update( renderer, mesh );
  45619. texture.minFilter = currentMinFilter;
  45620. mesh.geometry.dispose();
  45621. mesh.material.dispose();
  45622. return this;
  45623. }
  45624. /**
  45625. * Clears this cube render target.
  45626. *
  45627. * @param {WebGLRenderer} renderer - The renderer.
  45628. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  45629. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  45630. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  45631. */
  45632. clear( renderer, color = true, depth = true, stencil = true ) {
  45633. const currentRenderTarget = renderer.getRenderTarget();
  45634. for ( let i = 0; i < 6; i ++ ) {
  45635. renderer.setRenderTarget( this, i );
  45636. renderer.clear( color, depth, stencil );
  45637. }
  45638. renderer.setRenderTarget( currentRenderTarget );
  45639. }
  45640. }
  45641. function WebGLEnvironments( renderer ) {
  45642. let cubeMaps = new WeakMap();
  45643. let pmremMaps = new WeakMap();
  45644. let pmremGenerator = null;
  45645. function get( texture, usePMREM = false ) {
  45646. if ( texture === null || texture === undefined ) return null;
  45647. if ( usePMREM ) {
  45648. return getPMREM( texture );
  45649. }
  45650. return getCube( texture );
  45651. }
  45652. function getCube( texture ) {
  45653. if ( texture && texture.isTexture ) {
  45654. const mapping = texture.mapping;
  45655. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  45656. if ( cubeMaps.has( texture ) ) {
  45657. const cubemap = cubeMaps.get( texture ).texture;
  45658. return mapTextureMapping( cubemap, texture.mapping );
  45659. } else {
  45660. const image = texture.image;
  45661. if ( image && image.height > 0 ) {
  45662. const renderTarget = new WebGLCubeRenderTarget( image.height );
  45663. renderTarget.fromEquirectangularTexture( renderer, texture );
  45664. cubeMaps.set( texture, renderTarget );
  45665. texture.addEventListener( 'dispose', onCubemapDispose );
  45666. return mapTextureMapping( renderTarget.texture, texture.mapping );
  45667. } else {
  45668. // image not yet ready. try the conversion next frame
  45669. return null;
  45670. }
  45671. }
  45672. }
  45673. }
  45674. return texture;
  45675. }
  45676. function getPMREM( texture ) {
  45677. if ( texture && texture.isTexture ) {
  45678. const mapping = texture.mapping;
  45679. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45680. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45681. // equirect/cube map to cubeUV conversion
  45682. if ( isEquirectMap || isCubeMap ) {
  45683. let renderTarget = pmremMaps.get( texture );
  45684. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45685. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45686. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45687. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45688. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45689. pmremMaps.set( texture, renderTarget );
  45690. return renderTarget.texture;
  45691. } else {
  45692. if ( renderTarget !== undefined ) {
  45693. return renderTarget.texture;
  45694. } else {
  45695. const image = texture.image;
  45696. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45697. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45698. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45699. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45700. pmremMaps.set( texture, renderTarget );
  45701. texture.addEventListener( 'dispose', onPMREMDispose );
  45702. return renderTarget.texture;
  45703. } else {
  45704. // image not yet ready. try the conversion next frame
  45705. return null;
  45706. }
  45707. }
  45708. }
  45709. }
  45710. }
  45711. return texture;
  45712. }
  45713. function mapTextureMapping( texture, mapping ) {
  45714. if ( mapping === EquirectangularReflectionMapping ) {
  45715. texture.mapping = CubeReflectionMapping;
  45716. } else if ( mapping === EquirectangularRefractionMapping ) {
  45717. texture.mapping = CubeRefractionMapping;
  45718. }
  45719. return texture;
  45720. }
  45721. function isCubeTextureComplete( image ) {
  45722. let count = 0;
  45723. const length = 6;
  45724. for ( let i = 0; i < length; i ++ ) {
  45725. if ( image[ i ] !== undefined ) count ++;
  45726. }
  45727. return count === length;
  45728. }
  45729. function onCubemapDispose( event ) {
  45730. const texture = event.target;
  45731. texture.removeEventListener( 'dispose', onCubemapDispose );
  45732. const cubemap = cubeMaps.get( texture );
  45733. if ( cubemap !== undefined ) {
  45734. cubeMaps.delete( texture );
  45735. cubemap.dispose();
  45736. }
  45737. }
  45738. function onPMREMDispose( event ) {
  45739. const texture = event.target;
  45740. texture.removeEventListener( 'dispose', onPMREMDispose );
  45741. const pmrem = pmremMaps.get( texture );
  45742. if ( pmrem !== undefined ) {
  45743. pmremMaps.delete( texture );
  45744. pmrem.dispose();
  45745. }
  45746. }
  45747. function dispose() {
  45748. cubeMaps = new WeakMap();
  45749. pmremMaps = new WeakMap();
  45750. if ( pmremGenerator !== null ) {
  45751. pmremGenerator.dispose();
  45752. pmremGenerator = null;
  45753. }
  45754. }
  45755. return {
  45756. get: get,
  45757. dispose: dispose
  45758. };
  45759. }
  45760. function WebGLExtensions( gl ) {
  45761. const extensions = {};
  45762. function getExtension( name ) {
  45763. if ( extensions[ name ] !== undefined ) {
  45764. return extensions[ name ];
  45765. }
  45766. const extension = gl.getExtension( name );
  45767. extensions[ name ] = extension;
  45768. return extension;
  45769. }
  45770. return {
  45771. has: function ( name ) {
  45772. return getExtension( name ) !== null;
  45773. },
  45774. init: function () {
  45775. getExtension( 'EXT_color_buffer_float' );
  45776. getExtension( 'WEBGL_clip_cull_distance' );
  45777. getExtension( 'OES_texture_float_linear' );
  45778. getExtension( 'EXT_color_buffer_half_float' );
  45779. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45780. getExtension( 'WEBGL_render_shared_exponent' );
  45781. },
  45782. get: function ( name ) {
  45783. const extension = getExtension( name );
  45784. if ( extension === null ) {
  45785. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45786. }
  45787. return extension;
  45788. }
  45789. };
  45790. }
  45791. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45792. const geometries = {};
  45793. const wireframeAttributes = new WeakMap();
  45794. function onGeometryDispose( event ) {
  45795. const geometry = event.target;
  45796. if ( geometry.index !== null ) {
  45797. attributes.remove( geometry.index );
  45798. }
  45799. for ( const name in geometry.attributes ) {
  45800. attributes.remove( geometry.attributes[ name ] );
  45801. }
  45802. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45803. delete geometries[ geometry.id ];
  45804. const attribute = wireframeAttributes.get( geometry );
  45805. if ( attribute ) {
  45806. attributes.remove( attribute );
  45807. wireframeAttributes.delete( geometry );
  45808. }
  45809. bindingStates.releaseStatesOfGeometry( geometry );
  45810. if ( geometry.isInstancedBufferGeometry === true ) {
  45811. delete geometry._maxInstanceCount;
  45812. }
  45813. //
  45814. info.memory.geometries --;
  45815. }
  45816. function get( object, geometry ) {
  45817. if ( geometries[ geometry.id ] === true ) return geometry;
  45818. geometry.addEventListener( 'dispose', onGeometryDispose );
  45819. geometries[ geometry.id ] = true;
  45820. info.memory.geometries ++;
  45821. return geometry;
  45822. }
  45823. function update( geometry ) {
  45824. const geometryAttributes = geometry.attributes;
  45825. // Updating index buffer in VAO now. See WebGLBindingStates.
  45826. for ( const name in geometryAttributes ) {
  45827. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45828. }
  45829. }
  45830. function updateWireframeAttribute( geometry ) {
  45831. const indices = [];
  45832. const geometryIndex = geometry.index;
  45833. const geometryPosition = geometry.attributes.position;
  45834. let version = 0;
  45835. if ( geometryPosition === undefined ) {
  45836. return;
  45837. }
  45838. if ( geometryIndex !== null ) {
  45839. const array = geometryIndex.array;
  45840. version = geometryIndex.version;
  45841. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45842. const a = array[ i + 0 ];
  45843. const b = array[ i + 1 ];
  45844. const c = array[ i + 2 ];
  45845. indices.push( a, b, b, c, c, a );
  45846. }
  45847. } else {
  45848. const array = geometryPosition.array;
  45849. version = geometryPosition.version;
  45850. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45851. const a = i + 0;
  45852. const b = i + 1;
  45853. const c = i + 2;
  45854. indices.push( a, b, b, c, c, a );
  45855. }
  45856. }
  45857. // check whether a 32 bit or 16 bit buffer is required to store the indices
  45858. // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  45859. const attribute = new ( geometryPosition.count >= 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45860. attribute.version = version;
  45861. // Updating index buffer in VAO now. See WebGLBindingStates
  45862. //
  45863. const previousAttribute = wireframeAttributes.get( geometry );
  45864. if ( previousAttribute ) attributes.remove( previousAttribute );
  45865. //
  45866. wireframeAttributes.set( geometry, attribute );
  45867. }
  45868. function getWireframeAttribute( geometry ) {
  45869. const currentAttribute = wireframeAttributes.get( geometry );
  45870. if ( currentAttribute ) {
  45871. const geometryIndex = geometry.index;
  45872. if ( geometryIndex !== null ) {
  45873. // if the attribute is obsolete, create a new one
  45874. if ( currentAttribute.version < geometryIndex.version ) {
  45875. updateWireframeAttribute( geometry );
  45876. }
  45877. }
  45878. } else {
  45879. updateWireframeAttribute( geometry );
  45880. }
  45881. return wireframeAttributes.get( geometry );
  45882. }
  45883. return {
  45884. get: get,
  45885. update: update,
  45886. getWireframeAttribute: getWireframeAttribute
  45887. };
  45888. }
  45889. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45890. let mode;
  45891. function setMode( value ) {
  45892. mode = value;
  45893. }
  45894. let type, bytesPerElement;
  45895. function setIndex( value ) {
  45896. type = value.type;
  45897. bytesPerElement = value.bytesPerElement;
  45898. }
  45899. function render( start, count ) {
  45900. gl.drawElements( mode, count, type, start * bytesPerElement );
  45901. info.update( count, mode, 1 );
  45902. }
  45903. function renderInstances( start, count, primcount ) {
  45904. if ( primcount === 0 ) return;
  45905. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45906. info.update( count, mode, primcount );
  45907. }
  45908. function renderMultiDraw( starts, counts, drawCount ) {
  45909. if ( drawCount === 0 ) return;
  45910. const extension = extensions.get( 'WEBGL_multi_draw' );
  45911. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45912. let elementCount = 0;
  45913. for ( let i = 0; i < drawCount; i ++ ) {
  45914. elementCount += counts[ i ];
  45915. }
  45916. info.update( elementCount, mode, 1 );
  45917. }
  45918. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45919. if ( drawCount === 0 ) return;
  45920. const extension = extensions.get( 'WEBGL_multi_draw' );
  45921. if ( extension === null ) {
  45922. for ( let i = 0; i < starts.length; i ++ ) {
  45923. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45924. }
  45925. } else {
  45926. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45927. let elementCount = 0;
  45928. for ( let i = 0; i < drawCount; i ++ ) {
  45929. elementCount += counts[ i ] * primcount[ i ];
  45930. }
  45931. info.update( elementCount, mode, 1 );
  45932. }
  45933. }
  45934. //
  45935. this.setMode = setMode;
  45936. this.setIndex = setIndex;
  45937. this.render = render;
  45938. this.renderInstances = renderInstances;
  45939. this.renderMultiDraw = renderMultiDraw;
  45940. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45941. }
  45942. function WebGLInfo( gl ) {
  45943. const memory = {
  45944. geometries: 0,
  45945. textures: 0
  45946. };
  45947. const render = {
  45948. frame: 0,
  45949. calls: 0,
  45950. triangles: 0,
  45951. points: 0,
  45952. lines: 0
  45953. };
  45954. function update( count, mode, instanceCount ) {
  45955. render.calls ++;
  45956. switch ( mode ) {
  45957. case gl.TRIANGLES:
  45958. render.triangles += instanceCount * ( count / 3 );
  45959. break;
  45960. case gl.LINES:
  45961. render.lines += instanceCount * ( count / 2 );
  45962. break;
  45963. case gl.LINE_STRIP:
  45964. render.lines += instanceCount * ( count - 1 );
  45965. break;
  45966. case gl.LINE_LOOP:
  45967. render.lines += instanceCount * count;
  45968. break;
  45969. case gl.POINTS:
  45970. render.points += instanceCount * count;
  45971. break;
  45972. default:
  45973. error( 'WebGLInfo: Unknown draw mode:', mode );
  45974. break;
  45975. }
  45976. }
  45977. function reset() {
  45978. render.calls = 0;
  45979. render.triangles = 0;
  45980. render.points = 0;
  45981. render.lines = 0;
  45982. }
  45983. return {
  45984. memory: memory,
  45985. render: render,
  45986. programs: null,
  45987. autoReset: true,
  45988. reset: reset,
  45989. update: update
  45990. };
  45991. }
  45992. function WebGLMorphtargets( gl, capabilities, textures ) {
  45993. const morphTextures = new WeakMap();
  45994. const morph = new Vector4();
  45995. function update( object, geometry, program ) {
  45996. const objectInfluences = object.morphTargetInfluences;
  45997. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45998. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45999. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  46000. let entry = morphTextures.get( geometry );
  46001. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  46002. if ( entry !== undefined ) entry.texture.dispose();
  46003. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  46004. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  46005. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  46006. const morphTargets = geometry.morphAttributes.position || [];
  46007. const morphNormals = geometry.morphAttributes.normal || [];
  46008. const morphColors = geometry.morphAttributes.color || [];
  46009. let vertexDataCount = 0;
  46010. if ( hasMorphPosition === true ) vertexDataCount = 1;
  46011. if ( hasMorphNormals === true ) vertexDataCount = 2;
  46012. if ( hasMorphColors === true ) vertexDataCount = 3;
  46013. let width = geometry.attributes.position.count * vertexDataCount;
  46014. let height = 1;
  46015. if ( width > capabilities.maxTextureSize ) {
  46016. height = Math.ceil( width / capabilities.maxTextureSize );
  46017. width = capabilities.maxTextureSize;
  46018. }
  46019. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  46020. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  46021. texture.type = FloatType;
  46022. texture.needsUpdate = true;
  46023. // fill buffer
  46024. const vertexDataStride = vertexDataCount * 4;
  46025. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  46026. const morphTarget = morphTargets[ i ];
  46027. const morphNormal = morphNormals[ i ];
  46028. const morphColor = morphColors[ i ];
  46029. const offset = width * height * 4 * i;
  46030. for ( let j = 0; j < morphTarget.count; j ++ ) {
  46031. const stride = j * vertexDataStride;
  46032. if ( hasMorphPosition === true ) {
  46033. morph.fromBufferAttribute( morphTarget, j );
  46034. buffer[ offset + stride + 0 ] = morph.x;
  46035. buffer[ offset + stride + 1 ] = morph.y;
  46036. buffer[ offset + stride + 2 ] = morph.z;
  46037. buffer[ offset + stride + 3 ] = 0;
  46038. }
  46039. if ( hasMorphNormals === true ) {
  46040. morph.fromBufferAttribute( morphNormal, j );
  46041. buffer[ offset + stride + 4 ] = morph.x;
  46042. buffer[ offset + stride + 5 ] = morph.y;
  46043. buffer[ offset + stride + 6 ] = morph.z;
  46044. buffer[ offset + stride + 7 ] = 0;
  46045. }
  46046. if ( hasMorphColors === true ) {
  46047. morph.fromBufferAttribute( morphColor, j );
  46048. buffer[ offset + stride + 8 ] = morph.x;
  46049. buffer[ offset + stride + 9 ] = morph.y;
  46050. buffer[ offset + stride + 10 ] = morph.z;
  46051. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  46052. }
  46053. }
  46054. }
  46055. entry = {
  46056. count: morphTargetsCount,
  46057. texture: texture,
  46058. size: new Vector2( width, height )
  46059. };
  46060. morphTextures.set( geometry, entry );
  46061. function disposeTexture() {
  46062. texture.dispose();
  46063. morphTextures.delete( geometry );
  46064. geometry.removeEventListener( 'dispose', disposeTexture );
  46065. }
  46066. geometry.addEventListener( 'dispose', disposeTexture );
  46067. }
  46068. //
  46069. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  46070. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  46071. } else {
  46072. let morphInfluencesSum = 0;
  46073. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  46074. morphInfluencesSum += objectInfluences[ i ];
  46075. }
  46076. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  46077. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  46078. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  46079. }
  46080. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  46081. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  46082. }
  46083. return {
  46084. update: update
  46085. };
  46086. }
  46087. function WebGLObjects( gl, geometries, attributes, bindingStates, info ) {
  46088. let updateMap = new WeakMap();
  46089. function update( object ) {
  46090. const frame = info.render.frame;
  46091. const geometry = object.geometry;
  46092. const buffergeometry = geometries.get( object, geometry );
  46093. // Update once per frame
  46094. if ( updateMap.get( buffergeometry ) !== frame ) {
  46095. geometries.update( buffergeometry );
  46096. updateMap.set( buffergeometry, frame );
  46097. }
  46098. if ( object.isInstancedMesh ) {
  46099. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  46100. object.addEventListener( 'dispose', onInstancedMeshDispose );
  46101. }
  46102. if ( updateMap.get( object ) !== frame ) {
  46103. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  46104. if ( object.instanceColor !== null ) {
  46105. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  46106. }
  46107. updateMap.set( object, frame );
  46108. }
  46109. }
  46110. if ( object.isSkinnedMesh ) {
  46111. const skeleton = object.skeleton;
  46112. if ( updateMap.get( skeleton ) !== frame ) {
  46113. skeleton.update();
  46114. updateMap.set( skeleton, frame );
  46115. }
  46116. }
  46117. return buffergeometry;
  46118. }
  46119. function dispose() {
  46120. updateMap = new WeakMap();
  46121. }
  46122. function onInstancedMeshDispose( event ) {
  46123. const instancedMesh = event.target;
  46124. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  46125. bindingStates.releaseStatesOfObject( instancedMesh );
  46126. attributes.remove( instancedMesh.instanceMatrix );
  46127. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  46128. }
  46129. return {
  46130. update: update,
  46131. dispose: dispose
  46132. };
  46133. }
  46134. const toneMappingMap = {
  46135. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  46136. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  46137. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  46138. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  46139. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  46140. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  46141. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  46142. };
  46143. function WebGLOutput( type, width, height, depth, stencil ) {
  46144. // render targets for scene and post-processing
  46145. const targetA = new WebGLRenderTarget( width, height, {
  46146. type: type,
  46147. depthBuffer: depth,
  46148. stencilBuffer: stencil
  46149. } );
  46150. const targetB = new WebGLRenderTarget( width, height, {
  46151. type: HalfFloatType,
  46152. depthBuffer: false,
  46153. stencilBuffer: false
  46154. } );
  46155. // create fullscreen triangle geometry
  46156. const geometry = new BufferGeometry();
  46157. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  46158. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  46159. // create output material with tone mapping support
  46160. const material = new RawShaderMaterial( {
  46161. uniforms: {
  46162. tDiffuse: { value: null }
  46163. },
  46164. vertexShader: /* glsl */`
  46165. precision highp float;
  46166. uniform mat4 modelViewMatrix;
  46167. uniform mat4 projectionMatrix;
  46168. attribute vec3 position;
  46169. attribute vec2 uv;
  46170. varying vec2 vUv;
  46171. void main() {
  46172. vUv = uv;
  46173. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  46174. }`,
  46175. fragmentShader: /* glsl */`
  46176. precision highp float;
  46177. uniform sampler2D tDiffuse;
  46178. varying vec2 vUv;
  46179. #include <tonemapping_pars_fragment>
  46180. #include <colorspace_pars_fragment>
  46181. void main() {
  46182. gl_FragColor = texture2D( tDiffuse, vUv );
  46183. #ifdef LINEAR_TONE_MAPPING
  46184. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  46185. #elif defined( REINHARD_TONE_MAPPING )
  46186. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  46187. #elif defined( CINEON_TONE_MAPPING )
  46188. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  46189. #elif defined( ACES_FILMIC_TONE_MAPPING )
  46190. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  46191. #elif defined( AGX_TONE_MAPPING )
  46192. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  46193. #elif defined( NEUTRAL_TONE_MAPPING )
  46194. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  46195. #elif defined( CUSTOM_TONE_MAPPING )
  46196. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  46197. #endif
  46198. #ifdef SRGB_TRANSFER
  46199. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  46200. #endif
  46201. }`,
  46202. depthTest: false,
  46203. depthWrite: false
  46204. } );
  46205. const mesh = new Mesh( geometry, material );
  46206. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  46207. let _outputColorSpace = null;
  46208. let _outputToneMapping = null;
  46209. let _isCompositing = false;
  46210. let _savedToneMapping;
  46211. let _savedRenderTarget = null;
  46212. let _effects = [];
  46213. let _hasRenderPass = false;
  46214. this.setSize = function ( width, height ) {
  46215. targetA.setSize( width, height );
  46216. targetB.setSize( width, height );
  46217. for ( let i = 0; i < _effects.length; i ++ ) {
  46218. const effect = _effects[ i ];
  46219. if ( effect.setSize ) effect.setSize( width, height );
  46220. }
  46221. };
  46222. this.setEffects = function ( effects ) {
  46223. _effects = effects;
  46224. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  46225. const width = targetA.width;
  46226. const height = targetA.height;
  46227. for ( let i = 0; i < _effects.length; i ++ ) {
  46228. const effect = _effects[ i ];
  46229. if ( effect.setSize ) effect.setSize( width, height );
  46230. }
  46231. };
  46232. this.begin = function ( renderer, renderTarget ) {
  46233. // Don't begin during compositing phase (post-processing effects call render())
  46234. if ( _isCompositing ) return false;
  46235. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  46236. _savedRenderTarget = renderTarget;
  46237. // resize internal buffers to match render target (e.g. XR resolution)
  46238. if ( renderTarget !== null ) {
  46239. const width = renderTarget.width;
  46240. const height = renderTarget.height;
  46241. if ( targetA.width !== width || targetA.height !== height ) {
  46242. this.setSize( width, height );
  46243. }
  46244. }
  46245. // if first effect is a RenderPass, it will set its own render target
  46246. if ( _hasRenderPass === false ) {
  46247. renderer.setRenderTarget( targetA );
  46248. }
  46249. // disable tone mapping during render - it will be applied in end()
  46250. _savedToneMapping = renderer.toneMapping;
  46251. renderer.toneMapping = NoToneMapping;
  46252. return true;
  46253. };
  46254. this.hasRenderPass = function () {
  46255. return _hasRenderPass;
  46256. };
  46257. this.end = function ( renderer, deltaTime ) {
  46258. // restore tone mapping
  46259. renderer.toneMapping = _savedToneMapping;
  46260. _isCompositing = true;
  46261. // run post-processing effects
  46262. let readBuffer = targetA;
  46263. let writeBuffer = targetB;
  46264. for ( let i = 0; i < _effects.length; i ++ ) {
  46265. const effect = _effects[ i ];
  46266. if ( effect.enabled === false ) continue;
  46267. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  46268. if ( effect.needsSwap !== false ) {
  46269. const temp = readBuffer;
  46270. readBuffer = writeBuffer;
  46271. writeBuffer = temp;
  46272. }
  46273. }
  46274. // update output material defines if settings changed
  46275. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  46276. _outputColorSpace = renderer.outputColorSpace;
  46277. _outputToneMapping = renderer.toneMapping;
  46278. material.defines = {};
  46279. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  46280. const toneMapping = toneMappingMap[ _outputToneMapping ];
  46281. if ( toneMapping ) material.defines[ toneMapping ] = '';
  46282. material.needsUpdate = true;
  46283. }
  46284. // final output to canvas (or XR render target)
  46285. material.uniforms.tDiffuse.value = readBuffer.texture;
  46286. renderer.setRenderTarget( _savedRenderTarget );
  46287. renderer.render( mesh, camera );
  46288. _savedRenderTarget = null;
  46289. _isCompositing = false;
  46290. };
  46291. this.isCompositing = function () {
  46292. return _isCompositing;
  46293. };
  46294. this.dispose = function () {
  46295. targetA.dispose();
  46296. targetB.dispose();
  46297. geometry.dispose();
  46298. material.dispose();
  46299. };
  46300. }
  46301. /**
  46302. * Uniforms of a program.
  46303. * Those form a tree structure with a special top-level container for the root,
  46304. * which you get by calling 'new WebGLUniforms( gl, program )'.
  46305. *
  46306. *
  46307. * Properties of inner nodes including the top-level container:
  46308. *
  46309. * .seq - array of nested uniforms
  46310. * .map - nested uniforms by name
  46311. *
  46312. *
  46313. * Methods of all nodes except the top-level container:
  46314. *
  46315. * .setValue( gl, value, [textures] )
  46316. *
  46317. * uploads a uniform value(s)
  46318. * the 'textures' parameter is needed for sampler uniforms
  46319. *
  46320. *
  46321. * Static methods of the top-level container (textures factorizations):
  46322. *
  46323. * .upload( gl, seq, values, textures )
  46324. *
  46325. * sets uniforms in 'seq' to 'values[id].value'
  46326. *
  46327. * .seqWithValue( seq, values ) : filteredSeq
  46328. *
  46329. * filters 'seq' entries with corresponding entry in values
  46330. *
  46331. *
  46332. * Methods of the top-level container (textures factorizations):
  46333. *
  46334. * .setValue( gl, name, value, textures )
  46335. *
  46336. * sets uniform with name 'name' to 'value'
  46337. *
  46338. * .setOptional( gl, obj, prop )
  46339. *
  46340. * like .set for an optional property of the object
  46341. *
  46342. */
  46343. const emptyTexture = /*@__PURE__*/ new Texture();
  46344. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  46345. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  46346. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  46347. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  46348. // --- Utilities ---
  46349. // Array Caches (provide typed arrays for temporary by size)
  46350. const arrayCacheF32 = [];
  46351. const arrayCacheI32 = [];
  46352. // Float32Array caches used for uploading Matrix uniforms
  46353. const mat4array = new Float32Array( 16 );
  46354. const mat3array = new Float32Array( 9 );
  46355. const mat2array = new Float32Array( 4 );
  46356. // Flattening for arrays of vectors and matrices
  46357. function flatten( array, nBlocks, blockSize ) {
  46358. const firstElem = array[ 0 ];
  46359. if ( firstElem <= 0 || firstElem > 0 ) return array;
  46360. // unoptimized: ! isNaN( firstElem )
  46361. // see http://jacksondunstan.com/articles/983
  46362. const n = nBlocks * blockSize;
  46363. let r = arrayCacheF32[ n ];
  46364. if ( r === undefined ) {
  46365. r = new Float32Array( n );
  46366. arrayCacheF32[ n ] = r;
  46367. }
  46368. if ( nBlocks !== 0 ) {
  46369. firstElem.toArray( r, 0 );
  46370. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  46371. offset += blockSize;
  46372. array[ i ].toArray( r, offset );
  46373. }
  46374. }
  46375. return r;
  46376. }
  46377. function arraysEqual( a, b ) {
  46378. if ( a.length !== b.length ) return false;
  46379. for ( let i = 0, l = a.length; i < l; i ++ ) {
  46380. if ( a[ i ] !== b[ i ] ) return false;
  46381. }
  46382. return true;
  46383. }
  46384. function copyArray( a, b ) {
  46385. for ( let i = 0, l = b.length; i < l; i ++ ) {
  46386. a[ i ] = b[ i ];
  46387. }
  46388. }
  46389. // Texture unit allocation
  46390. function allocTexUnits( textures, n ) {
  46391. let r = arrayCacheI32[ n ];
  46392. if ( r === undefined ) {
  46393. r = new Int32Array( n );
  46394. arrayCacheI32[ n ] = r;
  46395. }
  46396. for ( let i = 0; i !== n; ++ i ) {
  46397. r[ i ] = textures.allocateTextureUnit();
  46398. }
  46399. return r;
  46400. }
  46401. // --- Setters ---
  46402. // Note: Defining these methods externally, because they come in a bunch
  46403. // and this way their names minify.
  46404. // Single scalar
  46405. function setValueV1f( gl, v ) {
  46406. const cache = this.cache;
  46407. if ( cache[ 0 ] === v ) return;
  46408. gl.uniform1f( this.addr, v );
  46409. cache[ 0 ] = v;
  46410. }
  46411. // Single float vector (from flat array or THREE.VectorN)
  46412. function setValueV2f( gl, v ) {
  46413. const cache = this.cache;
  46414. if ( v.x !== undefined ) {
  46415. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46416. gl.uniform2f( this.addr, v.x, v.y );
  46417. cache[ 0 ] = v.x;
  46418. cache[ 1 ] = v.y;
  46419. }
  46420. } else {
  46421. if ( arraysEqual( cache, v ) ) return;
  46422. gl.uniform2fv( this.addr, v );
  46423. copyArray( cache, v );
  46424. }
  46425. }
  46426. function setValueV3f( gl, v ) {
  46427. const cache = this.cache;
  46428. if ( v.x !== undefined ) {
  46429. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46430. gl.uniform3f( this.addr, v.x, v.y, v.z );
  46431. cache[ 0 ] = v.x;
  46432. cache[ 1 ] = v.y;
  46433. cache[ 2 ] = v.z;
  46434. }
  46435. } else if ( v.r !== undefined ) {
  46436. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  46437. gl.uniform3f( this.addr, v.r, v.g, v.b );
  46438. cache[ 0 ] = v.r;
  46439. cache[ 1 ] = v.g;
  46440. cache[ 2 ] = v.b;
  46441. }
  46442. } else {
  46443. if ( arraysEqual( cache, v ) ) return;
  46444. gl.uniform3fv( this.addr, v );
  46445. copyArray( cache, v );
  46446. }
  46447. }
  46448. function setValueV4f( gl, v ) {
  46449. const cache = this.cache;
  46450. if ( v.x !== undefined ) {
  46451. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46452. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  46453. cache[ 0 ] = v.x;
  46454. cache[ 1 ] = v.y;
  46455. cache[ 2 ] = v.z;
  46456. cache[ 3 ] = v.w;
  46457. }
  46458. } else {
  46459. if ( arraysEqual( cache, v ) ) return;
  46460. gl.uniform4fv( this.addr, v );
  46461. copyArray( cache, v );
  46462. }
  46463. }
  46464. // Single matrix (from flat array or THREE.MatrixN)
  46465. function setValueM2( gl, v ) {
  46466. const cache = this.cache;
  46467. const elements = v.elements;
  46468. if ( elements === undefined ) {
  46469. if ( arraysEqual( cache, v ) ) return;
  46470. gl.uniformMatrix2fv( this.addr, false, v );
  46471. copyArray( cache, v );
  46472. } else {
  46473. if ( arraysEqual( cache, elements ) ) return;
  46474. mat2array.set( elements );
  46475. gl.uniformMatrix2fv( this.addr, false, mat2array );
  46476. copyArray( cache, elements );
  46477. }
  46478. }
  46479. function setValueM3( gl, v ) {
  46480. const cache = this.cache;
  46481. const elements = v.elements;
  46482. if ( elements === undefined ) {
  46483. if ( arraysEqual( cache, v ) ) return;
  46484. gl.uniformMatrix3fv( this.addr, false, v );
  46485. copyArray( cache, v );
  46486. } else {
  46487. if ( arraysEqual( cache, elements ) ) return;
  46488. mat3array.set( elements );
  46489. gl.uniformMatrix3fv( this.addr, false, mat3array );
  46490. copyArray( cache, elements );
  46491. }
  46492. }
  46493. function setValueM4( gl, v ) {
  46494. const cache = this.cache;
  46495. const elements = v.elements;
  46496. if ( elements === undefined ) {
  46497. if ( arraysEqual( cache, v ) ) return;
  46498. gl.uniformMatrix4fv( this.addr, false, v );
  46499. copyArray( cache, v );
  46500. } else {
  46501. if ( arraysEqual( cache, elements ) ) return;
  46502. mat4array.set( elements );
  46503. gl.uniformMatrix4fv( this.addr, false, mat4array );
  46504. copyArray( cache, elements );
  46505. }
  46506. }
  46507. // Single integer / boolean
  46508. function setValueV1i( gl, v ) {
  46509. const cache = this.cache;
  46510. if ( cache[ 0 ] === v ) return;
  46511. gl.uniform1i( this.addr, v );
  46512. cache[ 0 ] = v;
  46513. }
  46514. // Single integer / boolean vector (from flat array or THREE.VectorN)
  46515. function setValueV2i( gl, v ) {
  46516. const cache = this.cache;
  46517. if ( v.x !== undefined ) {
  46518. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46519. gl.uniform2i( this.addr, v.x, v.y );
  46520. cache[ 0 ] = v.x;
  46521. cache[ 1 ] = v.y;
  46522. }
  46523. } else {
  46524. if ( arraysEqual( cache, v ) ) return;
  46525. gl.uniform2iv( this.addr, v );
  46526. copyArray( cache, v );
  46527. }
  46528. }
  46529. function setValueV3i( gl, v ) {
  46530. const cache = this.cache;
  46531. if ( v.x !== undefined ) {
  46532. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46533. gl.uniform3i( this.addr, v.x, v.y, v.z );
  46534. cache[ 0 ] = v.x;
  46535. cache[ 1 ] = v.y;
  46536. cache[ 2 ] = v.z;
  46537. }
  46538. } else {
  46539. if ( arraysEqual( cache, v ) ) return;
  46540. gl.uniform3iv( this.addr, v );
  46541. copyArray( cache, v );
  46542. }
  46543. }
  46544. function setValueV4i( gl, v ) {
  46545. const cache = this.cache;
  46546. if ( v.x !== undefined ) {
  46547. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46548. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  46549. cache[ 0 ] = v.x;
  46550. cache[ 1 ] = v.y;
  46551. cache[ 2 ] = v.z;
  46552. cache[ 3 ] = v.w;
  46553. }
  46554. } else {
  46555. if ( arraysEqual( cache, v ) ) return;
  46556. gl.uniform4iv( this.addr, v );
  46557. copyArray( cache, v );
  46558. }
  46559. }
  46560. // Single unsigned integer
  46561. function setValueV1ui( gl, v ) {
  46562. const cache = this.cache;
  46563. if ( cache[ 0 ] === v ) return;
  46564. gl.uniform1ui( this.addr, v );
  46565. cache[ 0 ] = v;
  46566. }
  46567. // Single unsigned integer vector (from flat array or THREE.VectorN)
  46568. function setValueV2ui( gl, v ) {
  46569. const cache = this.cache;
  46570. if ( v.x !== undefined ) {
  46571. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46572. gl.uniform2ui( this.addr, v.x, v.y );
  46573. cache[ 0 ] = v.x;
  46574. cache[ 1 ] = v.y;
  46575. }
  46576. } else {
  46577. if ( arraysEqual( cache, v ) ) return;
  46578. gl.uniform2uiv( this.addr, v );
  46579. copyArray( cache, v );
  46580. }
  46581. }
  46582. function setValueV3ui( gl, v ) {
  46583. const cache = this.cache;
  46584. if ( v.x !== undefined ) {
  46585. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46586. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  46587. cache[ 0 ] = v.x;
  46588. cache[ 1 ] = v.y;
  46589. cache[ 2 ] = v.z;
  46590. }
  46591. } else {
  46592. if ( arraysEqual( cache, v ) ) return;
  46593. gl.uniform3uiv( this.addr, v );
  46594. copyArray( cache, v );
  46595. }
  46596. }
  46597. function setValueV4ui( gl, v ) {
  46598. const cache = this.cache;
  46599. if ( v.x !== undefined ) {
  46600. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46601. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  46602. cache[ 0 ] = v.x;
  46603. cache[ 1 ] = v.y;
  46604. cache[ 2 ] = v.z;
  46605. cache[ 3 ] = v.w;
  46606. }
  46607. } else {
  46608. if ( arraysEqual( cache, v ) ) return;
  46609. gl.uniform4uiv( this.addr, v );
  46610. copyArray( cache, v );
  46611. }
  46612. }
  46613. // Single texture (2D / Cube)
  46614. function setValueT1( gl, v, textures ) {
  46615. const cache = this.cache;
  46616. const unit = textures.allocateTextureUnit();
  46617. if ( cache[ 0 ] !== unit ) {
  46618. gl.uniform1i( this.addr, unit );
  46619. cache[ 0 ] = unit;
  46620. }
  46621. let emptyTexture2D;
  46622. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46623. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  46624. emptyTexture2D = emptyShadowTexture;
  46625. } else {
  46626. emptyTexture2D = emptyTexture;
  46627. }
  46628. textures.setTexture2D( v || emptyTexture2D, unit );
  46629. }
  46630. function setValueT3D1( gl, v, textures ) {
  46631. const cache = this.cache;
  46632. const unit = textures.allocateTextureUnit();
  46633. if ( cache[ 0 ] !== unit ) {
  46634. gl.uniform1i( this.addr, unit );
  46635. cache[ 0 ] = unit;
  46636. }
  46637. textures.setTexture3D( v || empty3dTexture, unit );
  46638. }
  46639. function setValueT6( gl, v, textures ) {
  46640. const cache = this.cache;
  46641. const unit = textures.allocateTextureUnit();
  46642. if ( cache[ 0 ] !== unit ) {
  46643. gl.uniform1i( this.addr, unit );
  46644. cache[ 0 ] = unit;
  46645. }
  46646. textures.setTextureCube( v || emptyCubeTexture, unit );
  46647. }
  46648. function setValueT2DArray1( gl, v, textures ) {
  46649. const cache = this.cache;
  46650. const unit = textures.allocateTextureUnit();
  46651. if ( cache[ 0 ] !== unit ) {
  46652. gl.uniform1i( this.addr, unit );
  46653. cache[ 0 ] = unit;
  46654. }
  46655. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46656. }
  46657. // Helper to pick the right setter for the singular case
  46658. function getSingularSetter( type ) {
  46659. switch ( type ) {
  46660. case 0x1406: return setValueV1f; // FLOAT
  46661. case 0x8b50: return setValueV2f; // _VEC2
  46662. case 0x8b51: return setValueV3f; // _VEC3
  46663. case 0x8b52: return setValueV4f; // _VEC4
  46664. case 0x8b5a: return setValueM2; // _MAT2
  46665. case 0x8b5b: return setValueM3; // _MAT3
  46666. case 0x8b5c: return setValueM4; // _MAT4
  46667. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46668. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46669. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46670. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46671. case 0x1405: return setValueV1ui; // UINT
  46672. case 0x8dc6: return setValueV2ui; // _VEC2
  46673. case 0x8dc7: return setValueV3ui; // _VEC3
  46674. case 0x8dc8: return setValueV4ui; // _VEC4
  46675. case 0x8b5e: // SAMPLER_2D
  46676. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46677. case 0x8dca: // INT_SAMPLER_2D
  46678. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46679. case 0x8b62: // SAMPLER_2D_SHADOW
  46680. return setValueT1;
  46681. case 0x8b5f: // SAMPLER_3D
  46682. case 0x8dcb: // INT_SAMPLER_3D
  46683. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46684. return setValueT3D1;
  46685. case 0x8b60: // SAMPLER_CUBE
  46686. case 0x8dcc: // INT_SAMPLER_CUBE
  46687. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46688. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46689. return setValueT6;
  46690. case 0x8dc1: // SAMPLER_2D_ARRAY
  46691. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46692. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46693. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46694. return setValueT2DArray1;
  46695. }
  46696. }
  46697. // Array of scalars
  46698. function setValueV1fArray( gl, v ) {
  46699. gl.uniform1fv( this.addr, v );
  46700. }
  46701. // Array of vectors (from flat array or array of THREE.VectorN)
  46702. function setValueV2fArray( gl, v ) {
  46703. const data = flatten( v, this.size, 2 );
  46704. gl.uniform2fv( this.addr, data );
  46705. }
  46706. function setValueV3fArray( gl, v ) {
  46707. const data = flatten( v, this.size, 3 );
  46708. gl.uniform3fv( this.addr, data );
  46709. }
  46710. function setValueV4fArray( gl, v ) {
  46711. const data = flatten( v, this.size, 4 );
  46712. gl.uniform4fv( this.addr, data );
  46713. }
  46714. // Array of matrices (from flat array or array of THREE.MatrixN)
  46715. function setValueM2Array( gl, v ) {
  46716. const data = flatten( v, this.size, 4 );
  46717. gl.uniformMatrix2fv( this.addr, false, data );
  46718. }
  46719. function setValueM3Array( gl, v ) {
  46720. const data = flatten( v, this.size, 9 );
  46721. gl.uniformMatrix3fv( this.addr, false, data );
  46722. }
  46723. function setValueM4Array( gl, v ) {
  46724. const data = flatten( v, this.size, 16 );
  46725. gl.uniformMatrix4fv( this.addr, false, data );
  46726. }
  46727. // Array of integer / boolean
  46728. function setValueV1iArray( gl, v ) {
  46729. gl.uniform1iv( this.addr, v );
  46730. }
  46731. // Array of integer / boolean vectors (from flat array)
  46732. function setValueV2iArray( gl, v ) {
  46733. gl.uniform2iv( this.addr, v );
  46734. }
  46735. function setValueV3iArray( gl, v ) {
  46736. gl.uniform3iv( this.addr, v );
  46737. }
  46738. function setValueV4iArray( gl, v ) {
  46739. gl.uniform4iv( this.addr, v );
  46740. }
  46741. // Array of unsigned integer
  46742. function setValueV1uiArray( gl, v ) {
  46743. gl.uniform1uiv( this.addr, v );
  46744. }
  46745. // Array of unsigned integer vectors (from flat array)
  46746. function setValueV2uiArray( gl, v ) {
  46747. gl.uniform2uiv( this.addr, v );
  46748. }
  46749. function setValueV3uiArray( gl, v ) {
  46750. gl.uniform3uiv( this.addr, v );
  46751. }
  46752. function setValueV4uiArray( gl, v ) {
  46753. gl.uniform4uiv( this.addr, v );
  46754. }
  46755. // Array of textures (2D / 3D / Cube / 2DArray)
  46756. function setValueT1Array( gl, v, textures ) {
  46757. const cache = this.cache;
  46758. const n = v.length;
  46759. const units = allocTexUnits( textures, n );
  46760. if ( ! arraysEqual( cache, units ) ) {
  46761. gl.uniform1iv( this.addr, units );
  46762. copyArray( cache, units );
  46763. }
  46764. let emptyTexture2D;
  46765. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46766. emptyTexture2D = emptyShadowTexture;
  46767. } else {
  46768. emptyTexture2D = emptyTexture;
  46769. }
  46770. for ( let i = 0; i !== n; ++ i ) {
  46771. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46772. }
  46773. }
  46774. function setValueT3DArray( gl, v, textures ) {
  46775. const cache = this.cache;
  46776. const n = v.length;
  46777. const units = allocTexUnits( textures, n );
  46778. if ( ! arraysEqual( cache, units ) ) {
  46779. gl.uniform1iv( this.addr, units );
  46780. copyArray( cache, units );
  46781. }
  46782. for ( let i = 0; i !== n; ++ i ) {
  46783. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46784. }
  46785. }
  46786. function setValueT6Array( gl, v, textures ) {
  46787. const cache = this.cache;
  46788. const n = v.length;
  46789. const units = allocTexUnits( textures, n );
  46790. if ( ! arraysEqual( cache, units ) ) {
  46791. gl.uniform1iv( this.addr, units );
  46792. copyArray( cache, units );
  46793. }
  46794. for ( let i = 0; i !== n; ++ i ) {
  46795. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46796. }
  46797. }
  46798. function setValueT2DArrayArray( gl, v, textures ) {
  46799. const cache = this.cache;
  46800. const n = v.length;
  46801. const units = allocTexUnits( textures, n );
  46802. if ( ! arraysEqual( cache, units ) ) {
  46803. gl.uniform1iv( this.addr, units );
  46804. copyArray( cache, units );
  46805. }
  46806. for ( let i = 0; i !== n; ++ i ) {
  46807. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46808. }
  46809. }
  46810. // Helper to pick the right setter for a pure (bottom-level) array
  46811. function getPureArraySetter( type ) {
  46812. switch ( type ) {
  46813. case 0x1406: return setValueV1fArray; // FLOAT
  46814. case 0x8b50: return setValueV2fArray; // _VEC2
  46815. case 0x8b51: return setValueV3fArray; // _VEC3
  46816. case 0x8b52: return setValueV4fArray; // _VEC4
  46817. case 0x8b5a: return setValueM2Array; // _MAT2
  46818. case 0x8b5b: return setValueM3Array; // _MAT3
  46819. case 0x8b5c: return setValueM4Array; // _MAT4
  46820. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46821. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46822. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46823. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46824. case 0x1405: return setValueV1uiArray; // UINT
  46825. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46826. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46827. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46828. case 0x8b5e: // SAMPLER_2D
  46829. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46830. case 0x8dca: // INT_SAMPLER_2D
  46831. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46832. case 0x8b62: // SAMPLER_2D_SHADOW
  46833. return setValueT1Array;
  46834. case 0x8b5f: // SAMPLER_3D
  46835. case 0x8dcb: // INT_SAMPLER_3D
  46836. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46837. return setValueT3DArray;
  46838. case 0x8b60: // SAMPLER_CUBE
  46839. case 0x8dcc: // INT_SAMPLER_CUBE
  46840. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46841. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46842. return setValueT6Array;
  46843. case 0x8dc1: // SAMPLER_2D_ARRAY
  46844. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46845. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46846. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46847. return setValueT2DArrayArray;
  46848. }
  46849. }
  46850. // --- Uniform Classes ---
  46851. class SingleUniform {
  46852. constructor( id, activeInfo, addr ) {
  46853. this.id = id;
  46854. this.addr = addr;
  46855. this.cache = [];
  46856. this.type = activeInfo.type;
  46857. this.setValue = getSingularSetter( activeInfo.type );
  46858. // this.path = activeInfo.name; // DEBUG
  46859. }
  46860. }
  46861. class PureArrayUniform {
  46862. constructor( id, activeInfo, addr ) {
  46863. this.id = id;
  46864. this.addr = addr;
  46865. this.cache = [];
  46866. this.type = activeInfo.type;
  46867. this.size = activeInfo.size;
  46868. this.setValue = getPureArraySetter( activeInfo.type );
  46869. // this.path = activeInfo.name; // DEBUG
  46870. }
  46871. }
  46872. class StructuredUniform {
  46873. constructor( id ) {
  46874. this.id = id;
  46875. this.seq = [];
  46876. this.map = {};
  46877. }
  46878. setValue( gl, value, textures ) {
  46879. const seq = this.seq;
  46880. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46881. const u = seq[ i ];
  46882. u.setValue( gl, value[ u.id ], textures );
  46883. }
  46884. }
  46885. }
  46886. // --- Top-level ---
  46887. // Parser - builds up the property tree from the path strings
  46888. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46889. // extracts
  46890. // - the identifier (member name or array index)
  46891. // - followed by an optional right bracket (found when array index)
  46892. // - followed by an optional left bracket or dot (type of subscript)
  46893. //
  46894. // Note: These portions can be read in a non-overlapping fashion and
  46895. // allow straightforward parsing of the hierarchy that WebGL encodes
  46896. // in the uniform names.
  46897. function addUniform( container, uniformObject ) {
  46898. container.seq.push( uniformObject );
  46899. container.map[ uniformObject.id ] = uniformObject;
  46900. }
  46901. function parseUniform( activeInfo, addr, container ) {
  46902. const path = activeInfo.name,
  46903. pathLength = path.length;
  46904. // reset RegExp object, because of the early exit of a previous run
  46905. RePathPart.lastIndex = 0;
  46906. while ( true ) {
  46907. const match = RePathPart.exec( path ),
  46908. matchEnd = RePathPart.lastIndex;
  46909. let id = match[ 1 ];
  46910. const idIsIndex = match[ 2 ] === ']',
  46911. subscript = match[ 3 ];
  46912. if ( idIsIndex ) id = id | 0; // convert to integer
  46913. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46914. // bare name or "pure" bottom-level array "[0]" suffix
  46915. addUniform( container, subscript === undefined ?
  46916. new SingleUniform( id, activeInfo, addr ) :
  46917. new PureArrayUniform( id, activeInfo, addr ) );
  46918. break;
  46919. } else {
  46920. // step into inner node / create it in case it doesn't exist
  46921. const map = container.map;
  46922. let next = map[ id ];
  46923. if ( next === undefined ) {
  46924. next = new StructuredUniform( id );
  46925. addUniform( container, next );
  46926. }
  46927. container = next;
  46928. }
  46929. }
  46930. }
  46931. // Root Container
  46932. class WebGLUniforms {
  46933. constructor( gl, program ) {
  46934. this.seq = [];
  46935. this.map = {};
  46936. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46937. for ( let i = 0; i < n; ++ i ) {
  46938. const info = gl.getActiveUniform( program, i ),
  46939. addr = gl.getUniformLocation( program, info.name );
  46940. parseUniform( info, addr, this );
  46941. }
  46942. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46943. const shadowSamplers = [];
  46944. const otherUniforms = [];
  46945. for ( const u of this.seq ) {
  46946. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46947. shadowSamplers.push( u );
  46948. } else {
  46949. otherUniforms.push( u );
  46950. }
  46951. }
  46952. if ( shadowSamplers.length > 0 ) {
  46953. this.seq = shadowSamplers.concat( otherUniforms );
  46954. }
  46955. }
  46956. setValue( gl, name, value, textures ) {
  46957. const u = this.map[ name ];
  46958. if ( u !== undefined ) u.setValue( gl, value, textures );
  46959. }
  46960. setOptional( gl, object, name ) {
  46961. const v = object[ name ];
  46962. if ( v !== undefined ) this.setValue( gl, name, v );
  46963. }
  46964. static upload( gl, seq, values, textures ) {
  46965. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46966. const u = seq[ i ],
  46967. v = values[ u.id ];
  46968. if ( v.needsUpdate !== false ) {
  46969. // note: always updating when .needsUpdate is undefined
  46970. u.setValue( gl, v.value, textures );
  46971. }
  46972. }
  46973. }
  46974. static seqWithValue( seq, values ) {
  46975. const r = [];
  46976. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46977. const u = seq[ i ];
  46978. if ( u.id in values ) r.push( u );
  46979. }
  46980. return r;
  46981. }
  46982. }
  46983. function WebGLShader( gl, type, string ) {
  46984. const shader = gl.createShader( type );
  46985. gl.shaderSource( shader, string );
  46986. gl.compileShader( shader );
  46987. return shader;
  46988. }
  46989. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46990. const COMPLETION_STATUS_KHR = 0x91B1;
  46991. let programIdCount = 0;
  46992. function handleSource( string, errorLine ) {
  46993. const lines = string.split( '\n' );
  46994. const lines2 = [];
  46995. const from = Math.max( errorLine - 6, 0 );
  46996. const to = Math.min( errorLine + 6, lines.length );
  46997. for ( let i = from; i < to; i ++ ) {
  46998. const line = i + 1;
  46999. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  47000. }
  47001. return lines2.join( '\n' );
  47002. }
  47003. const _m0 = /*@__PURE__*/ new Matrix3();
  47004. function getEncodingComponents( colorSpace ) {
  47005. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  47006. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  47007. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  47008. case LinearTransfer:
  47009. return [ encodingMatrix, 'LinearTransferOETF' ];
  47010. case SRGBTransfer:
  47011. return [ encodingMatrix, 'sRGBTransferOETF' ];
  47012. default:
  47013. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  47014. return [ encodingMatrix, 'LinearTransferOETF' ];
  47015. }
  47016. }
  47017. function getShaderErrors( gl, shader, type ) {
  47018. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  47019. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  47020. const errors = shaderInfoLog.trim();
  47021. if ( status && errors === '' ) return '';
  47022. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  47023. if ( errorMatches ) {
  47024. // --enable-privileged-webgl-extension
  47025. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  47026. const errorLine = parseInt( errorMatches[ 1 ] );
  47027. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  47028. } else {
  47029. return errors;
  47030. }
  47031. }
  47032. function getTexelEncodingFunction( functionName, colorSpace ) {
  47033. const components = getEncodingComponents( colorSpace );
  47034. return [
  47035. `vec4 ${functionName}( vec4 value ) {`,
  47036. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  47037. '}',
  47038. ].join( '\n' );
  47039. }
  47040. const toneMappingFunctions = {
  47041. [ LinearToneMapping ]: 'Linear',
  47042. [ ReinhardToneMapping ]: 'Reinhard',
  47043. [ CineonToneMapping ]: 'Cineon',
  47044. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  47045. [ AgXToneMapping ]: 'AgX',
  47046. [ NeutralToneMapping ]: 'Neutral',
  47047. [ CustomToneMapping ]: 'Custom'
  47048. };
  47049. function getToneMappingFunction( functionName, toneMapping ) {
  47050. const toneMappingName = toneMappingFunctions[ toneMapping ];
  47051. if ( toneMappingName === undefined ) {
  47052. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  47053. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  47054. }
  47055. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  47056. }
  47057. const _v0 = /*@__PURE__*/ new Vector3();
  47058. function getLuminanceFunction() {
  47059. ColorManagement.getLuminanceCoefficients( _v0 );
  47060. const r = _v0.x.toFixed( 4 );
  47061. const g = _v0.y.toFixed( 4 );
  47062. const b = _v0.z.toFixed( 4 );
  47063. return [
  47064. 'float luminance( const in vec3 rgb ) {',
  47065. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  47066. ' return dot( weights, rgb );',
  47067. '}'
  47068. ].join( '\n' );
  47069. }
  47070. function generateVertexExtensions( parameters ) {
  47071. const chunks = [
  47072. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  47073. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  47074. ];
  47075. return chunks.filter( filterEmptyLine ).join( '\n' );
  47076. }
  47077. function generateDefines( defines ) {
  47078. const chunks = [];
  47079. for ( const name in defines ) {
  47080. const value = defines[ name ];
  47081. if ( value === false ) continue;
  47082. chunks.push( '#define ' + name + ' ' + value );
  47083. }
  47084. return chunks.join( '\n' );
  47085. }
  47086. function fetchAttributeLocations( gl, program ) {
  47087. const attributes = {};
  47088. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  47089. for ( let i = 0; i < n; i ++ ) {
  47090. const info = gl.getActiveAttrib( program, i );
  47091. const name = info.name;
  47092. let locationSize = 1;
  47093. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  47094. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  47095. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  47096. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  47097. attributes[ name ] = {
  47098. type: info.type,
  47099. location: gl.getAttribLocation( program, name ),
  47100. locationSize: locationSize
  47101. };
  47102. }
  47103. return attributes;
  47104. }
  47105. function filterEmptyLine( string ) {
  47106. return string !== '';
  47107. }
  47108. function replaceLightNums( string, parameters ) {
  47109. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  47110. return string
  47111. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  47112. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  47113. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  47114. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  47115. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  47116. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  47117. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  47118. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  47119. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  47120. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  47121. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  47122. }
  47123. function replaceClippingPlaneNums( string, parameters ) {
  47124. return string
  47125. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  47126. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  47127. }
  47128. // Resolve Includes
  47129. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  47130. function resolveIncludes( string ) {
  47131. return string.replace( includePattern, includeReplacer );
  47132. }
  47133. const shaderChunkMap = new Map();
  47134. function includeReplacer( match, include ) {
  47135. let string = ShaderChunk[ include ];
  47136. if ( string === undefined ) {
  47137. const newInclude = shaderChunkMap.get( include );
  47138. if ( newInclude !== undefined ) {
  47139. string = ShaderChunk[ newInclude ];
  47140. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  47141. } else {
  47142. throw new Error( 'Can not resolve #include <' + include + '>' );
  47143. }
  47144. }
  47145. return resolveIncludes( string );
  47146. }
  47147. // Unroll Loops
  47148. 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;
  47149. function unrollLoops( string ) {
  47150. return string.replace( unrollLoopPattern, loopReplacer );
  47151. }
  47152. function loopReplacer( match, start, end, snippet ) {
  47153. let string = '';
  47154. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  47155. string += snippet
  47156. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  47157. .replace( /UNROLLED_LOOP_INDEX/g, i );
  47158. }
  47159. return string;
  47160. }
  47161. //
  47162. function generatePrecision( parameters ) {
  47163. let precisionstring = `precision ${parameters.precision} float;
  47164. precision ${parameters.precision} int;
  47165. precision ${parameters.precision} sampler2D;
  47166. precision ${parameters.precision} samplerCube;
  47167. precision ${parameters.precision} sampler3D;
  47168. precision ${parameters.precision} sampler2DArray;
  47169. precision ${parameters.precision} sampler2DShadow;
  47170. precision ${parameters.precision} samplerCubeShadow;
  47171. precision ${parameters.precision} sampler2DArrayShadow;
  47172. precision ${parameters.precision} isampler2D;
  47173. precision ${parameters.precision} isampler3D;
  47174. precision ${parameters.precision} isamplerCube;
  47175. precision ${parameters.precision} isampler2DArray;
  47176. precision ${parameters.precision} usampler2D;
  47177. precision ${parameters.precision} usampler3D;
  47178. precision ${parameters.precision} usamplerCube;
  47179. precision ${parameters.precision} usampler2DArray;
  47180. `;
  47181. if ( parameters.precision === 'highp' ) {
  47182. precisionstring += '\n#define HIGH_PRECISION';
  47183. } else if ( parameters.precision === 'mediump' ) {
  47184. precisionstring += '\n#define MEDIUM_PRECISION';
  47185. } else if ( parameters.precision === 'lowp' ) {
  47186. precisionstring += '\n#define LOW_PRECISION';
  47187. }
  47188. return precisionstring;
  47189. }
  47190. const shadowMapTypeDefines = {
  47191. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  47192. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  47193. };
  47194. function generateShadowMapTypeDefine( parameters ) {
  47195. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  47196. }
  47197. const envMapTypeDefines = {
  47198. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  47199. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  47200. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  47201. };
  47202. function generateEnvMapTypeDefine( parameters ) {
  47203. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  47204. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  47205. }
  47206. const envMapModeDefines = {
  47207. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  47208. };
  47209. function generateEnvMapModeDefine( parameters ) {
  47210. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  47211. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  47212. }
  47213. const envMapBlendingDefines = {
  47214. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  47215. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  47216. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  47217. };
  47218. function generateEnvMapBlendingDefine( parameters ) {
  47219. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  47220. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  47221. }
  47222. function generateCubeUVSize( parameters ) {
  47223. const imageHeight = parameters.envMapCubeUVHeight;
  47224. if ( imageHeight === null ) return null;
  47225. const maxMip = Math.log2( imageHeight ) - 2;
  47226. const texelHeight = 1.0 / imageHeight;
  47227. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  47228. return { texelWidth, texelHeight, maxMip };
  47229. }
  47230. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  47231. // TODO Send this event to Three.js DevTools
  47232. // log( 'WebGLProgram', cacheKey );
  47233. const gl = renderer.getContext();
  47234. const defines = parameters.defines;
  47235. let vertexShader = parameters.vertexShader;
  47236. let fragmentShader = parameters.fragmentShader;
  47237. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  47238. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  47239. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  47240. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  47241. const envMapCubeUVSize = generateCubeUVSize( parameters );
  47242. const customVertexExtensions = generateVertexExtensions( parameters );
  47243. const customDefines = generateDefines( defines );
  47244. const program = gl.createProgram();
  47245. let prefixVertex, prefixFragment;
  47246. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  47247. if ( parameters.isRawShaderMaterial ) {
  47248. prefixVertex = [
  47249. '#define SHADER_TYPE ' + parameters.shaderType,
  47250. '#define SHADER_NAME ' + parameters.shaderName,
  47251. customDefines
  47252. ].filter( filterEmptyLine ).join( '\n' );
  47253. if ( prefixVertex.length > 0 ) {
  47254. prefixVertex += '\n';
  47255. }
  47256. prefixFragment = [
  47257. '#define SHADER_TYPE ' + parameters.shaderType,
  47258. '#define SHADER_NAME ' + parameters.shaderName,
  47259. customDefines
  47260. ].filter( filterEmptyLine ).join( '\n' );
  47261. if ( prefixFragment.length > 0 ) {
  47262. prefixFragment += '\n';
  47263. }
  47264. } else {
  47265. prefixVertex = [
  47266. generatePrecision( parameters ),
  47267. '#define SHADER_TYPE ' + parameters.shaderType,
  47268. '#define SHADER_NAME ' + parameters.shaderName,
  47269. customDefines,
  47270. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  47271. parameters.batching ? '#define USE_BATCHING' : '',
  47272. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  47273. parameters.instancing ? '#define USE_INSTANCING' : '',
  47274. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  47275. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  47276. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47277. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47278. parameters.map ? '#define USE_MAP' : '',
  47279. parameters.envMap ? '#define USE_ENVMAP' : '',
  47280. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47281. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47282. parameters.aoMap ? '#define USE_AOMAP' : '',
  47283. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47284. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47285. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47286. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47287. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  47288. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47289. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47290. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47291. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47292. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47293. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47294. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47295. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47296. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47297. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47298. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47299. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47300. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47301. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47302. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47303. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47304. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47305. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47306. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47307. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47308. //
  47309. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  47310. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  47311. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  47312. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  47313. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  47314. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  47315. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  47316. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  47317. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  47318. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  47319. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  47320. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  47321. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  47322. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  47323. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  47324. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  47325. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  47326. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  47327. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  47328. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  47329. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  47330. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  47331. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  47332. //
  47333. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47334. parameters.vertexColors ? '#define USE_COLOR' : '',
  47335. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  47336. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47337. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47338. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47339. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47340. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47341. parameters.skinning ? '#define USE_SKINNING' : '',
  47342. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  47343. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  47344. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  47345. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  47346. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  47347. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47348. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47349. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47350. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47351. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  47352. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47353. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47354. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47355. 'uniform mat4 modelMatrix;',
  47356. 'uniform mat4 modelViewMatrix;',
  47357. 'uniform mat4 projectionMatrix;',
  47358. 'uniform mat4 viewMatrix;',
  47359. 'uniform mat3 normalMatrix;',
  47360. 'uniform vec3 cameraPosition;',
  47361. 'uniform bool isOrthographic;',
  47362. '#ifdef USE_INSTANCING',
  47363. ' attribute mat4 instanceMatrix;',
  47364. '#endif',
  47365. '#ifdef USE_INSTANCING_COLOR',
  47366. ' attribute vec3 instanceColor;',
  47367. '#endif',
  47368. '#ifdef USE_INSTANCING_MORPH',
  47369. ' uniform sampler2D morphTexture;',
  47370. '#endif',
  47371. 'attribute vec3 position;',
  47372. 'attribute vec3 normal;',
  47373. 'attribute vec2 uv;',
  47374. '#ifdef USE_UV1',
  47375. ' attribute vec2 uv1;',
  47376. '#endif',
  47377. '#ifdef USE_UV2',
  47378. ' attribute vec2 uv2;',
  47379. '#endif',
  47380. '#ifdef USE_UV3',
  47381. ' attribute vec2 uv3;',
  47382. '#endif',
  47383. '#ifdef USE_TANGENT',
  47384. ' attribute vec4 tangent;',
  47385. '#endif',
  47386. '#if defined( USE_COLOR_ALPHA )',
  47387. ' attribute vec4 color;',
  47388. '#elif defined( USE_COLOR )',
  47389. ' attribute vec3 color;',
  47390. '#endif',
  47391. '#ifdef USE_SKINNING',
  47392. ' attribute vec4 skinIndex;',
  47393. ' attribute vec4 skinWeight;',
  47394. '#endif',
  47395. '\n'
  47396. ].filter( filterEmptyLine ).join( '\n' );
  47397. prefixFragment = [
  47398. generatePrecision( parameters ),
  47399. '#define SHADER_TYPE ' + parameters.shaderType,
  47400. '#define SHADER_NAME ' + parameters.shaderName,
  47401. customDefines,
  47402. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47403. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47404. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  47405. parameters.map ? '#define USE_MAP' : '',
  47406. parameters.matcap ? '#define USE_MATCAP' : '',
  47407. parameters.envMap ? '#define USE_ENVMAP' : '',
  47408. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  47409. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47410. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  47411. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  47412. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  47413. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  47414. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47415. parameters.aoMap ? '#define USE_AOMAP' : '',
  47416. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47417. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47418. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47419. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47420. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47421. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47422. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47423. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  47424. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47425. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47426. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47427. parameters.dispersion ? '#define USE_DISPERSION' : '',
  47428. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  47429. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47430. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47431. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47432. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47433. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47434. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47435. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47436. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47437. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  47438. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47439. parameters.sheen ? '#define USE_SHEEN' : '',
  47440. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47441. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47442. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47443. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47444. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47445. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47446. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  47447. parameters.vertexAlphas || parameters.batchingColor ? '#define USE_COLOR_ALPHA' : '',
  47448. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47449. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47450. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47451. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47452. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  47453. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47454. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47455. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47456. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47457. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47458. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  47459. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47460. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  47461. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  47462. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47463. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47464. 'uniform mat4 viewMatrix;',
  47465. 'uniform vec3 cameraPosition;',
  47466. 'uniform bool isOrthographic;',
  47467. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  47468. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  47469. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  47470. parameters.dithering ? '#define DITHERING' : '',
  47471. parameters.opaque ? '#define OPAQUE' : '',
  47472. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  47473. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  47474. getLuminanceFunction(),
  47475. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  47476. '\n'
  47477. ].filter( filterEmptyLine ).join( '\n' );
  47478. }
  47479. vertexShader = resolveIncludes( vertexShader );
  47480. vertexShader = replaceLightNums( vertexShader, parameters );
  47481. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  47482. fragmentShader = resolveIncludes( fragmentShader );
  47483. fragmentShader = replaceLightNums( fragmentShader, parameters );
  47484. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  47485. vertexShader = unrollLoops( vertexShader );
  47486. fragmentShader = unrollLoops( fragmentShader );
  47487. if ( parameters.isRawShaderMaterial !== true ) {
  47488. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  47489. versionString = '#version 300 es\n';
  47490. prefixVertex = [
  47491. customVertexExtensions,
  47492. '#define attribute in',
  47493. '#define varying out',
  47494. '#define texture2D texture'
  47495. ].join( '\n' ) + '\n' + prefixVertex;
  47496. prefixFragment = [
  47497. '#define varying in',
  47498. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  47499. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  47500. '#define gl_FragDepthEXT gl_FragDepth',
  47501. '#define texture2D texture',
  47502. '#define textureCube texture',
  47503. '#define texture2DProj textureProj',
  47504. '#define texture2DLodEXT textureLod',
  47505. '#define texture2DProjLodEXT textureProjLod',
  47506. '#define textureCubeLodEXT textureLod',
  47507. '#define texture2DGradEXT textureGrad',
  47508. '#define texture2DProjGradEXT textureProjGrad',
  47509. '#define textureCubeGradEXT textureGrad'
  47510. ].join( '\n' ) + '\n' + prefixFragment;
  47511. }
  47512. const vertexGlsl = versionString + prefixVertex + vertexShader;
  47513. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  47514. // log( '*VERTEX*', vertexGlsl );
  47515. // log( '*FRAGMENT*', fragmentGlsl );
  47516. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  47517. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  47518. gl.attachShader( program, glVertexShader );
  47519. gl.attachShader( program, glFragmentShader );
  47520. // Force a particular attribute to index 0.
  47521. if ( parameters.index0AttributeName !== undefined ) {
  47522. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  47523. } else if ( parameters.morphTargets === true ) {
  47524. // programs with morphTargets displace position out of attribute 0
  47525. gl.bindAttribLocation( program, 0, 'position' );
  47526. }
  47527. gl.linkProgram( program );
  47528. function onFirstUse( self ) {
  47529. // check for link errors
  47530. if ( renderer.debug.checkShaderErrors ) {
  47531. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  47532. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  47533. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  47534. const programLog = programInfoLog.trim();
  47535. const vertexLog = vertexShaderInfoLog.trim();
  47536. const fragmentLog = fragmentShaderInfoLog.trim();
  47537. let runnable = true;
  47538. let haveDiagnostics = true;
  47539. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  47540. runnable = false;
  47541. if ( typeof renderer.debug.onShaderError === 'function' ) {
  47542. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  47543. } else {
  47544. // default error reporting
  47545. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  47546. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  47547. error(
  47548. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47549. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  47550. 'Material Name: ' + self.name + '\n' +
  47551. 'Material Type: ' + self.type + '\n\n' +
  47552. 'Program Info Log: ' + programLog + '\n' +
  47553. vertexErrors + '\n' +
  47554. fragmentErrors
  47555. );
  47556. }
  47557. } else if ( programLog !== '' ) {
  47558. warn( 'WebGLProgram: Program Info Log:', programLog );
  47559. } else if ( vertexLog === '' || fragmentLog === '' ) {
  47560. haveDiagnostics = false;
  47561. }
  47562. if ( haveDiagnostics ) {
  47563. self.diagnostics = {
  47564. runnable: runnable,
  47565. programLog: programLog,
  47566. vertexShader: {
  47567. log: vertexLog,
  47568. prefix: prefixVertex
  47569. },
  47570. fragmentShader: {
  47571. log: fragmentLog,
  47572. prefix: prefixFragment
  47573. }
  47574. };
  47575. }
  47576. }
  47577. // Clean up
  47578. // Crashes in iOS9 and iOS10. #18402
  47579. // gl.detachShader( program, glVertexShader );
  47580. // gl.detachShader( program, glFragmentShader );
  47581. gl.deleteShader( glVertexShader );
  47582. gl.deleteShader( glFragmentShader );
  47583. cachedUniforms = new WebGLUniforms( gl, program );
  47584. cachedAttributes = fetchAttributeLocations( gl, program );
  47585. }
  47586. // set up caching for uniform locations
  47587. let cachedUniforms;
  47588. this.getUniforms = function () {
  47589. if ( cachedUniforms === undefined ) {
  47590. // Populates cachedUniforms and cachedAttributes
  47591. onFirstUse( this );
  47592. }
  47593. return cachedUniforms;
  47594. };
  47595. // set up caching for attribute locations
  47596. let cachedAttributes;
  47597. this.getAttributes = function () {
  47598. if ( cachedAttributes === undefined ) {
  47599. // Populates cachedAttributes and cachedUniforms
  47600. onFirstUse( this );
  47601. }
  47602. return cachedAttributes;
  47603. };
  47604. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  47605. // flag the program as ready immediately. It may cause a stall when it's first used.
  47606. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  47607. this.isReady = function () {
  47608. if ( programReady === false ) {
  47609. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  47610. }
  47611. return programReady;
  47612. };
  47613. // free resource
  47614. this.destroy = function () {
  47615. bindingStates.releaseStatesOfProgram( this );
  47616. gl.deleteProgram( program );
  47617. this.program = undefined;
  47618. };
  47619. //
  47620. this.type = parameters.shaderType;
  47621. this.name = parameters.shaderName;
  47622. this.id = programIdCount ++;
  47623. this.cacheKey = cacheKey;
  47624. this.usedTimes = 1;
  47625. this.program = program;
  47626. this.vertexShader = glVertexShader;
  47627. this.fragmentShader = glFragmentShader;
  47628. return this;
  47629. }
  47630. let _id = 0;
  47631. class WebGLShaderCache {
  47632. constructor() {
  47633. this.shaderCache = new Map();
  47634. this.materialCache = new Map();
  47635. }
  47636. update( material ) {
  47637. const vertexShader = material.vertexShader;
  47638. const fragmentShader = material.fragmentShader;
  47639. const vertexShaderStage = this._getShaderStage( vertexShader );
  47640. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47641. const materialShaders = this._getShaderCacheForMaterial( material );
  47642. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47643. materialShaders.add( vertexShaderStage );
  47644. vertexShaderStage.usedTimes ++;
  47645. }
  47646. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47647. materialShaders.add( fragmentShaderStage );
  47648. fragmentShaderStage.usedTimes ++;
  47649. }
  47650. return this;
  47651. }
  47652. remove( material ) {
  47653. const materialShaders = this.materialCache.get( material );
  47654. for ( const shaderStage of materialShaders ) {
  47655. shaderStage.usedTimes --;
  47656. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47657. }
  47658. this.materialCache.delete( material );
  47659. return this;
  47660. }
  47661. getVertexShaderID( material ) {
  47662. return this._getShaderStage( material.vertexShader ).id;
  47663. }
  47664. getFragmentShaderID( material ) {
  47665. return this._getShaderStage( material.fragmentShader ).id;
  47666. }
  47667. dispose() {
  47668. this.shaderCache.clear();
  47669. this.materialCache.clear();
  47670. }
  47671. _getShaderCacheForMaterial( material ) {
  47672. const cache = this.materialCache;
  47673. let set = cache.get( material );
  47674. if ( set === undefined ) {
  47675. set = new Set();
  47676. cache.set( material, set );
  47677. }
  47678. return set;
  47679. }
  47680. _getShaderStage( code ) {
  47681. const cache = this.shaderCache;
  47682. let stage = cache.get( code );
  47683. if ( stage === undefined ) {
  47684. stage = new WebGLShaderStage( code );
  47685. cache.set( code, stage );
  47686. }
  47687. return stage;
  47688. }
  47689. }
  47690. class WebGLShaderStage {
  47691. constructor( code ) {
  47692. this.id = _id ++;
  47693. this.code = code;
  47694. this.usedTimes = 0;
  47695. }
  47696. }
  47697. function WebGLPrograms( renderer, environments, extensions, capabilities, bindingStates, clipping ) {
  47698. const _programLayers = new Layers();
  47699. const _customShaders = new WebGLShaderCache();
  47700. const _activeChannels = new Set();
  47701. const programs = [];
  47702. const programsMap = new Map();
  47703. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47704. let precision = capabilities.precision;
  47705. const shaderIDs = {
  47706. MeshDepthMaterial: 'depth',
  47707. MeshDistanceMaterial: 'distance',
  47708. MeshNormalMaterial: 'normal',
  47709. MeshBasicMaterial: 'basic',
  47710. MeshLambertMaterial: 'lambert',
  47711. MeshPhongMaterial: 'phong',
  47712. MeshToonMaterial: 'toon',
  47713. MeshStandardMaterial: 'physical',
  47714. MeshPhysicalMaterial: 'physical',
  47715. MeshMatcapMaterial: 'matcap',
  47716. LineBasicMaterial: 'basic',
  47717. LineDashedMaterial: 'dashed',
  47718. PointsMaterial: 'points',
  47719. ShadowMaterial: 'shadow',
  47720. SpriteMaterial: 'sprite'
  47721. };
  47722. function getChannel( value ) {
  47723. _activeChannels.add( value );
  47724. if ( value === 0 ) return 'uv';
  47725. return `uv${ value }`;
  47726. }
  47727. function getParameters( material, lights, shadows, scene, object ) {
  47728. const fog = scene.fog;
  47729. const geometry = object.geometry;
  47730. const environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null;
  47731. const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap );
  47732. const envMap = environments.get( material.envMap || environment, usePMREM );
  47733. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47734. const shaderID = shaderIDs[ material.type ];
  47735. // heuristics to create shader parameters according to lights in the scene
  47736. // (not to blow over maxLights budget)
  47737. if ( material.precision !== null ) {
  47738. precision = capabilities.getMaxPrecision( material.precision );
  47739. if ( precision !== material.precision ) {
  47740. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47741. }
  47742. }
  47743. //
  47744. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47745. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47746. let morphTextureStride = 0;
  47747. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47748. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47749. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47750. //
  47751. let vertexShader, fragmentShader;
  47752. let customVertexShaderID, customFragmentShaderID;
  47753. if ( shaderID ) {
  47754. const shader = ShaderLib[ shaderID ];
  47755. vertexShader = shader.vertexShader;
  47756. fragmentShader = shader.fragmentShader;
  47757. } else {
  47758. vertexShader = material.vertexShader;
  47759. fragmentShader = material.fragmentShader;
  47760. _customShaders.update( material );
  47761. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47762. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47763. }
  47764. const currentRenderTarget = renderer.getRenderTarget();
  47765. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47766. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47767. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47768. const HAS_MAP = !! material.map;
  47769. const HAS_MATCAP = !! material.matcap;
  47770. const HAS_ENVMAP = !! envMap;
  47771. const HAS_AOMAP = !! material.aoMap;
  47772. const HAS_LIGHTMAP = !! material.lightMap;
  47773. const HAS_BUMPMAP = !! material.bumpMap;
  47774. const HAS_NORMALMAP = !! material.normalMap;
  47775. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47776. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47777. const HAS_METALNESSMAP = !! material.metalnessMap;
  47778. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47779. const HAS_ANISOTROPY = material.anisotropy > 0;
  47780. const HAS_CLEARCOAT = material.clearcoat > 0;
  47781. const HAS_DISPERSION = material.dispersion > 0;
  47782. const HAS_IRIDESCENCE = material.iridescence > 0;
  47783. const HAS_SHEEN = material.sheen > 0;
  47784. const HAS_TRANSMISSION = material.transmission > 0;
  47785. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47786. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47787. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47788. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47789. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47790. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47791. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47792. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47793. const HAS_SPECULARMAP = !! material.specularMap;
  47794. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47795. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47796. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47797. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47798. const HAS_GRADIENTMAP = !! material.gradientMap;
  47799. const HAS_ALPHAMAP = !! material.alphaMap;
  47800. const HAS_ALPHATEST = material.alphaTest > 0;
  47801. const HAS_ALPHAHASH = !! material.alphaHash;
  47802. const HAS_EXTENSIONS = !! material.extensions;
  47803. let toneMapping = NoToneMapping;
  47804. if ( material.toneMapped ) {
  47805. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47806. toneMapping = renderer.toneMapping;
  47807. }
  47808. }
  47809. const parameters = {
  47810. shaderID: shaderID,
  47811. shaderType: material.type,
  47812. shaderName: material.name,
  47813. vertexShader: vertexShader,
  47814. fragmentShader: fragmentShader,
  47815. defines: material.defines,
  47816. customVertexShaderID: customVertexShaderID,
  47817. customFragmentShaderID: customFragmentShaderID,
  47818. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47819. glslVersion: material.glslVersion,
  47820. precision: precision,
  47821. batching: IS_BATCHEDMESH,
  47822. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47823. instancing: IS_INSTANCEDMESH,
  47824. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47825. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47826. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47827. alphaToCoverage: !! material.alphaToCoverage,
  47828. map: HAS_MAP,
  47829. matcap: HAS_MATCAP,
  47830. envMap: HAS_ENVMAP,
  47831. envMapMode: HAS_ENVMAP && envMap.mapping,
  47832. envMapCubeUVHeight: envMapCubeUVHeight,
  47833. aoMap: HAS_AOMAP,
  47834. lightMap: HAS_LIGHTMAP,
  47835. bumpMap: HAS_BUMPMAP,
  47836. normalMap: HAS_NORMALMAP,
  47837. displacementMap: HAS_DISPLACEMENTMAP,
  47838. emissiveMap: HAS_EMISSIVEMAP,
  47839. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47840. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47841. metalnessMap: HAS_METALNESSMAP,
  47842. roughnessMap: HAS_ROUGHNESSMAP,
  47843. anisotropy: HAS_ANISOTROPY,
  47844. anisotropyMap: HAS_ANISOTROPYMAP,
  47845. clearcoat: HAS_CLEARCOAT,
  47846. clearcoatMap: HAS_CLEARCOATMAP,
  47847. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47848. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47849. dispersion: HAS_DISPERSION,
  47850. iridescence: HAS_IRIDESCENCE,
  47851. iridescenceMap: HAS_IRIDESCENCEMAP,
  47852. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47853. sheen: HAS_SHEEN,
  47854. sheenColorMap: HAS_SHEEN_COLORMAP,
  47855. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47856. specularMap: HAS_SPECULARMAP,
  47857. specularColorMap: HAS_SPECULAR_COLORMAP,
  47858. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47859. transmission: HAS_TRANSMISSION,
  47860. transmissionMap: HAS_TRANSMISSIONMAP,
  47861. thicknessMap: HAS_THICKNESSMAP,
  47862. gradientMap: HAS_GRADIENTMAP,
  47863. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47864. alphaMap: HAS_ALPHAMAP,
  47865. alphaTest: HAS_ALPHATEST,
  47866. alphaHash: HAS_ALPHAHASH,
  47867. combine: material.combine,
  47868. //
  47869. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47870. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47871. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47872. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47873. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47874. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47875. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47876. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47877. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47878. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47879. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47880. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47881. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47882. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47883. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47884. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47885. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47886. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47887. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47888. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47889. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47890. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47891. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47892. //
  47893. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47894. vertexColors: material.vertexColors,
  47895. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47896. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47897. fog: !! fog,
  47898. useFog: material.fog === true,
  47899. fogExp2: ( !! fog && fog.isFogExp2 ),
  47900. flatShading: material.wireframe === false && (
  47901. material.flatShading === true ||
  47902. ( geometry.attributes.normal === undefined && HAS_NORMALMAP === false &&
  47903. ( material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isMeshPhysicalMaterial )
  47904. )
  47905. ),
  47906. sizeAttenuation: material.sizeAttenuation === true,
  47907. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47908. reversedDepthBuffer: reversedDepthBuffer,
  47909. skinning: object.isSkinnedMesh === true,
  47910. morphTargets: geometry.morphAttributes.position !== undefined,
  47911. morphNormals: geometry.morphAttributes.normal !== undefined,
  47912. morphColors: geometry.morphAttributes.color !== undefined,
  47913. morphTargetsCount: morphTargetsCount,
  47914. morphTextureStride: morphTextureStride,
  47915. numDirLights: lights.directional.length,
  47916. numPointLights: lights.point.length,
  47917. numSpotLights: lights.spot.length,
  47918. numSpotLightMaps: lights.spotLightMap.length,
  47919. numRectAreaLights: lights.rectArea.length,
  47920. numHemiLights: lights.hemi.length,
  47921. numDirLightShadows: lights.directionalShadowMap.length,
  47922. numPointLightShadows: lights.pointShadowMap.length,
  47923. numSpotLightShadows: lights.spotShadowMap.length,
  47924. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47925. numLightProbes: lights.numLightProbes,
  47926. numClippingPlanes: clipping.numPlanes,
  47927. numClipIntersection: clipping.numIntersection,
  47928. dithering: material.dithering,
  47929. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47930. shadowMapType: renderer.shadowMap.type,
  47931. toneMapping: toneMapping,
  47932. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47933. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47934. premultipliedAlpha: material.premultipliedAlpha,
  47935. doubleSided: material.side === DoubleSide,
  47936. flipSided: material.side === BackSide,
  47937. useDepthPacking: material.depthPacking >= 0,
  47938. depthPacking: material.depthPacking || 0,
  47939. index0AttributeName: material.index0AttributeName,
  47940. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47941. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47942. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47943. customProgramCacheKey: material.customProgramCacheKey()
  47944. };
  47945. // the usage of getChannel() determines the active texture channels for this shader
  47946. parameters.vertexUv1s = _activeChannels.has( 1 );
  47947. parameters.vertexUv2s = _activeChannels.has( 2 );
  47948. parameters.vertexUv3s = _activeChannels.has( 3 );
  47949. _activeChannels.clear();
  47950. return parameters;
  47951. }
  47952. function getProgramCacheKey( parameters ) {
  47953. const array = [];
  47954. if ( parameters.shaderID ) {
  47955. array.push( parameters.shaderID );
  47956. } else {
  47957. array.push( parameters.customVertexShaderID );
  47958. array.push( parameters.customFragmentShaderID );
  47959. }
  47960. if ( parameters.defines !== undefined ) {
  47961. for ( const name in parameters.defines ) {
  47962. array.push( name );
  47963. array.push( parameters.defines[ name ] );
  47964. }
  47965. }
  47966. if ( parameters.isRawShaderMaterial === false ) {
  47967. getProgramCacheKeyParameters( array, parameters );
  47968. getProgramCacheKeyBooleans( array, parameters );
  47969. array.push( renderer.outputColorSpace );
  47970. }
  47971. array.push( parameters.customProgramCacheKey );
  47972. return array.join();
  47973. }
  47974. function getProgramCacheKeyParameters( array, parameters ) {
  47975. array.push( parameters.precision );
  47976. array.push( parameters.outputColorSpace );
  47977. array.push( parameters.envMapMode );
  47978. array.push( parameters.envMapCubeUVHeight );
  47979. array.push( parameters.mapUv );
  47980. array.push( parameters.alphaMapUv );
  47981. array.push( parameters.lightMapUv );
  47982. array.push( parameters.aoMapUv );
  47983. array.push( parameters.bumpMapUv );
  47984. array.push( parameters.normalMapUv );
  47985. array.push( parameters.displacementMapUv );
  47986. array.push( parameters.emissiveMapUv );
  47987. array.push( parameters.metalnessMapUv );
  47988. array.push( parameters.roughnessMapUv );
  47989. array.push( parameters.anisotropyMapUv );
  47990. array.push( parameters.clearcoatMapUv );
  47991. array.push( parameters.clearcoatNormalMapUv );
  47992. array.push( parameters.clearcoatRoughnessMapUv );
  47993. array.push( parameters.iridescenceMapUv );
  47994. array.push( parameters.iridescenceThicknessMapUv );
  47995. array.push( parameters.sheenColorMapUv );
  47996. array.push( parameters.sheenRoughnessMapUv );
  47997. array.push( parameters.specularMapUv );
  47998. array.push( parameters.specularColorMapUv );
  47999. array.push( parameters.specularIntensityMapUv );
  48000. array.push( parameters.transmissionMapUv );
  48001. array.push( parameters.thicknessMapUv );
  48002. array.push( parameters.combine );
  48003. array.push( parameters.fogExp2 );
  48004. array.push( parameters.sizeAttenuation );
  48005. array.push( parameters.morphTargetsCount );
  48006. array.push( parameters.morphAttributeCount );
  48007. array.push( parameters.numDirLights );
  48008. array.push( parameters.numPointLights );
  48009. array.push( parameters.numSpotLights );
  48010. array.push( parameters.numSpotLightMaps );
  48011. array.push( parameters.numHemiLights );
  48012. array.push( parameters.numRectAreaLights );
  48013. array.push( parameters.numDirLightShadows );
  48014. array.push( parameters.numPointLightShadows );
  48015. array.push( parameters.numSpotLightShadows );
  48016. array.push( parameters.numSpotLightShadowsWithMaps );
  48017. array.push( parameters.numLightProbes );
  48018. array.push( parameters.shadowMapType );
  48019. array.push( parameters.toneMapping );
  48020. array.push( parameters.numClippingPlanes );
  48021. array.push( parameters.numClipIntersection );
  48022. array.push( parameters.depthPacking );
  48023. }
  48024. function getProgramCacheKeyBooleans( array, parameters ) {
  48025. _programLayers.disableAll();
  48026. if ( parameters.instancing )
  48027. _programLayers.enable( 0 );
  48028. if ( parameters.instancingColor )
  48029. _programLayers.enable( 1 );
  48030. if ( parameters.instancingMorph )
  48031. _programLayers.enable( 2 );
  48032. if ( parameters.matcap )
  48033. _programLayers.enable( 3 );
  48034. if ( parameters.envMap )
  48035. _programLayers.enable( 4 );
  48036. if ( parameters.normalMapObjectSpace )
  48037. _programLayers.enable( 5 );
  48038. if ( parameters.normalMapTangentSpace )
  48039. _programLayers.enable( 6 );
  48040. if ( parameters.clearcoat )
  48041. _programLayers.enable( 7 );
  48042. if ( parameters.iridescence )
  48043. _programLayers.enable( 8 );
  48044. if ( parameters.alphaTest )
  48045. _programLayers.enable( 9 );
  48046. if ( parameters.vertexColors )
  48047. _programLayers.enable( 10 );
  48048. if ( parameters.vertexAlphas )
  48049. _programLayers.enable( 11 );
  48050. if ( parameters.vertexUv1s )
  48051. _programLayers.enable( 12 );
  48052. if ( parameters.vertexUv2s )
  48053. _programLayers.enable( 13 );
  48054. if ( parameters.vertexUv3s )
  48055. _programLayers.enable( 14 );
  48056. if ( parameters.vertexTangents )
  48057. _programLayers.enable( 15 );
  48058. if ( parameters.anisotropy )
  48059. _programLayers.enable( 16 );
  48060. if ( parameters.alphaHash )
  48061. _programLayers.enable( 17 );
  48062. if ( parameters.batching )
  48063. _programLayers.enable( 18 );
  48064. if ( parameters.dispersion )
  48065. _programLayers.enable( 19 );
  48066. if ( parameters.batchingColor )
  48067. _programLayers.enable( 20 );
  48068. if ( parameters.gradientMap )
  48069. _programLayers.enable( 21 );
  48070. array.push( _programLayers.mask );
  48071. _programLayers.disableAll();
  48072. if ( parameters.fog )
  48073. _programLayers.enable( 0 );
  48074. if ( parameters.useFog )
  48075. _programLayers.enable( 1 );
  48076. if ( parameters.flatShading )
  48077. _programLayers.enable( 2 );
  48078. if ( parameters.logarithmicDepthBuffer )
  48079. _programLayers.enable( 3 );
  48080. if ( parameters.reversedDepthBuffer )
  48081. _programLayers.enable( 4 );
  48082. if ( parameters.skinning )
  48083. _programLayers.enable( 5 );
  48084. if ( parameters.morphTargets )
  48085. _programLayers.enable( 6 );
  48086. if ( parameters.morphNormals )
  48087. _programLayers.enable( 7 );
  48088. if ( parameters.morphColors )
  48089. _programLayers.enable( 8 );
  48090. if ( parameters.premultipliedAlpha )
  48091. _programLayers.enable( 9 );
  48092. if ( parameters.shadowMapEnabled )
  48093. _programLayers.enable( 10 );
  48094. if ( parameters.doubleSided )
  48095. _programLayers.enable( 11 );
  48096. if ( parameters.flipSided )
  48097. _programLayers.enable( 12 );
  48098. if ( parameters.useDepthPacking )
  48099. _programLayers.enable( 13 );
  48100. if ( parameters.dithering )
  48101. _programLayers.enable( 14 );
  48102. if ( parameters.transmission )
  48103. _programLayers.enable( 15 );
  48104. if ( parameters.sheen )
  48105. _programLayers.enable( 16 );
  48106. if ( parameters.opaque )
  48107. _programLayers.enable( 17 );
  48108. if ( parameters.pointsUvs )
  48109. _programLayers.enable( 18 );
  48110. if ( parameters.decodeVideoTexture )
  48111. _programLayers.enable( 19 );
  48112. if ( parameters.decodeVideoTextureEmissive )
  48113. _programLayers.enable( 20 );
  48114. if ( parameters.alphaToCoverage )
  48115. _programLayers.enable( 21 );
  48116. array.push( _programLayers.mask );
  48117. }
  48118. function getUniforms( material ) {
  48119. const shaderID = shaderIDs[ material.type ];
  48120. let uniforms;
  48121. if ( shaderID ) {
  48122. const shader = ShaderLib[ shaderID ];
  48123. uniforms = UniformsUtils.clone( shader.uniforms );
  48124. } else {
  48125. uniforms = material.uniforms;
  48126. }
  48127. return uniforms;
  48128. }
  48129. function acquireProgram( parameters, cacheKey ) {
  48130. let program = programsMap.get( cacheKey );
  48131. if ( program !== undefined ) {
  48132. ++ program.usedTimes;
  48133. } else {
  48134. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  48135. programs.push( program );
  48136. programsMap.set( cacheKey, program );
  48137. }
  48138. return program;
  48139. }
  48140. function releaseProgram( program ) {
  48141. if ( -- program.usedTimes === 0 ) {
  48142. // Remove from unordered set
  48143. const i = programs.indexOf( program );
  48144. programs[ i ] = programs[ programs.length - 1 ];
  48145. programs.pop();
  48146. // Remove from map
  48147. programsMap.delete( program.cacheKey );
  48148. // Free WebGL resources
  48149. program.destroy();
  48150. }
  48151. }
  48152. function releaseShaderCache( material ) {
  48153. _customShaders.remove( material );
  48154. }
  48155. function dispose() {
  48156. _customShaders.dispose();
  48157. }
  48158. return {
  48159. getParameters: getParameters,
  48160. getProgramCacheKey: getProgramCacheKey,
  48161. getUniforms: getUniforms,
  48162. acquireProgram: acquireProgram,
  48163. releaseProgram: releaseProgram,
  48164. releaseShaderCache: releaseShaderCache,
  48165. // Exposed for resource monitoring & error feedback via renderer.info:
  48166. programs: programs,
  48167. dispose: dispose
  48168. };
  48169. }
  48170. function WebGLProperties() {
  48171. let properties = new WeakMap();
  48172. function has( object ) {
  48173. return properties.has( object );
  48174. }
  48175. function get( object ) {
  48176. let map = properties.get( object );
  48177. if ( map === undefined ) {
  48178. map = {};
  48179. properties.set( object, map );
  48180. }
  48181. return map;
  48182. }
  48183. function remove( object ) {
  48184. properties.delete( object );
  48185. }
  48186. function update( object, key, value ) {
  48187. properties.get( object )[ key ] = value;
  48188. }
  48189. function dispose() {
  48190. properties = new WeakMap();
  48191. }
  48192. return {
  48193. has: has,
  48194. get: get,
  48195. remove: remove,
  48196. update: update,
  48197. dispose: dispose
  48198. };
  48199. }
  48200. function painterSortStable( a, b ) {
  48201. if ( a.groupOrder !== b.groupOrder ) {
  48202. return a.groupOrder - b.groupOrder;
  48203. } else if ( a.renderOrder !== b.renderOrder ) {
  48204. return a.renderOrder - b.renderOrder;
  48205. } else if ( a.material.id !== b.material.id ) {
  48206. return a.material.id - b.material.id;
  48207. } else if ( a.materialVariant !== b.materialVariant ) {
  48208. return a.materialVariant - b.materialVariant;
  48209. } else if ( a.z !== b.z ) {
  48210. return a.z - b.z;
  48211. } else {
  48212. return a.id - b.id;
  48213. }
  48214. }
  48215. function reversePainterSortStable( a, b ) {
  48216. if ( a.groupOrder !== b.groupOrder ) {
  48217. return a.groupOrder - b.groupOrder;
  48218. } else if ( a.renderOrder !== b.renderOrder ) {
  48219. return a.renderOrder - b.renderOrder;
  48220. } else if ( a.z !== b.z ) {
  48221. return b.z - a.z;
  48222. } else {
  48223. return a.id - b.id;
  48224. }
  48225. }
  48226. function WebGLRenderList() {
  48227. const renderItems = [];
  48228. let renderItemsIndex = 0;
  48229. const opaque = [];
  48230. const transmissive = [];
  48231. const transparent = [];
  48232. function init() {
  48233. renderItemsIndex = 0;
  48234. opaque.length = 0;
  48235. transmissive.length = 0;
  48236. transparent.length = 0;
  48237. }
  48238. function materialVariant( object ) {
  48239. let variant = 0;
  48240. if ( object.isInstancedMesh ) variant += 2;
  48241. if ( object.isSkinnedMesh ) variant += 1;
  48242. return variant;
  48243. }
  48244. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  48245. let renderItem = renderItems[ renderItemsIndex ];
  48246. if ( renderItem === undefined ) {
  48247. renderItem = {
  48248. id: object.id,
  48249. object: object,
  48250. geometry: geometry,
  48251. material: material,
  48252. materialVariant: materialVariant( object ),
  48253. groupOrder: groupOrder,
  48254. renderOrder: object.renderOrder,
  48255. z: z,
  48256. group: group
  48257. };
  48258. renderItems[ renderItemsIndex ] = renderItem;
  48259. } else {
  48260. renderItem.id = object.id;
  48261. renderItem.object = object;
  48262. renderItem.geometry = geometry;
  48263. renderItem.material = material;
  48264. renderItem.materialVariant = materialVariant( object );
  48265. renderItem.groupOrder = groupOrder;
  48266. renderItem.renderOrder = object.renderOrder;
  48267. renderItem.z = z;
  48268. renderItem.group = group;
  48269. }
  48270. renderItemsIndex ++;
  48271. return renderItem;
  48272. }
  48273. function push( object, geometry, material, groupOrder, z, group ) {
  48274. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  48275. if ( material.transmission > 0.0 ) {
  48276. transmissive.push( renderItem );
  48277. } else if ( material.transparent === true ) {
  48278. transparent.push( renderItem );
  48279. } else {
  48280. opaque.push( renderItem );
  48281. }
  48282. }
  48283. function unshift( object, geometry, material, groupOrder, z, group ) {
  48284. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  48285. if ( material.transmission > 0.0 ) {
  48286. transmissive.unshift( renderItem );
  48287. } else if ( material.transparent === true ) {
  48288. transparent.unshift( renderItem );
  48289. } else {
  48290. opaque.unshift( renderItem );
  48291. }
  48292. }
  48293. function sort( customOpaqueSort, customTransparentSort ) {
  48294. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  48295. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  48296. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  48297. }
  48298. function finish() {
  48299. // Clear references from inactive renderItems in the list
  48300. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  48301. const renderItem = renderItems[ i ];
  48302. if ( renderItem.id === null ) break;
  48303. renderItem.id = null;
  48304. renderItem.object = null;
  48305. renderItem.geometry = null;
  48306. renderItem.material = null;
  48307. renderItem.group = null;
  48308. }
  48309. }
  48310. return {
  48311. opaque: opaque,
  48312. transmissive: transmissive,
  48313. transparent: transparent,
  48314. init: init,
  48315. push: push,
  48316. unshift: unshift,
  48317. finish: finish,
  48318. sort: sort
  48319. };
  48320. }
  48321. function WebGLRenderLists() {
  48322. let lists = new WeakMap();
  48323. function get( scene, renderCallDepth ) {
  48324. const listArray = lists.get( scene );
  48325. let list;
  48326. if ( listArray === undefined ) {
  48327. list = new WebGLRenderList();
  48328. lists.set( scene, [ list ] );
  48329. } else {
  48330. if ( renderCallDepth >= listArray.length ) {
  48331. list = new WebGLRenderList();
  48332. listArray.push( list );
  48333. } else {
  48334. list = listArray[ renderCallDepth ];
  48335. }
  48336. }
  48337. return list;
  48338. }
  48339. function dispose() {
  48340. lists = new WeakMap();
  48341. }
  48342. return {
  48343. get: get,
  48344. dispose: dispose
  48345. };
  48346. }
  48347. function UniformsCache() {
  48348. const lights = {};
  48349. return {
  48350. get: function ( light ) {
  48351. if ( lights[ light.id ] !== undefined ) {
  48352. return lights[ light.id ];
  48353. }
  48354. let uniforms;
  48355. switch ( light.type ) {
  48356. case 'DirectionalLight':
  48357. uniforms = {
  48358. direction: new Vector3(),
  48359. color: new Color()
  48360. };
  48361. break;
  48362. case 'SpotLight':
  48363. uniforms = {
  48364. position: new Vector3(),
  48365. direction: new Vector3(),
  48366. color: new Color(),
  48367. distance: 0,
  48368. coneCos: 0,
  48369. penumbraCos: 0,
  48370. decay: 0
  48371. };
  48372. break;
  48373. case 'PointLight':
  48374. uniforms = {
  48375. position: new Vector3(),
  48376. color: new Color(),
  48377. distance: 0,
  48378. decay: 0
  48379. };
  48380. break;
  48381. case 'HemisphereLight':
  48382. uniforms = {
  48383. direction: new Vector3(),
  48384. skyColor: new Color(),
  48385. groundColor: new Color()
  48386. };
  48387. break;
  48388. case 'RectAreaLight':
  48389. uniforms = {
  48390. color: new Color(),
  48391. position: new Vector3(),
  48392. halfWidth: new Vector3(),
  48393. halfHeight: new Vector3()
  48394. };
  48395. break;
  48396. }
  48397. lights[ light.id ] = uniforms;
  48398. return uniforms;
  48399. }
  48400. };
  48401. }
  48402. function ShadowUniformsCache() {
  48403. const lights = {};
  48404. return {
  48405. get: function ( light ) {
  48406. if ( lights[ light.id ] !== undefined ) {
  48407. return lights[ light.id ];
  48408. }
  48409. let uniforms;
  48410. switch ( light.type ) {
  48411. case 'DirectionalLight':
  48412. uniforms = {
  48413. shadowIntensity: 1,
  48414. shadowBias: 0,
  48415. shadowNormalBias: 0,
  48416. shadowRadius: 1,
  48417. shadowMapSize: new Vector2()
  48418. };
  48419. break;
  48420. case 'SpotLight':
  48421. uniforms = {
  48422. shadowIntensity: 1,
  48423. shadowBias: 0,
  48424. shadowNormalBias: 0,
  48425. shadowRadius: 1,
  48426. shadowMapSize: new Vector2()
  48427. };
  48428. break;
  48429. case 'PointLight':
  48430. uniforms = {
  48431. shadowIntensity: 1,
  48432. shadowBias: 0,
  48433. shadowNormalBias: 0,
  48434. shadowRadius: 1,
  48435. shadowMapSize: new Vector2(),
  48436. shadowCameraNear: 1,
  48437. shadowCameraFar: 1000
  48438. };
  48439. break;
  48440. // TODO (abelnation): set RectAreaLight shadow uniforms
  48441. }
  48442. lights[ light.id ] = uniforms;
  48443. return uniforms;
  48444. }
  48445. };
  48446. }
  48447. let nextVersion = 0;
  48448. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  48449. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  48450. }
  48451. function WebGLLights( extensions ) {
  48452. const cache = new UniformsCache();
  48453. const shadowCache = ShadowUniformsCache();
  48454. const state = {
  48455. version: 0,
  48456. hash: {
  48457. directionalLength: -1,
  48458. pointLength: -1,
  48459. spotLength: -1,
  48460. rectAreaLength: -1,
  48461. hemiLength: -1,
  48462. numDirectionalShadows: -1,
  48463. numPointShadows: -1,
  48464. numSpotShadows: -1,
  48465. numSpotMaps: -1,
  48466. numLightProbes: -1
  48467. },
  48468. ambient: [ 0, 0, 0 ],
  48469. probe: [],
  48470. directional: [],
  48471. directionalShadow: [],
  48472. directionalShadowMap: [],
  48473. directionalShadowMatrix: [],
  48474. spot: [],
  48475. spotLightMap: [],
  48476. spotShadow: [],
  48477. spotShadowMap: [],
  48478. spotLightMatrix: [],
  48479. rectArea: [],
  48480. rectAreaLTC1: null,
  48481. rectAreaLTC2: null,
  48482. point: [],
  48483. pointShadow: [],
  48484. pointShadowMap: [],
  48485. pointShadowMatrix: [],
  48486. hemi: [],
  48487. numSpotLightShadowsWithMaps: 0,
  48488. numLightProbes: 0
  48489. };
  48490. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  48491. const vector3 = new Vector3();
  48492. const matrix4 = new Matrix4();
  48493. const matrix42 = new Matrix4();
  48494. function setup( lights ) {
  48495. let r = 0, g = 0, b = 0;
  48496. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  48497. let directionalLength = 0;
  48498. let pointLength = 0;
  48499. let spotLength = 0;
  48500. let rectAreaLength = 0;
  48501. let hemiLength = 0;
  48502. let numDirectionalShadows = 0;
  48503. let numPointShadows = 0;
  48504. let numSpotShadows = 0;
  48505. let numSpotMaps = 0;
  48506. let numSpotShadowsWithMaps = 0;
  48507. let numLightProbes = 0;
  48508. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  48509. lights.sort( shadowCastingAndTexturingLightsFirst );
  48510. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48511. const light = lights[ i ];
  48512. const color = light.color;
  48513. const intensity = light.intensity;
  48514. const distance = light.distance;
  48515. let shadowMap = null;
  48516. if ( light.shadow && light.shadow.map ) {
  48517. if ( light.shadow.map.texture.format === RGFormat ) {
  48518. // VSM uses color texture with blurred mean/std_dev
  48519. shadowMap = light.shadow.map.texture;
  48520. } else {
  48521. // Other types use depth texture
  48522. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  48523. }
  48524. }
  48525. if ( light.isAmbientLight ) {
  48526. r += color.r * intensity;
  48527. g += color.g * intensity;
  48528. b += color.b * intensity;
  48529. } else if ( light.isLightProbe ) {
  48530. for ( let j = 0; j < 9; j ++ ) {
  48531. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  48532. }
  48533. numLightProbes ++;
  48534. } else if ( light.isDirectionalLight ) {
  48535. const uniforms = cache.get( light );
  48536. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48537. if ( light.castShadow ) {
  48538. const shadow = light.shadow;
  48539. const shadowUniforms = shadowCache.get( light );
  48540. shadowUniforms.shadowIntensity = shadow.intensity;
  48541. shadowUniforms.shadowBias = shadow.bias;
  48542. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48543. shadowUniforms.shadowRadius = shadow.radius;
  48544. shadowUniforms.shadowMapSize = shadow.mapSize;
  48545. state.directionalShadow[ directionalLength ] = shadowUniforms;
  48546. state.directionalShadowMap[ directionalLength ] = shadowMap;
  48547. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  48548. numDirectionalShadows ++;
  48549. }
  48550. state.directional[ directionalLength ] = uniforms;
  48551. directionalLength ++;
  48552. } else if ( light.isSpotLight ) {
  48553. const uniforms = cache.get( light );
  48554. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48555. uniforms.color.copy( color ).multiplyScalar( intensity );
  48556. uniforms.distance = distance;
  48557. uniforms.coneCos = Math.cos( light.angle );
  48558. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  48559. uniforms.decay = light.decay;
  48560. state.spot[ spotLength ] = uniforms;
  48561. const shadow = light.shadow;
  48562. if ( light.map ) {
  48563. state.spotLightMap[ numSpotMaps ] = light.map;
  48564. numSpotMaps ++;
  48565. // make sure the lightMatrix is up to date
  48566. // TODO : do it if required only
  48567. shadow.updateMatrices( light );
  48568. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  48569. }
  48570. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  48571. if ( light.castShadow ) {
  48572. const shadowUniforms = shadowCache.get( light );
  48573. shadowUniforms.shadowIntensity = shadow.intensity;
  48574. shadowUniforms.shadowBias = shadow.bias;
  48575. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48576. shadowUniforms.shadowRadius = shadow.radius;
  48577. shadowUniforms.shadowMapSize = shadow.mapSize;
  48578. state.spotShadow[ spotLength ] = shadowUniforms;
  48579. state.spotShadowMap[ spotLength ] = shadowMap;
  48580. numSpotShadows ++;
  48581. }
  48582. spotLength ++;
  48583. } else if ( light.isRectAreaLight ) {
  48584. const uniforms = cache.get( light );
  48585. uniforms.color.copy( color ).multiplyScalar( intensity );
  48586. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48587. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48588. state.rectArea[ rectAreaLength ] = uniforms;
  48589. rectAreaLength ++;
  48590. } else if ( light.isPointLight ) {
  48591. const uniforms = cache.get( light );
  48592. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48593. uniforms.distance = light.distance;
  48594. uniforms.decay = light.decay;
  48595. if ( light.castShadow ) {
  48596. const shadow = light.shadow;
  48597. const shadowUniforms = shadowCache.get( light );
  48598. shadowUniforms.shadowIntensity = shadow.intensity;
  48599. shadowUniforms.shadowBias = shadow.bias;
  48600. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48601. shadowUniforms.shadowRadius = shadow.radius;
  48602. shadowUniforms.shadowMapSize = shadow.mapSize;
  48603. shadowUniforms.shadowCameraNear = shadow.camera.near;
  48604. shadowUniforms.shadowCameraFar = shadow.camera.far;
  48605. state.pointShadow[ pointLength ] = shadowUniforms;
  48606. state.pointShadowMap[ pointLength ] = shadowMap;
  48607. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  48608. numPointShadows ++;
  48609. }
  48610. state.point[ pointLength ] = uniforms;
  48611. pointLength ++;
  48612. } else if ( light.isHemisphereLight ) {
  48613. const uniforms = cache.get( light );
  48614. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  48615. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  48616. state.hemi[ hemiLength ] = uniforms;
  48617. hemiLength ++;
  48618. }
  48619. }
  48620. if ( rectAreaLength > 0 ) {
  48621. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  48622. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  48623. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  48624. } else {
  48625. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  48626. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  48627. }
  48628. }
  48629. state.ambient[ 0 ] = r;
  48630. state.ambient[ 1 ] = g;
  48631. state.ambient[ 2 ] = b;
  48632. const hash = state.hash;
  48633. if ( hash.directionalLength !== directionalLength ||
  48634. hash.pointLength !== pointLength ||
  48635. hash.spotLength !== spotLength ||
  48636. hash.rectAreaLength !== rectAreaLength ||
  48637. hash.hemiLength !== hemiLength ||
  48638. hash.numDirectionalShadows !== numDirectionalShadows ||
  48639. hash.numPointShadows !== numPointShadows ||
  48640. hash.numSpotShadows !== numSpotShadows ||
  48641. hash.numSpotMaps !== numSpotMaps ||
  48642. hash.numLightProbes !== numLightProbes ) {
  48643. state.directional.length = directionalLength;
  48644. state.spot.length = spotLength;
  48645. state.rectArea.length = rectAreaLength;
  48646. state.point.length = pointLength;
  48647. state.hemi.length = hemiLength;
  48648. state.directionalShadow.length = numDirectionalShadows;
  48649. state.directionalShadowMap.length = numDirectionalShadows;
  48650. state.pointShadow.length = numPointShadows;
  48651. state.pointShadowMap.length = numPointShadows;
  48652. state.spotShadow.length = numSpotShadows;
  48653. state.spotShadowMap.length = numSpotShadows;
  48654. state.directionalShadowMatrix.length = numDirectionalShadows;
  48655. state.pointShadowMatrix.length = numPointShadows;
  48656. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48657. state.spotLightMap.length = numSpotMaps;
  48658. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48659. state.numLightProbes = numLightProbes;
  48660. hash.directionalLength = directionalLength;
  48661. hash.pointLength = pointLength;
  48662. hash.spotLength = spotLength;
  48663. hash.rectAreaLength = rectAreaLength;
  48664. hash.hemiLength = hemiLength;
  48665. hash.numDirectionalShadows = numDirectionalShadows;
  48666. hash.numPointShadows = numPointShadows;
  48667. hash.numSpotShadows = numSpotShadows;
  48668. hash.numSpotMaps = numSpotMaps;
  48669. hash.numLightProbes = numLightProbes;
  48670. state.version = nextVersion ++;
  48671. }
  48672. }
  48673. function setupView( lights, camera ) {
  48674. let directionalLength = 0;
  48675. let pointLength = 0;
  48676. let spotLength = 0;
  48677. let rectAreaLength = 0;
  48678. let hemiLength = 0;
  48679. const viewMatrix = camera.matrixWorldInverse;
  48680. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48681. const light = lights[ i ];
  48682. if ( light.isDirectionalLight ) {
  48683. const uniforms = state.directional[ directionalLength ];
  48684. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48685. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48686. uniforms.direction.sub( vector3 );
  48687. uniforms.direction.transformDirection( viewMatrix );
  48688. directionalLength ++;
  48689. } else if ( light.isSpotLight ) {
  48690. const uniforms = state.spot[ spotLength ];
  48691. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48692. uniforms.position.applyMatrix4( viewMatrix );
  48693. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48694. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48695. uniforms.direction.sub( vector3 );
  48696. uniforms.direction.transformDirection( viewMatrix );
  48697. spotLength ++;
  48698. } else if ( light.isRectAreaLight ) {
  48699. const uniforms = state.rectArea[ rectAreaLength ];
  48700. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48701. uniforms.position.applyMatrix4( viewMatrix );
  48702. // extract local rotation of light to derive width/height half vectors
  48703. matrix42.identity();
  48704. matrix4.copy( light.matrixWorld );
  48705. matrix4.premultiply( viewMatrix );
  48706. matrix42.extractRotation( matrix4 );
  48707. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48708. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48709. uniforms.halfWidth.applyMatrix4( matrix42 );
  48710. uniforms.halfHeight.applyMatrix4( matrix42 );
  48711. rectAreaLength ++;
  48712. } else if ( light.isPointLight ) {
  48713. const uniforms = state.point[ pointLength ];
  48714. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48715. uniforms.position.applyMatrix4( viewMatrix );
  48716. pointLength ++;
  48717. } else if ( light.isHemisphereLight ) {
  48718. const uniforms = state.hemi[ hemiLength ];
  48719. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48720. uniforms.direction.transformDirection( viewMatrix );
  48721. hemiLength ++;
  48722. }
  48723. }
  48724. }
  48725. return {
  48726. setup: setup,
  48727. setupView: setupView,
  48728. state: state
  48729. };
  48730. }
  48731. function WebGLRenderState( extensions ) {
  48732. const lights = new WebGLLights( extensions );
  48733. const lightsArray = [];
  48734. const shadowsArray = [];
  48735. function init( camera ) {
  48736. state.camera = camera;
  48737. lightsArray.length = 0;
  48738. shadowsArray.length = 0;
  48739. }
  48740. function pushLight( light ) {
  48741. lightsArray.push( light );
  48742. }
  48743. function pushShadow( shadowLight ) {
  48744. shadowsArray.push( shadowLight );
  48745. }
  48746. function setupLights() {
  48747. lights.setup( lightsArray );
  48748. }
  48749. function setupLightsView( camera ) {
  48750. lights.setupView( lightsArray, camera );
  48751. }
  48752. const state = {
  48753. lightsArray: lightsArray,
  48754. shadowsArray: shadowsArray,
  48755. camera: null,
  48756. lights: lights,
  48757. transmissionRenderTarget: {}
  48758. };
  48759. return {
  48760. init: init,
  48761. state: state,
  48762. setupLights: setupLights,
  48763. setupLightsView: setupLightsView,
  48764. pushLight: pushLight,
  48765. pushShadow: pushShadow
  48766. };
  48767. }
  48768. function WebGLRenderStates( extensions ) {
  48769. let renderStates = new WeakMap();
  48770. function get( scene, renderCallDepth = 0 ) {
  48771. const renderStateArray = renderStates.get( scene );
  48772. let renderState;
  48773. if ( renderStateArray === undefined ) {
  48774. renderState = new WebGLRenderState( extensions );
  48775. renderStates.set( scene, [ renderState ] );
  48776. } else {
  48777. if ( renderCallDepth >= renderStateArray.length ) {
  48778. renderState = new WebGLRenderState( extensions );
  48779. renderStateArray.push( renderState );
  48780. } else {
  48781. renderState = renderStateArray[ renderCallDepth ];
  48782. }
  48783. }
  48784. return renderState;
  48785. }
  48786. function dispose() {
  48787. renderStates = new WeakMap();
  48788. }
  48789. return {
  48790. get: get,
  48791. dispose: dispose
  48792. };
  48793. }
  48794. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48795. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\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( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}";
  48796. const _cubeDirections = [
  48797. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  48798. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  48799. ];
  48800. const _cubeUps = [
  48801. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  48802. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  48803. ];
  48804. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  48805. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  48806. const _lookTarget = /*@__PURE__*/ new Vector3();
  48807. function WebGLShadowMap( renderer, objects, capabilities ) {
  48808. let _frustum = new Frustum();
  48809. const _shadowMapSize = new Vector2(),
  48810. _viewportSize = new Vector2(),
  48811. _viewport = new Vector4(),
  48812. _depthMaterial = new MeshDepthMaterial(),
  48813. _distanceMaterial = new MeshDistanceMaterial(),
  48814. _materialCache = {},
  48815. _maxTextureSize = capabilities.maxTextureSize;
  48816. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48817. const shadowMaterialVertical = new ShaderMaterial( {
  48818. defines: {
  48819. VSM_SAMPLES: 8
  48820. },
  48821. uniforms: {
  48822. shadow_pass: { value: null },
  48823. resolution: { value: new Vector2() },
  48824. radius: { value: 4.0 }
  48825. },
  48826. vertexShader: vertex,
  48827. fragmentShader: fragment
  48828. } );
  48829. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48830. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48831. const fullScreenTri = new BufferGeometry();
  48832. fullScreenTri.setAttribute(
  48833. 'position',
  48834. new BufferAttribute(
  48835. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48836. 3
  48837. )
  48838. );
  48839. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48840. const scope = this;
  48841. this.enabled = false;
  48842. this.autoUpdate = true;
  48843. this.needsUpdate = false;
  48844. this.type = PCFShadowMap;
  48845. let _previousType = this.type;
  48846. this.render = function ( lights, scene, camera ) {
  48847. if ( scope.enabled === false ) return;
  48848. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48849. if ( lights.length === 0 ) return;
  48850. if ( this.type === PCFSoftShadowMap ) {
  48851. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48852. this.type = PCFShadowMap;
  48853. }
  48854. const currentRenderTarget = renderer.getRenderTarget();
  48855. const activeCubeFace = renderer.getActiveCubeFace();
  48856. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48857. const _state = renderer.state;
  48858. // Set GL state for depth map.
  48859. _state.setBlending( NoBlending );
  48860. if ( _state.buffers.depth.getReversed() === true ) {
  48861. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48862. } else {
  48863. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48864. }
  48865. _state.buffers.depth.setTest( true );
  48866. _state.setScissorTest( false );
  48867. // check for shadow map type changes
  48868. const typeChanged = _previousType !== this.type;
  48869. // When shadow map type changes, materials need recompilation because sampler types change
  48870. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48871. if ( typeChanged ) {
  48872. scene.traverse( function ( object ) {
  48873. if ( object.material ) {
  48874. if ( Array.isArray( object.material ) ) {
  48875. object.material.forEach( mat => mat.needsUpdate = true );
  48876. } else {
  48877. object.material.needsUpdate = true;
  48878. }
  48879. }
  48880. } );
  48881. }
  48882. // render depth map
  48883. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48884. const light = lights[ i ];
  48885. const shadow = light.shadow;
  48886. if ( shadow === undefined ) {
  48887. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48888. continue;
  48889. }
  48890. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48891. _shadowMapSize.copy( shadow.mapSize );
  48892. const shadowFrameExtents = shadow.getFrameExtents();
  48893. _shadowMapSize.multiply( shadowFrameExtents );
  48894. _viewportSize.copy( shadow.mapSize );
  48895. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48896. if ( _shadowMapSize.x > _maxTextureSize ) {
  48897. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48898. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48899. shadow.mapSize.x = _viewportSize.x;
  48900. }
  48901. if ( _shadowMapSize.y > _maxTextureSize ) {
  48902. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48903. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48904. shadow.mapSize.y = _viewportSize.y;
  48905. }
  48906. }
  48907. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48908. shadow.camera._reversedDepth = reversedDepthBuffer;
  48909. if ( shadow.map === null || typeChanged === true ) {
  48910. if ( shadow.map !== null ) {
  48911. if ( shadow.map.depthTexture !== null ) {
  48912. shadow.map.depthTexture.dispose();
  48913. shadow.map.depthTexture = null;
  48914. }
  48915. shadow.map.dispose();
  48916. }
  48917. if ( this.type === VSMShadowMap ) {
  48918. if ( light.isPointLight ) {
  48919. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48920. continue;
  48921. }
  48922. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48923. format: RGFormat,
  48924. type: HalfFloatType,
  48925. minFilter: LinearFilter,
  48926. magFilter: LinearFilter,
  48927. generateMipmaps: false
  48928. } );
  48929. shadow.map.texture.name = light.name + '.shadowMap';
  48930. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  48931. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  48932. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  48933. shadow.map.depthTexture.format = DepthFormat;
  48934. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  48935. shadow.map.depthTexture.minFilter = NearestFilter;
  48936. shadow.map.depthTexture.magFilter = NearestFilter;
  48937. } else {
  48938. if ( light.isPointLight ) {
  48939. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48940. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48941. } else {
  48942. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48943. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48944. }
  48945. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48946. shadow.map.depthTexture.format = DepthFormat;
  48947. if ( this.type === PCFShadowMap ) {
  48948. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48949. shadow.map.depthTexture.minFilter = LinearFilter;
  48950. shadow.map.depthTexture.magFilter = LinearFilter;
  48951. } else {
  48952. shadow.map.depthTexture.compareFunction = null;
  48953. shadow.map.depthTexture.minFilter = NearestFilter;
  48954. shadow.map.depthTexture.magFilter = NearestFilter;
  48955. }
  48956. }
  48957. shadow.camera.updateProjectionMatrix();
  48958. }
  48959. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48960. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48961. for ( let face = 0; face < faceCount; face ++ ) {
  48962. // For cube render targets, render to each face separately
  48963. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48964. renderer.setRenderTarget( shadow.map, face );
  48965. renderer.clear();
  48966. } else {
  48967. // For 2D render targets, use viewports
  48968. if ( face === 0 ) {
  48969. renderer.setRenderTarget( shadow.map );
  48970. renderer.clear();
  48971. }
  48972. const viewport = shadow.getViewport( face );
  48973. _viewport.set(
  48974. _viewportSize.x * viewport.x,
  48975. _viewportSize.y * viewport.y,
  48976. _viewportSize.x * viewport.z,
  48977. _viewportSize.y * viewport.w
  48978. );
  48979. _state.viewport( _viewport );
  48980. }
  48981. if ( light.isPointLight ) {
  48982. const camera = shadow.camera;
  48983. const shadowMatrix = shadow.matrix;
  48984. const far = light.distance || camera.far;
  48985. if ( far !== camera.far ) {
  48986. camera.far = far;
  48987. camera.updateProjectionMatrix();
  48988. }
  48989. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  48990. camera.position.copy( _lightPositionWorld );
  48991. _lookTarget.copy( camera.position );
  48992. _lookTarget.add( _cubeDirections[ face ] );
  48993. camera.up.copy( _cubeUps[ face ] );
  48994. camera.lookAt( _lookTarget );
  48995. camera.updateMatrixWorld();
  48996. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  48997. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  48998. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  48999. } else {
  49000. shadow.updateMatrices( light );
  49001. }
  49002. _frustum = shadow.getFrustum();
  49003. renderObject( scene, camera, shadow.camera, light, this.type );
  49004. }
  49005. // do blur pass for VSM
  49006. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  49007. VSMPass( shadow, camera );
  49008. }
  49009. shadow.needsUpdate = false;
  49010. }
  49011. _previousType = this.type;
  49012. scope.needsUpdate = false;
  49013. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  49014. };
  49015. function VSMPass( shadow, camera ) {
  49016. const geometry = objects.update( fullScreenMesh );
  49017. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  49018. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  49019. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  49020. shadowMaterialVertical.needsUpdate = true;
  49021. shadowMaterialHorizontal.needsUpdate = true;
  49022. }
  49023. if ( shadow.mapPass === null ) {
  49024. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  49025. format: RGFormat,
  49026. type: HalfFloatType
  49027. } );
  49028. }
  49029. // vertical pass - read from native depth texture
  49030. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  49031. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  49032. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  49033. renderer.setRenderTarget( shadow.mapPass );
  49034. renderer.clear();
  49035. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  49036. // horizontal pass
  49037. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  49038. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  49039. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  49040. renderer.setRenderTarget( shadow.map );
  49041. renderer.clear();
  49042. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  49043. }
  49044. function getDepthMaterial( object, material, light, type ) {
  49045. let result = null;
  49046. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  49047. if ( customMaterial !== undefined ) {
  49048. result = customMaterial;
  49049. } else {
  49050. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  49051. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  49052. ( material.displacementMap && material.displacementScale !== 0 ) ||
  49053. ( material.alphaMap && material.alphaTest > 0 ) ||
  49054. ( material.map && material.alphaTest > 0 ) ||
  49055. ( material.alphaToCoverage === true ) ) {
  49056. // in this case we need a unique material instance reflecting the
  49057. // appropriate state
  49058. const keyA = result.uuid, keyB = material.uuid;
  49059. let materialsForVariant = _materialCache[ keyA ];
  49060. if ( materialsForVariant === undefined ) {
  49061. materialsForVariant = {};
  49062. _materialCache[ keyA ] = materialsForVariant;
  49063. }
  49064. let cachedMaterial = materialsForVariant[ keyB ];
  49065. if ( cachedMaterial === undefined ) {
  49066. cachedMaterial = result.clone();
  49067. materialsForVariant[ keyB ] = cachedMaterial;
  49068. material.addEventListener( 'dispose', onMaterialDispose );
  49069. }
  49070. result = cachedMaterial;
  49071. }
  49072. }
  49073. result.visible = material.visible;
  49074. result.wireframe = material.wireframe;
  49075. if ( type === VSMShadowMap ) {
  49076. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  49077. } else {
  49078. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  49079. }
  49080. result.alphaMap = material.alphaMap;
  49081. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  49082. result.map = material.map;
  49083. result.clipShadows = material.clipShadows;
  49084. result.clippingPlanes = material.clippingPlanes;
  49085. result.clipIntersection = material.clipIntersection;
  49086. result.displacementMap = material.displacementMap;
  49087. result.displacementScale = material.displacementScale;
  49088. result.displacementBias = material.displacementBias;
  49089. result.wireframeLinewidth = material.wireframeLinewidth;
  49090. result.linewidth = material.linewidth;
  49091. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  49092. const materialProperties = renderer.properties.get( result );
  49093. materialProperties.light = light;
  49094. }
  49095. return result;
  49096. }
  49097. function renderObject( object, camera, shadowCamera, light, type ) {
  49098. if ( object.visible === false ) return;
  49099. const visible = object.layers.test( camera.layers );
  49100. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  49101. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  49102. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  49103. const geometry = objects.update( object );
  49104. const material = object.material;
  49105. if ( Array.isArray( material ) ) {
  49106. const groups = geometry.groups;
  49107. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  49108. const group = groups[ k ];
  49109. const groupMaterial = material[ group.materialIndex ];
  49110. if ( groupMaterial && groupMaterial.visible ) {
  49111. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  49112. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  49113. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  49114. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  49115. }
  49116. }
  49117. } else if ( material.visible ) {
  49118. const depthMaterial = getDepthMaterial( object, material, light, type );
  49119. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  49120. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  49121. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  49122. }
  49123. }
  49124. }
  49125. const children = object.children;
  49126. for ( let i = 0, l = children.length; i < l; i ++ ) {
  49127. renderObject( children[ i ], camera, shadowCamera, light, type );
  49128. }
  49129. }
  49130. function onMaterialDispose( event ) {
  49131. const material = event.target;
  49132. material.removeEventListener( 'dispose', onMaterialDispose );
  49133. // make sure to remove the unique distance/depth materials used for shadow map rendering
  49134. for ( const id in _materialCache ) {
  49135. const cache = _materialCache[ id ];
  49136. const uuid = event.target.uuid;
  49137. if ( uuid in cache ) {
  49138. const shadowMaterial = cache[ uuid ];
  49139. shadowMaterial.dispose();
  49140. delete cache[ uuid ];
  49141. }
  49142. }
  49143. }
  49144. }
  49145. function WebGLState( gl, extensions ) {
  49146. function ColorBuffer() {
  49147. let locked = false;
  49148. const color = new Vector4();
  49149. let currentColorMask = null;
  49150. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  49151. return {
  49152. setMask: function ( colorMask ) {
  49153. if ( currentColorMask !== colorMask && ! locked ) {
  49154. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  49155. currentColorMask = colorMask;
  49156. }
  49157. },
  49158. setLocked: function ( lock ) {
  49159. locked = lock;
  49160. },
  49161. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  49162. if ( premultipliedAlpha === true ) {
  49163. r *= a; g *= a; b *= a;
  49164. }
  49165. color.set( r, g, b, a );
  49166. if ( currentColorClear.equals( color ) === false ) {
  49167. gl.clearColor( r, g, b, a );
  49168. currentColorClear.copy( color );
  49169. }
  49170. },
  49171. reset: function () {
  49172. locked = false;
  49173. currentColorMask = null;
  49174. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  49175. }
  49176. };
  49177. }
  49178. function DepthBuffer() {
  49179. let locked = false;
  49180. let currentReversed = false;
  49181. let currentDepthMask = null;
  49182. let currentDepthFunc = null;
  49183. let currentDepthClear = null;
  49184. return {
  49185. setReversed: function ( reversed ) {
  49186. if ( currentReversed !== reversed ) {
  49187. const ext = extensions.get( 'EXT_clip_control' );
  49188. if ( reversed ) {
  49189. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  49190. } else {
  49191. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  49192. }
  49193. currentReversed = reversed;
  49194. const oldDepth = currentDepthClear;
  49195. currentDepthClear = null;
  49196. this.setClear( oldDepth );
  49197. }
  49198. },
  49199. getReversed: function () {
  49200. return currentReversed;
  49201. },
  49202. setTest: function ( depthTest ) {
  49203. if ( depthTest ) {
  49204. enable( gl.DEPTH_TEST );
  49205. } else {
  49206. disable( gl.DEPTH_TEST );
  49207. }
  49208. },
  49209. setMask: function ( depthMask ) {
  49210. if ( currentDepthMask !== depthMask && ! locked ) {
  49211. gl.depthMask( depthMask );
  49212. currentDepthMask = depthMask;
  49213. }
  49214. },
  49215. setFunc: function ( depthFunc ) {
  49216. if ( currentReversed ) depthFunc = ReversedDepthFuncs[ depthFunc ];
  49217. if ( currentDepthFunc !== depthFunc ) {
  49218. switch ( depthFunc ) {
  49219. case NeverDepth:
  49220. gl.depthFunc( gl.NEVER );
  49221. break;
  49222. case AlwaysDepth:
  49223. gl.depthFunc( gl.ALWAYS );
  49224. break;
  49225. case LessDepth:
  49226. gl.depthFunc( gl.LESS );
  49227. break;
  49228. case LessEqualDepth:
  49229. gl.depthFunc( gl.LEQUAL );
  49230. break;
  49231. case EqualDepth:
  49232. gl.depthFunc( gl.EQUAL );
  49233. break;
  49234. case GreaterEqualDepth:
  49235. gl.depthFunc( gl.GEQUAL );
  49236. break;
  49237. case GreaterDepth:
  49238. gl.depthFunc( gl.GREATER );
  49239. break;
  49240. case NotEqualDepth:
  49241. gl.depthFunc( gl.NOTEQUAL );
  49242. break;
  49243. default:
  49244. gl.depthFunc( gl.LEQUAL );
  49245. }
  49246. currentDepthFunc = depthFunc;
  49247. }
  49248. },
  49249. setLocked: function ( lock ) {
  49250. locked = lock;
  49251. },
  49252. setClear: function ( depth ) {
  49253. if ( currentDepthClear !== depth ) {
  49254. currentDepthClear = depth;
  49255. if ( currentReversed ) {
  49256. depth = 1 - depth;
  49257. }
  49258. gl.clearDepth( depth );
  49259. }
  49260. },
  49261. reset: function () {
  49262. locked = false;
  49263. currentDepthMask = null;
  49264. currentDepthFunc = null;
  49265. currentDepthClear = null;
  49266. currentReversed = false;
  49267. }
  49268. };
  49269. }
  49270. function StencilBuffer() {
  49271. let locked = false;
  49272. let currentStencilMask = null;
  49273. let currentStencilFunc = null;
  49274. let currentStencilRef = null;
  49275. let currentStencilFuncMask = null;
  49276. let currentStencilFail = null;
  49277. let currentStencilZFail = null;
  49278. let currentStencilZPass = null;
  49279. let currentStencilClear = null;
  49280. return {
  49281. setTest: function ( stencilTest ) {
  49282. if ( ! locked ) {
  49283. if ( stencilTest ) {
  49284. enable( gl.STENCIL_TEST );
  49285. } else {
  49286. disable( gl.STENCIL_TEST );
  49287. }
  49288. }
  49289. },
  49290. setMask: function ( stencilMask ) {
  49291. if ( currentStencilMask !== stencilMask && ! locked ) {
  49292. gl.stencilMask( stencilMask );
  49293. currentStencilMask = stencilMask;
  49294. }
  49295. },
  49296. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  49297. if ( currentStencilFunc !== stencilFunc ||
  49298. currentStencilRef !== stencilRef ||
  49299. currentStencilFuncMask !== stencilMask ) {
  49300. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  49301. currentStencilFunc = stencilFunc;
  49302. currentStencilRef = stencilRef;
  49303. currentStencilFuncMask = stencilMask;
  49304. }
  49305. },
  49306. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  49307. if ( currentStencilFail !== stencilFail ||
  49308. currentStencilZFail !== stencilZFail ||
  49309. currentStencilZPass !== stencilZPass ) {
  49310. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  49311. currentStencilFail = stencilFail;
  49312. currentStencilZFail = stencilZFail;
  49313. currentStencilZPass = stencilZPass;
  49314. }
  49315. },
  49316. setLocked: function ( lock ) {
  49317. locked = lock;
  49318. },
  49319. setClear: function ( stencil ) {
  49320. if ( currentStencilClear !== stencil ) {
  49321. gl.clearStencil( stencil );
  49322. currentStencilClear = stencil;
  49323. }
  49324. },
  49325. reset: function () {
  49326. locked = false;
  49327. currentStencilMask = null;
  49328. currentStencilFunc = null;
  49329. currentStencilRef = null;
  49330. currentStencilFuncMask = null;
  49331. currentStencilFail = null;
  49332. currentStencilZFail = null;
  49333. currentStencilZPass = null;
  49334. currentStencilClear = null;
  49335. }
  49336. };
  49337. }
  49338. //
  49339. const colorBuffer = new ColorBuffer();
  49340. const depthBuffer = new DepthBuffer();
  49341. const stencilBuffer = new StencilBuffer();
  49342. const uboBindings = new WeakMap();
  49343. const uboProgramMap = new WeakMap();
  49344. let enabledCapabilities = {};
  49345. let currentBoundFramebuffers = {};
  49346. let currentDrawbuffers = new WeakMap();
  49347. let defaultDrawbuffers = [];
  49348. let currentProgram = null;
  49349. let currentBlendingEnabled = false;
  49350. let currentBlending = null;
  49351. let currentBlendEquation = null;
  49352. let currentBlendSrc = null;
  49353. let currentBlendDst = null;
  49354. let currentBlendEquationAlpha = null;
  49355. let currentBlendSrcAlpha = null;
  49356. let currentBlendDstAlpha = null;
  49357. let currentBlendColor = new Color( 0, 0, 0 );
  49358. let currentBlendAlpha = 0;
  49359. let currentPremultipledAlpha = false;
  49360. let currentFlipSided = null;
  49361. let currentCullFace = null;
  49362. let currentLineWidth = null;
  49363. let currentPolygonOffsetFactor = null;
  49364. let currentPolygonOffsetUnits = null;
  49365. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  49366. let lineWidthAvailable = false;
  49367. let version = 0;
  49368. const glVersion = gl.getParameter( gl.VERSION );
  49369. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  49370. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  49371. lineWidthAvailable = ( version >= 1.0 );
  49372. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  49373. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  49374. lineWidthAvailable = ( version >= 2.0 );
  49375. }
  49376. let currentTextureSlot = null;
  49377. let currentBoundTextures = {};
  49378. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  49379. const viewportParam = gl.getParameter( gl.VIEWPORT );
  49380. const currentScissor = new Vector4().fromArray( scissorParam );
  49381. const currentViewport = new Vector4().fromArray( viewportParam );
  49382. function createTexture( type, target, count, dimensions ) {
  49383. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  49384. const texture = gl.createTexture();
  49385. gl.bindTexture( type, texture );
  49386. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  49387. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  49388. for ( let i = 0; i < count; i ++ ) {
  49389. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  49390. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49391. } else {
  49392. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49393. }
  49394. }
  49395. return texture;
  49396. }
  49397. const emptyTextures = {};
  49398. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  49399. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  49400. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  49401. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  49402. // init
  49403. colorBuffer.setClear( 0, 0, 0, 1 );
  49404. depthBuffer.setClear( 1 );
  49405. stencilBuffer.setClear( 0 );
  49406. enable( gl.DEPTH_TEST );
  49407. depthBuffer.setFunc( LessEqualDepth );
  49408. setFlipSided( false );
  49409. setCullFace( CullFaceBack );
  49410. enable( gl.CULL_FACE );
  49411. setBlending( NoBlending );
  49412. //
  49413. function enable( id ) {
  49414. if ( enabledCapabilities[ id ] !== true ) {
  49415. gl.enable( id );
  49416. enabledCapabilities[ id ] = true;
  49417. }
  49418. }
  49419. function disable( id ) {
  49420. if ( enabledCapabilities[ id ] !== false ) {
  49421. gl.disable( id );
  49422. enabledCapabilities[ id ] = false;
  49423. }
  49424. }
  49425. function bindFramebuffer( target, framebuffer ) {
  49426. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  49427. gl.bindFramebuffer( target, framebuffer );
  49428. currentBoundFramebuffers[ target ] = framebuffer;
  49429. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  49430. if ( target === gl.DRAW_FRAMEBUFFER ) {
  49431. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  49432. }
  49433. if ( target === gl.FRAMEBUFFER ) {
  49434. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  49435. }
  49436. return true;
  49437. }
  49438. return false;
  49439. }
  49440. function drawBuffers( renderTarget, framebuffer ) {
  49441. let drawBuffers = defaultDrawbuffers;
  49442. let needsUpdate = false;
  49443. if ( renderTarget ) {
  49444. drawBuffers = currentDrawbuffers.get( framebuffer );
  49445. if ( drawBuffers === undefined ) {
  49446. drawBuffers = [];
  49447. currentDrawbuffers.set( framebuffer, drawBuffers );
  49448. }
  49449. const textures = renderTarget.textures;
  49450. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  49451. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49452. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  49453. }
  49454. drawBuffers.length = textures.length;
  49455. needsUpdate = true;
  49456. }
  49457. } else {
  49458. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  49459. drawBuffers[ 0 ] = gl.BACK;
  49460. needsUpdate = true;
  49461. }
  49462. }
  49463. if ( needsUpdate ) {
  49464. gl.drawBuffers( drawBuffers );
  49465. }
  49466. }
  49467. function useProgram( program ) {
  49468. if ( currentProgram !== program ) {
  49469. gl.useProgram( program );
  49470. currentProgram = program;
  49471. return true;
  49472. }
  49473. return false;
  49474. }
  49475. const equationToGL = {
  49476. [ AddEquation ]: gl.FUNC_ADD,
  49477. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  49478. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  49479. };
  49480. equationToGL[ MinEquation ] = gl.MIN;
  49481. equationToGL[ MaxEquation ] = gl.MAX;
  49482. const factorToGL = {
  49483. [ ZeroFactor ]: gl.ZERO,
  49484. [ OneFactor ]: gl.ONE,
  49485. [ SrcColorFactor ]: gl.SRC_COLOR,
  49486. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  49487. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  49488. [ DstColorFactor ]: gl.DST_COLOR,
  49489. [ DstAlphaFactor ]: gl.DST_ALPHA,
  49490. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  49491. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  49492. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  49493. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  49494. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  49495. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  49496. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  49497. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  49498. };
  49499. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  49500. if ( blending === NoBlending ) {
  49501. if ( currentBlendingEnabled === true ) {
  49502. disable( gl.BLEND );
  49503. currentBlendingEnabled = false;
  49504. }
  49505. return;
  49506. }
  49507. if ( currentBlendingEnabled === false ) {
  49508. enable( gl.BLEND );
  49509. currentBlendingEnabled = true;
  49510. }
  49511. if ( blending !== CustomBlending ) {
  49512. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  49513. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  49514. gl.blendEquation( gl.FUNC_ADD );
  49515. currentBlendEquation = AddEquation;
  49516. currentBlendEquationAlpha = AddEquation;
  49517. }
  49518. if ( premultipliedAlpha ) {
  49519. switch ( blending ) {
  49520. case NormalBlending:
  49521. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49522. break;
  49523. case AdditiveBlending:
  49524. gl.blendFunc( gl.ONE, gl.ONE );
  49525. break;
  49526. case SubtractiveBlending:
  49527. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  49528. break;
  49529. case MultiplyBlending:
  49530. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  49531. break;
  49532. default:
  49533. error( 'WebGLState: Invalid blending: ', blending );
  49534. break;
  49535. }
  49536. } else {
  49537. switch ( blending ) {
  49538. case NormalBlending:
  49539. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49540. break;
  49541. case AdditiveBlending:
  49542. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  49543. break;
  49544. case SubtractiveBlending:
  49545. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49546. break;
  49547. case MultiplyBlending:
  49548. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  49549. break;
  49550. default:
  49551. error( 'WebGLState: Invalid blending: ', blending );
  49552. break;
  49553. }
  49554. }
  49555. currentBlendSrc = null;
  49556. currentBlendDst = null;
  49557. currentBlendSrcAlpha = null;
  49558. currentBlendDstAlpha = null;
  49559. currentBlendColor.set( 0, 0, 0 );
  49560. currentBlendAlpha = 0;
  49561. currentBlending = blending;
  49562. currentPremultipledAlpha = premultipliedAlpha;
  49563. }
  49564. return;
  49565. }
  49566. // custom blending
  49567. blendEquationAlpha = blendEquationAlpha || blendEquation;
  49568. blendSrcAlpha = blendSrcAlpha || blendSrc;
  49569. blendDstAlpha = blendDstAlpha || blendDst;
  49570. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  49571. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  49572. currentBlendEquation = blendEquation;
  49573. currentBlendEquationAlpha = blendEquationAlpha;
  49574. }
  49575. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  49576. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  49577. currentBlendSrc = blendSrc;
  49578. currentBlendDst = blendDst;
  49579. currentBlendSrcAlpha = blendSrcAlpha;
  49580. currentBlendDstAlpha = blendDstAlpha;
  49581. }
  49582. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  49583. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  49584. currentBlendColor.copy( blendColor );
  49585. currentBlendAlpha = blendAlpha;
  49586. }
  49587. currentBlending = blending;
  49588. currentPremultipledAlpha = false;
  49589. }
  49590. function setMaterial( material, frontFaceCW ) {
  49591. material.side === DoubleSide
  49592. ? disable( gl.CULL_FACE )
  49593. : enable( gl.CULL_FACE );
  49594. let flipSided = ( material.side === BackSide );
  49595. if ( frontFaceCW ) flipSided = ! flipSided;
  49596. setFlipSided( flipSided );
  49597. ( material.blending === NormalBlending && material.transparent === false )
  49598. ? setBlending( NoBlending )
  49599. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  49600. depthBuffer.setFunc( material.depthFunc );
  49601. depthBuffer.setTest( material.depthTest );
  49602. depthBuffer.setMask( material.depthWrite );
  49603. colorBuffer.setMask( material.colorWrite );
  49604. const stencilWrite = material.stencilWrite;
  49605. stencilBuffer.setTest( stencilWrite );
  49606. if ( stencilWrite ) {
  49607. stencilBuffer.setMask( material.stencilWriteMask );
  49608. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  49609. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  49610. }
  49611. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  49612. material.alphaToCoverage === true
  49613. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  49614. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49615. }
  49616. //
  49617. function setFlipSided( flipSided ) {
  49618. if ( currentFlipSided !== flipSided ) {
  49619. if ( flipSided ) {
  49620. gl.frontFace( gl.CW );
  49621. } else {
  49622. gl.frontFace( gl.CCW );
  49623. }
  49624. currentFlipSided = flipSided;
  49625. }
  49626. }
  49627. function setCullFace( cullFace ) {
  49628. if ( cullFace !== CullFaceNone ) {
  49629. enable( gl.CULL_FACE );
  49630. if ( cullFace !== currentCullFace ) {
  49631. if ( cullFace === CullFaceBack ) {
  49632. gl.cullFace( gl.BACK );
  49633. } else if ( cullFace === CullFaceFront ) {
  49634. gl.cullFace( gl.FRONT );
  49635. } else {
  49636. gl.cullFace( gl.FRONT_AND_BACK );
  49637. }
  49638. }
  49639. } else {
  49640. disable( gl.CULL_FACE );
  49641. }
  49642. currentCullFace = cullFace;
  49643. }
  49644. function setLineWidth( width ) {
  49645. if ( width !== currentLineWidth ) {
  49646. if ( lineWidthAvailable ) gl.lineWidth( width );
  49647. currentLineWidth = width;
  49648. }
  49649. }
  49650. function setPolygonOffset( polygonOffset, factor, units ) {
  49651. if ( polygonOffset ) {
  49652. enable( gl.POLYGON_OFFSET_FILL );
  49653. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  49654. currentPolygonOffsetFactor = factor;
  49655. currentPolygonOffsetUnits = units;
  49656. if ( depthBuffer.getReversed() ) {
  49657. factor = - factor;
  49658. }
  49659. gl.polygonOffset( factor, units );
  49660. }
  49661. } else {
  49662. disable( gl.POLYGON_OFFSET_FILL );
  49663. }
  49664. }
  49665. function setScissorTest( scissorTest ) {
  49666. if ( scissorTest ) {
  49667. enable( gl.SCISSOR_TEST );
  49668. } else {
  49669. disable( gl.SCISSOR_TEST );
  49670. }
  49671. }
  49672. // texture
  49673. function activeTexture( webglSlot ) {
  49674. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49675. if ( currentTextureSlot !== webglSlot ) {
  49676. gl.activeTexture( webglSlot );
  49677. currentTextureSlot = webglSlot;
  49678. }
  49679. }
  49680. function bindTexture( webglType, webglTexture, webglSlot ) {
  49681. if ( webglSlot === undefined ) {
  49682. if ( currentTextureSlot === null ) {
  49683. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49684. } else {
  49685. webglSlot = currentTextureSlot;
  49686. }
  49687. }
  49688. let boundTexture = currentBoundTextures[ webglSlot ];
  49689. if ( boundTexture === undefined ) {
  49690. boundTexture = { type: undefined, texture: undefined };
  49691. currentBoundTextures[ webglSlot ] = boundTexture;
  49692. }
  49693. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49694. if ( currentTextureSlot !== webglSlot ) {
  49695. gl.activeTexture( webglSlot );
  49696. currentTextureSlot = webglSlot;
  49697. }
  49698. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49699. boundTexture.type = webglType;
  49700. boundTexture.texture = webglTexture;
  49701. }
  49702. }
  49703. function unbindTexture() {
  49704. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49705. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49706. gl.bindTexture( boundTexture.type, null );
  49707. boundTexture.type = undefined;
  49708. boundTexture.texture = undefined;
  49709. }
  49710. }
  49711. function compressedTexImage2D() {
  49712. try {
  49713. gl.compressedTexImage2D( ...arguments );
  49714. } catch ( e ) {
  49715. error( 'WebGLState:', e );
  49716. }
  49717. }
  49718. function compressedTexImage3D() {
  49719. try {
  49720. gl.compressedTexImage3D( ...arguments );
  49721. } catch ( e ) {
  49722. error( 'WebGLState:', e );
  49723. }
  49724. }
  49725. function texSubImage2D() {
  49726. try {
  49727. gl.texSubImage2D( ...arguments );
  49728. } catch ( e ) {
  49729. error( 'WebGLState:', e );
  49730. }
  49731. }
  49732. function texSubImage3D() {
  49733. try {
  49734. gl.texSubImage3D( ...arguments );
  49735. } catch ( e ) {
  49736. error( 'WebGLState:', e );
  49737. }
  49738. }
  49739. function compressedTexSubImage2D() {
  49740. try {
  49741. gl.compressedTexSubImage2D( ...arguments );
  49742. } catch ( e ) {
  49743. error( 'WebGLState:', e );
  49744. }
  49745. }
  49746. function compressedTexSubImage3D() {
  49747. try {
  49748. gl.compressedTexSubImage3D( ...arguments );
  49749. } catch ( e ) {
  49750. error( 'WebGLState:', e );
  49751. }
  49752. }
  49753. function texStorage2D() {
  49754. try {
  49755. gl.texStorage2D( ...arguments );
  49756. } catch ( e ) {
  49757. error( 'WebGLState:', e );
  49758. }
  49759. }
  49760. function texStorage3D() {
  49761. try {
  49762. gl.texStorage3D( ...arguments );
  49763. } catch ( e ) {
  49764. error( 'WebGLState:', e );
  49765. }
  49766. }
  49767. function texImage2D() {
  49768. try {
  49769. gl.texImage2D( ...arguments );
  49770. } catch ( e ) {
  49771. error( 'WebGLState:', e );
  49772. }
  49773. }
  49774. function texImage3D() {
  49775. try {
  49776. gl.texImage3D( ...arguments );
  49777. } catch ( e ) {
  49778. error( 'WebGLState:', e );
  49779. }
  49780. }
  49781. //
  49782. function scissor( scissor ) {
  49783. if ( currentScissor.equals( scissor ) === false ) {
  49784. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49785. currentScissor.copy( scissor );
  49786. }
  49787. }
  49788. function viewport( viewport ) {
  49789. if ( currentViewport.equals( viewport ) === false ) {
  49790. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49791. currentViewport.copy( viewport );
  49792. }
  49793. }
  49794. function updateUBOMapping( uniformsGroup, program ) {
  49795. let mapping = uboProgramMap.get( program );
  49796. if ( mapping === undefined ) {
  49797. mapping = new WeakMap();
  49798. uboProgramMap.set( program, mapping );
  49799. }
  49800. let blockIndex = mapping.get( uniformsGroup );
  49801. if ( blockIndex === undefined ) {
  49802. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49803. mapping.set( uniformsGroup, blockIndex );
  49804. }
  49805. }
  49806. function uniformBlockBinding( uniformsGroup, program ) {
  49807. const mapping = uboProgramMap.get( program );
  49808. const blockIndex = mapping.get( uniformsGroup );
  49809. if ( uboBindings.get( program ) !== blockIndex ) {
  49810. // bind shader specific block index to global block point
  49811. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49812. uboBindings.set( program, blockIndex );
  49813. }
  49814. }
  49815. //
  49816. function reset() {
  49817. // reset state
  49818. gl.disable( gl.BLEND );
  49819. gl.disable( gl.CULL_FACE );
  49820. gl.disable( gl.DEPTH_TEST );
  49821. gl.disable( gl.POLYGON_OFFSET_FILL );
  49822. gl.disable( gl.SCISSOR_TEST );
  49823. gl.disable( gl.STENCIL_TEST );
  49824. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49825. gl.blendEquation( gl.FUNC_ADD );
  49826. gl.blendFunc( gl.ONE, gl.ZERO );
  49827. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49828. gl.blendColor( 0, 0, 0, 0 );
  49829. gl.colorMask( true, true, true, true );
  49830. gl.clearColor( 0, 0, 0, 0 );
  49831. gl.depthMask( true );
  49832. gl.depthFunc( gl.LESS );
  49833. depthBuffer.setReversed( false );
  49834. gl.clearDepth( 1 );
  49835. gl.stencilMask( 0xffffffff );
  49836. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49837. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49838. gl.clearStencil( 0 );
  49839. gl.cullFace( gl.BACK );
  49840. gl.frontFace( gl.CCW );
  49841. gl.polygonOffset( 0, 0 );
  49842. gl.activeTexture( gl.TEXTURE0 );
  49843. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49844. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49845. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49846. gl.useProgram( null );
  49847. gl.lineWidth( 1 );
  49848. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49849. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49850. // reset internals
  49851. enabledCapabilities = {};
  49852. currentTextureSlot = null;
  49853. currentBoundTextures = {};
  49854. currentBoundFramebuffers = {};
  49855. currentDrawbuffers = new WeakMap();
  49856. defaultDrawbuffers = [];
  49857. currentProgram = null;
  49858. currentBlendingEnabled = false;
  49859. currentBlending = null;
  49860. currentBlendEquation = null;
  49861. currentBlendSrc = null;
  49862. currentBlendDst = null;
  49863. currentBlendEquationAlpha = null;
  49864. currentBlendSrcAlpha = null;
  49865. currentBlendDstAlpha = null;
  49866. currentBlendColor = new Color( 0, 0, 0 );
  49867. currentBlendAlpha = 0;
  49868. currentPremultipledAlpha = false;
  49869. currentFlipSided = null;
  49870. currentCullFace = null;
  49871. currentLineWidth = null;
  49872. currentPolygonOffsetFactor = null;
  49873. currentPolygonOffsetUnits = null;
  49874. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49875. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49876. colorBuffer.reset();
  49877. depthBuffer.reset();
  49878. stencilBuffer.reset();
  49879. }
  49880. return {
  49881. buffers: {
  49882. color: colorBuffer,
  49883. depth: depthBuffer,
  49884. stencil: stencilBuffer
  49885. },
  49886. enable: enable,
  49887. disable: disable,
  49888. bindFramebuffer: bindFramebuffer,
  49889. drawBuffers: drawBuffers,
  49890. useProgram: useProgram,
  49891. setBlending: setBlending,
  49892. setMaterial: setMaterial,
  49893. setFlipSided: setFlipSided,
  49894. setCullFace: setCullFace,
  49895. setLineWidth: setLineWidth,
  49896. setPolygonOffset: setPolygonOffset,
  49897. setScissorTest: setScissorTest,
  49898. activeTexture: activeTexture,
  49899. bindTexture: bindTexture,
  49900. unbindTexture: unbindTexture,
  49901. compressedTexImage2D: compressedTexImage2D,
  49902. compressedTexImage3D: compressedTexImage3D,
  49903. texImage2D: texImage2D,
  49904. texImage3D: texImage3D,
  49905. updateUBOMapping: updateUBOMapping,
  49906. uniformBlockBinding: uniformBlockBinding,
  49907. texStorage2D: texStorage2D,
  49908. texStorage3D: texStorage3D,
  49909. texSubImage2D: texSubImage2D,
  49910. texSubImage3D: texSubImage3D,
  49911. compressedTexSubImage2D: compressedTexSubImage2D,
  49912. compressedTexSubImage3D: compressedTexSubImage3D,
  49913. scissor: scissor,
  49914. viewport: viewport,
  49915. reset: reset
  49916. };
  49917. }
  49918. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49919. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49920. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49921. const _imageDimensions = new Vector2();
  49922. const _videoTextures = new WeakMap();
  49923. let _canvas;
  49924. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49925. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49926. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49927. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49928. let useOffscreenCanvas = false;
  49929. try {
  49930. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49931. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49932. } catch ( err ) {
  49933. // Ignore any errors
  49934. }
  49935. function createCanvas( width, height ) {
  49936. // Use OffscreenCanvas when available. Specially needed in web workers
  49937. return useOffscreenCanvas ?
  49938. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49939. }
  49940. function resizeImage( image, needsNewCanvas, maxSize ) {
  49941. let scale = 1;
  49942. const dimensions = getDimensions( image );
  49943. // handle case if texture exceeds max size
  49944. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49945. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49946. }
  49947. // only perform resize if necessary
  49948. if ( scale < 1 ) {
  49949. // only perform resize for certain image types
  49950. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49951. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49952. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49953. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49954. const width = Math.floor( scale * dimensions.width );
  49955. const height = Math.floor( scale * dimensions.height );
  49956. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49957. // cube textures can't reuse the same canvas
  49958. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49959. canvas.width = width;
  49960. canvas.height = height;
  49961. const context = canvas.getContext( '2d' );
  49962. context.drawImage( image, 0, 0, width, height );
  49963. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49964. return canvas;
  49965. } else {
  49966. if ( 'data' in image ) {
  49967. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49968. }
  49969. return image;
  49970. }
  49971. }
  49972. return image;
  49973. }
  49974. function textureNeedsGenerateMipmaps( texture ) {
  49975. return texture.generateMipmaps;
  49976. }
  49977. function generateMipmap( target ) {
  49978. _gl.generateMipmap( target );
  49979. }
  49980. function getTargetType( texture ) {
  49981. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49982. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49983. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49984. return _gl.TEXTURE_2D;
  49985. }
  49986. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49987. if ( internalFormatName !== null ) {
  49988. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49989. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49990. }
  49991. let internalFormat = glFormat;
  49992. if ( glFormat === _gl.RED ) {
  49993. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49994. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49995. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49996. }
  49997. if ( glFormat === _gl.RED_INTEGER ) {
  49998. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49999. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  50000. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  50001. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  50002. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  50003. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  50004. }
  50005. if ( glFormat === _gl.RG ) {
  50006. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  50007. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  50008. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  50009. }
  50010. if ( glFormat === _gl.RG_INTEGER ) {
  50011. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  50012. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  50013. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  50014. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  50015. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  50016. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  50017. }
  50018. if ( glFormat === _gl.RGB_INTEGER ) {
  50019. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  50020. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  50021. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  50022. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  50023. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  50024. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  50025. }
  50026. if ( glFormat === _gl.RGBA_INTEGER ) {
  50027. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  50028. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  50029. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  50030. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  50031. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  50032. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  50033. }
  50034. if ( glFormat === _gl.RGB ) {
  50035. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  50036. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  50037. }
  50038. if ( glFormat === _gl.RGBA ) {
  50039. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  50040. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  50041. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  50042. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  50043. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  50044. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  50045. }
  50046. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  50047. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  50048. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  50049. extensions.get( 'EXT_color_buffer_float' );
  50050. }
  50051. return internalFormat;
  50052. }
  50053. function getInternalDepthFormat( useStencil, depthType ) {
  50054. let glInternalFormat;
  50055. if ( useStencil ) {
  50056. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  50057. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50058. } else if ( depthType === FloatType ) {
  50059. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  50060. } else if ( depthType === UnsignedShortType ) {
  50061. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50062. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  50063. }
  50064. } else {
  50065. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  50066. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50067. } else if ( depthType === FloatType ) {
  50068. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  50069. } else if ( depthType === UnsignedShortType ) {
  50070. glInternalFormat = _gl.DEPTH_COMPONENT16;
  50071. }
  50072. }
  50073. return glInternalFormat;
  50074. }
  50075. function getMipLevels( texture, image ) {
  50076. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  50077. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  50078. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  50079. // user-defined mipmaps
  50080. return texture.mipmaps.length;
  50081. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  50082. return image.mipmaps.length;
  50083. } else {
  50084. // texture without mipmaps (only base level)
  50085. return 1;
  50086. }
  50087. }
  50088. //
  50089. function onTextureDispose( event ) {
  50090. const texture = event.target;
  50091. texture.removeEventListener( 'dispose', onTextureDispose );
  50092. deallocateTexture( texture );
  50093. if ( texture.isVideoTexture ) {
  50094. _videoTextures.delete( texture );
  50095. }
  50096. }
  50097. function onRenderTargetDispose( event ) {
  50098. const renderTarget = event.target;
  50099. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  50100. deallocateRenderTarget( renderTarget );
  50101. }
  50102. //
  50103. function deallocateTexture( texture ) {
  50104. const textureProperties = properties.get( texture );
  50105. if ( textureProperties.__webglInit === undefined ) return;
  50106. // check if it's necessary to remove the WebGLTexture object
  50107. const source = texture.source;
  50108. const webglTextures = _sources.get( source );
  50109. if ( webglTextures ) {
  50110. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  50111. webglTexture.usedTimes --;
  50112. // the WebGLTexture object is not used anymore, remove it
  50113. if ( webglTexture.usedTimes === 0 ) {
  50114. deleteTexture( texture );
  50115. }
  50116. // remove the weak map entry if no WebGLTexture uses the source anymore
  50117. if ( Object.keys( webglTextures ).length === 0 ) {
  50118. _sources.delete( source );
  50119. }
  50120. }
  50121. properties.remove( texture );
  50122. }
  50123. function deleteTexture( texture ) {
  50124. const textureProperties = properties.get( texture );
  50125. _gl.deleteTexture( textureProperties.__webglTexture );
  50126. const source = texture.source;
  50127. const webglTextures = _sources.get( source );
  50128. delete webglTextures[ textureProperties.__cacheKey ];
  50129. info.memory.textures --;
  50130. }
  50131. function deallocateRenderTarget( renderTarget ) {
  50132. const renderTargetProperties = properties.get( renderTarget );
  50133. if ( renderTarget.depthTexture ) {
  50134. renderTarget.depthTexture.dispose();
  50135. properties.remove( renderTarget.depthTexture );
  50136. }
  50137. if ( renderTarget.isWebGLCubeRenderTarget ) {
  50138. for ( let i = 0; i < 6; i ++ ) {
  50139. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  50140. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  50141. } else {
  50142. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  50143. }
  50144. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  50145. }
  50146. } else {
  50147. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  50148. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  50149. } else {
  50150. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  50151. }
  50152. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  50153. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  50154. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  50155. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  50156. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50157. }
  50158. }
  50159. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  50160. }
  50161. const textures = renderTarget.textures;
  50162. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50163. const attachmentProperties = properties.get( textures[ i ] );
  50164. if ( attachmentProperties.__webglTexture ) {
  50165. _gl.deleteTexture( attachmentProperties.__webglTexture );
  50166. info.memory.textures --;
  50167. }
  50168. properties.remove( textures[ i ] );
  50169. }
  50170. properties.remove( renderTarget );
  50171. }
  50172. //
  50173. let textureUnits = 0;
  50174. function resetTextureUnits() {
  50175. textureUnits = 0;
  50176. }
  50177. function allocateTextureUnit() {
  50178. const textureUnit = textureUnits;
  50179. if ( textureUnit >= capabilities.maxTextures ) {
  50180. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  50181. }
  50182. textureUnits += 1;
  50183. return textureUnit;
  50184. }
  50185. function getTextureCacheKey( texture ) {
  50186. const array = [];
  50187. array.push( texture.wrapS );
  50188. array.push( texture.wrapT );
  50189. array.push( texture.wrapR || 0 );
  50190. array.push( texture.magFilter );
  50191. array.push( texture.minFilter );
  50192. array.push( texture.anisotropy );
  50193. array.push( texture.internalFormat );
  50194. array.push( texture.format );
  50195. array.push( texture.type );
  50196. array.push( texture.generateMipmaps );
  50197. array.push( texture.premultiplyAlpha );
  50198. array.push( texture.flipY );
  50199. array.push( texture.unpackAlignment );
  50200. array.push( texture.colorSpace );
  50201. return array.join();
  50202. }
  50203. //
  50204. function setTexture2D( texture, slot ) {
  50205. const textureProperties = properties.get( texture );
  50206. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  50207. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50208. const image = texture.image;
  50209. if ( image === null ) {
  50210. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  50211. } else if ( image.complete === false ) {
  50212. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  50213. } else {
  50214. uploadTexture( textureProperties, texture, slot );
  50215. return;
  50216. }
  50217. } else if ( texture.isExternalTexture ) {
  50218. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  50219. }
  50220. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50221. }
  50222. function setTexture2DArray( texture, slot ) {
  50223. const textureProperties = properties.get( texture );
  50224. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50225. uploadTexture( textureProperties, texture, slot );
  50226. return;
  50227. } else if ( texture.isExternalTexture ) {
  50228. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  50229. }
  50230. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50231. }
  50232. function setTexture3D( texture, slot ) {
  50233. const textureProperties = properties.get( texture );
  50234. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50235. uploadTexture( textureProperties, texture, slot );
  50236. return;
  50237. }
  50238. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50239. }
  50240. function setTextureCube( texture, slot ) {
  50241. const textureProperties = properties.get( texture );
  50242. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50243. uploadCubeTexture( textureProperties, texture, slot );
  50244. return;
  50245. }
  50246. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50247. }
  50248. const wrappingToGL = {
  50249. [ RepeatWrapping ]: _gl.REPEAT,
  50250. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  50251. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  50252. };
  50253. const filterToGL = {
  50254. [ NearestFilter ]: _gl.NEAREST,
  50255. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  50256. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  50257. [ LinearFilter ]: _gl.LINEAR,
  50258. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  50259. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  50260. };
  50261. const compareToGL = {
  50262. [ NeverCompare ]: _gl.NEVER,
  50263. [ AlwaysCompare ]: _gl.ALWAYS,
  50264. [ LessCompare ]: _gl.LESS,
  50265. [ LessEqualCompare ]: _gl.LEQUAL,
  50266. [ EqualCompare ]: _gl.EQUAL,
  50267. [ GreaterEqualCompare ]: _gl.GEQUAL,
  50268. [ GreaterCompare ]: _gl.GREATER,
  50269. [ NotEqualCompare ]: _gl.NOTEQUAL
  50270. };
  50271. function setTextureParameters( textureType, texture ) {
  50272. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  50273. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  50274. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  50275. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  50276. }
  50277. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  50278. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  50279. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  50280. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  50281. }
  50282. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  50283. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  50284. if ( texture.compareFunction ) {
  50285. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  50286. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  50287. }
  50288. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  50289. if ( texture.magFilter === NearestFilter ) return;
  50290. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  50291. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  50292. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  50293. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  50294. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  50295. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  50296. }
  50297. }
  50298. }
  50299. function initTexture( textureProperties, texture ) {
  50300. let forceUpload = false;
  50301. if ( textureProperties.__webglInit === undefined ) {
  50302. textureProperties.__webglInit = true;
  50303. texture.addEventListener( 'dispose', onTextureDispose );
  50304. }
  50305. // create Source <-> WebGLTextures mapping if necessary
  50306. const source = texture.source;
  50307. let webglTextures = _sources.get( source );
  50308. if ( webglTextures === undefined ) {
  50309. webglTextures = {};
  50310. _sources.set( source, webglTextures );
  50311. }
  50312. // check if there is already a WebGLTexture object for the given texture parameters
  50313. const textureCacheKey = getTextureCacheKey( texture );
  50314. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  50315. // if not, create a new instance of WebGLTexture
  50316. if ( webglTextures[ textureCacheKey ] === undefined ) {
  50317. // create new entry
  50318. webglTextures[ textureCacheKey ] = {
  50319. texture: _gl.createTexture(),
  50320. usedTimes: 0
  50321. };
  50322. info.memory.textures ++;
  50323. // when a new instance of WebGLTexture was created, a texture upload is required
  50324. // even if the image contents are identical
  50325. forceUpload = true;
  50326. }
  50327. webglTextures[ textureCacheKey ].usedTimes ++;
  50328. // every time the texture cache key changes, it's necessary to check if an instance of
  50329. // WebGLTexture can be deleted in order to avoid a memory leak.
  50330. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  50331. if ( webglTexture !== undefined ) {
  50332. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  50333. if ( webglTexture.usedTimes === 0 ) {
  50334. deleteTexture( texture );
  50335. }
  50336. }
  50337. // store references to cache key and WebGLTexture object
  50338. textureProperties.__cacheKey = textureCacheKey;
  50339. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  50340. }
  50341. return forceUpload;
  50342. }
  50343. function getRow( index, rowLength, componentStride ) {
  50344. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  50345. }
  50346. function updateTexture( texture, image, glFormat, glType ) {
  50347. const componentStride = 4; // only RGBA supported
  50348. const updateRanges = texture.updateRanges;
  50349. if ( updateRanges.length === 0 ) {
  50350. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  50351. } else {
  50352. // Before applying update ranges, we merge any adjacent / overlapping
  50353. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  50354. // to performance improvements for applications which make heavy use of
  50355. // update ranges. Likely due to GPU command overhead.
  50356. //
  50357. // Note that to reduce garbage collection between frames, we merge the
  50358. // update ranges in-place. This is safe because this method will clear the
  50359. // update ranges once updated.
  50360. updateRanges.sort( ( a, b ) => a.start - b.start );
  50361. // To merge the update ranges in-place, we work from left to right in the
  50362. // existing updateRanges array, merging ranges. This may result in a final
  50363. // array which is smaller than the original. This index tracks the last
  50364. // index representing a merged range, any data after this index can be
  50365. // trimmed once the merge algorithm is completed.
  50366. let mergeIndex = 0;
  50367. for ( let i = 1; i < updateRanges.length; i ++ ) {
  50368. const previousRange = updateRanges[ mergeIndex ];
  50369. const range = updateRanges[ i ];
  50370. // Only merge if in the same row and overlapping/adjacent
  50371. const previousEnd = previousRange.start + previousRange.count;
  50372. const currentRow = getRow( range.start, image.width, componentStride );
  50373. const previousRow = getRow( previousRange.start, image.width, componentStride );
  50374. // We add one here to merge adjacent ranges. This is safe because ranges
  50375. // operate over positive integers.
  50376. if (
  50377. range.start <= previousEnd + 1 &&
  50378. currentRow === previousRow &&
  50379. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  50380. ) {
  50381. previousRange.count = Math.max(
  50382. previousRange.count,
  50383. range.start + range.count - previousRange.start
  50384. );
  50385. } else {
  50386. ++ mergeIndex;
  50387. updateRanges[ mergeIndex ] = range;
  50388. }
  50389. }
  50390. // Trim the array to only contain the merged ranges.
  50391. updateRanges.length = mergeIndex + 1;
  50392. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  50393. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  50394. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  50395. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  50396. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50397. const range = updateRanges[ i ];
  50398. const pixelStart = Math.floor( range.start / componentStride );
  50399. const pixelCount = Math.ceil( range.count / componentStride );
  50400. const x = pixelStart % image.width;
  50401. const y = Math.floor( pixelStart / image.width );
  50402. // Assumes update ranges refer to contiguous memory
  50403. const width = pixelCount;
  50404. const height = 1;
  50405. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  50406. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  50407. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  50408. }
  50409. texture.clearUpdateRanges();
  50410. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  50411. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  50412. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  50413. }
  50414. }
  50415. function uploadTexture( textureProperties, texture, slot ) {
  50416. let textureType = _gl.TEXTURE_2D;
  50417. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  50418. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  50419. const forceUpload = initTexture( textureProperties, texture );
  50420. const source = texture.source;
  50421. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50422. const sourceProperties = properties.get( source );
  50423. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50424. state.activeTexture( _gl.TEXTURE0 + slot );
  50425. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50426. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50427. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50428. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50429. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50430. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50431. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50432. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  50433. image = verifyColorSpace( texture, image );
  50434. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50435. const glType = utils.convert( texture.type );
  50436. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  50437. setTextureParameters( textureType, texture );
  50438. let mipmap;
  50439. const mipmaps = texture.mipmaps;
  50440. const useTexStorage = ( texture.isVideoTexture !== true );
  50441. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50442. const dataReady = source.dataReady;
  50443. const levels = getMipLevels( texture, image );
  50444. if ( texture.isDepthTexture ) {
  50445. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  50446. //
  50447. if ( allocateMemory ) {
  50448. if ( useTexStorage ) {
  50449. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  50450. } else {
  50451. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  50452. }
  50453. }
  50454. } else if ( texture.isDataTexture ) {
  50455. // use manually created mipmaps if available
  50456. // if there are no manual mipmaps
  50457. // set 0 level mipmap and then use GL to generate other mipmap levels
  50458. if ( mipmaps.length > 0 ) {
  50459. if ( useTexStorage && allocateMemory ) {
  50460. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50461. }
  50462. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50463. mipmap = mipmaps[ i ];
  50464. if ( useTexStorage ) {
  50465. if ( dataReady ) {
  50466. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50467. }
  50468. } else {
  50469. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50470. }
  50471. }
  50472. texture.generateMipmaps = false;
  50473. } else {
  50474. if ( useTexStorage ) {
  50475. if ( allocateMemory ) {
  50476. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50477. }
  50478. if ( dataReady ) {
  50479. updateTexture( texture, image, glFormat, glType );
  50480. }
  50481. } else {
  50482. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  50483. }
  50484. }
  50485. } else if ( texture.isCompressedTexture ) {
  50486. if ( texture.isCompressedArrayTexture ) {
  50487. if ( useTexStorage && allocateMemory ) {
  50488. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  50489. }
  50490. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50491. mipmap = mipmaps[ i ];
  50492. if ( texture.format !== RGBAFormat ) {
  50493. if ( glFormat !== null ) {
  50494. if ( useTexStorage ) {
  50495. if ( dataReady ) {
  50496. if ( texture.layerUpdates.size > 0 ) {
  50497. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  50498. for ( const layerIndex of texture.layerUpdates ) {
  50499. const layerData = mipmap.data.subarray(
  50500. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  50501. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  50502. );
  50503. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  50504. }
  50505. texture.clearLayerUpdates();
  50506. } else {
  50507. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  50508. }
  50509. }
  50510. } else {
  50511. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  50512. }
  50513. } else {
  50514. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50515. }
  50516. } else {
  50517. if ( useTexStorage ) {
  50518. if ( dataReady ) {
  50519. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  50520. }
  50521. } else {
  50522. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  50523. }
  50524. }
  50525. }
  50526. } else {
  50527. if ( useTexStorage && allocateMemory ) {
  50528. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50529. }
  50530. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50531. mipmap = mipmaps[ i ];
  50532. if ( texture.format !== RGBAFormat ) {
  50533. if ( glFormat !== null ) {
  50534. if ( useTexStorage ) {
  50535. if ( dataReady ) {
  50536. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50537. }
  50538. } else {
  50539. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50540. }
  50541. } else {
  50542. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50543. }
  50544. } else {
  50545. if ( useTexStorage ) {
  50546. if ( dataReady ) {
  50547. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50548. }
  50549. } else {
  50550. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50551. }
  50552. }
  50553. }
  50554. }
  50555. } else if ( texture.isDataArrayTexture ) {
  50556. if ( useTexStorage ) {
  50557. if ( allocateMemory ) {
  50558. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  50559. }
  50560. if ( dataReady ) {
  50561. if ( texture.layerUpdates.size > 0 ) {
  50562. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  50563. for ( const layerIndex of texture.layerUpdates ) {
  50564. const layerData = image.data.subarray(
  50565. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  50566. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  50567. );
  50568. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  50569. }
  50570. texture.clearLayerUpdates();
  50571. } else {
  50572. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50573. }
  50574. }
  50575. } else {
  50576. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50577. }
  50578. } else if ( texture.isData3DTexture ) {
  50579. if ( useTexStorage ) {
  50580. if ( allocateMemory ) {
  50581. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  50582. }
  50583. if ( dataReady ) {
  50584. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50585. }
  50586. } else {
  50587. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50588. }
  50589. } else if ( texture.isFramebufferTexture ) {
  50590. if ( allocateMemory ) {
  50591. if ( useTexStorage ) {
  50592. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50593. } else {
  50594. let width = image.width, height = image.height;
  50595. for ( let i = 0; i < levels; i ++ ) {
  50596. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  50597. width >>= 1;
  50598. height >>= 1;
  50599. }
  50600. }
  50601. }
  50602. } else {
  50603. // regular Texture (image, video, canvas)
  50604. // use manually created mipmaps if available
  50605. // if there are no manual mipmaps
  50606. // set 0 level mipmap and then use GL to generate other mipmap levels
  50607. if ( mipmaps.length > 0 ) {
  50608. if ( useTexStorage && allocateMemory ) {
  50609. const dimensions = getDimensions( mipmaps[ 0 ] );
  50610. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50611. }
  50612. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50613. mipmap = mipmaps[ i ];
  50614. if ( useTexStorage ) {
  50615. if ( dataReady ) {
  50616. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  50617. }
  50618. } else {
  50619. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  50620. }
  50621. }
  50622. texture.generateMipmaps = false;
  50623. } else {
  50624. if ( useTexStorage ) {
  50625. if ( allocateMemory ) {
  50626. const dimensions = getDimensions( image );
  50627. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50628. }
  50629. if ( dataReady ) {
  50630. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  50631. }
  50632. } else {
  50633. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  50634. }
  50635. }
  50636. }
  50637. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50638. generateMipmap( textureType );
  50639. }
  50640. sourceProperties.__version = source.version;
  50641. if ( texture.onUpdate ) texture.onUpdate( texture );
  50642. }
  50643. textureProperties.__version = texture.version;
  50644. }
  50645. function uploadCubeTexture( textureProperties, texture, slot ) {
  50646. if ( texture.image.length !== 6 ) return;
  50647. const forceUpload = initTexture( textureProperties, texture );
  50648. const source = texture.source;
  50649. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50650. const sourceProperties = properties.get( source );
  50651. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50652. state.activeTexture( _gl.TEXTURE0 + slot );
  50653. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50654. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50655. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50656. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50657. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50658. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50659. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50660. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  50661. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  50662. const cubeImage = [];
  50663. for ( let i = 0; i < 6; i ++ ) {
  50664. if ( ! isCompressed && ! isDataTexture ) {
  50665. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50666. } else {
  50667. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50668. }
  50669. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50670. }
  50671. const image = cubeImage[ 0 ],
  50672. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50673. glType = utils.convert( texture.type ),
  50674. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50675. const useTexStorage = ( texture.isVideoTexture !== true );
  50676. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50677. const dataReady = source.dataReady;
  50678. let levels = getMipLevels( texture, image );
  50679. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50680. let mipmaps;
  50681. if ( isCompressed ) {
  50682. if ( useTexStorage && allocateMemory ) {
  50683. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50684. }
  50685. for ( let i = 0; i < 6; i ++ ) {
  50686. mipmaps = cubeImage[ i ].mipmaps;
  50687. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50688. const mipmap = mipmaps[ j ];
  50689. if ( texture.format !== RGBAFormat ) {
  50690. if ( glFormat !== null ) {
  50691. if ( useTexStorage ) {
  50692. if ( dataReady ) {
  50693. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50694. }
  50695. } else {
  50696. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50697. }
  50698. } else {
  50699. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50700. }
  50701. } else {
  50702. if ( useTexStorage ) {
  50703. if ( dataReady ) {
  50704. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50705. }
  50706. } else {
  50707. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50708. }
  50709. }
  50710. }
  50711. }
  50712. } else {
  50713. mipmaps = texture.mipmaps;
  50714. if ( useTexStorage && allocateMemory ) {
  50715. // TODO: Uniformly handle mipmap definitions
  50716. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50717. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50718. if ( mipmaps.length > 0 ) levels ++;
  50719. const dimensions = getDimensions( cubeImage[ 0 ] );
  50720. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50721. }
  50722. for ( let i = 0; i < 6; i ++ ) {
  50723. if ( isDataTexture ) {
  50724. if ( useTexStorage ) {
  50725. if ( dataReady ) {
  50726. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50727. }
  50728. } else {
  50729. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50730. }
  50731. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50732. const mipmap = mipmaps[ j ];
  50733. const mipmapImage = mipmap.image[ i ].image;
  50734. if ( useTexStorage ) {
  50735. if ( dataReady ) {
  50736. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50737. }
  50738. } else {
  50739. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50740. }
  50741. }
  50742. } else {
  50743. if ( useTexStorage ) {
  50744. if ( dataReady ) {
  50745. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50746. }
  50747. } else {
  50748. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50749. }
  50750. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50751. const mipmap = mipmaps[ j ];
  50752. if ( useTexStorage ) {
  50753. if ( dataReady ) {
  50754. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50755. }
  50756. } else {
  50757. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50758. }
  50759. }
  50760. }
  50761. }
  50762. }
  50763. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50764. // We assume images for cube map have the same size.
  50765. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50766. }
  50767. sourceProperties.__version = source.version;
  50768. if ( texture.onUpdate ) texture.onUpdate( texture );
  50769. }
  50770. textureProperties.__version = texture.version;
  50771. }
  50772. // Render targets
  50773. // Setup storage for target texture and bind it to correct framebuffer
  50774. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50775. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50776. const glType = utils.convert( texture.type );
  50777. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50778. const renderTargetProperties = properties.get( renderTarget );
  50779. const textureProperties = properties.get( texture );
  50780. textureProperties.__renderTarget = renderTarget;
  50781. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50782. const width = Math.max( 1, renderTarget.width >> level );
  50783. const height = Math.max( 1, renderTarget.height >> level );
  50784. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50785. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50786. } else {
  50787. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50788. }
  50789. }
  50790. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50791. if ( useMultisampledRTT( renderTarget ) ) {
  50792. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50793. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50794. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50795. }
  50796. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50797. }
  50798. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50799. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  50800. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50801. if ( renderTarget.depthBuffer ) {
  50802. // retrieve the depth attachment types
  50803. const depthTexture = renderTarget.depthTexture;
  50804. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50805. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50806. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50807. // set up the attachment
  50808. if ( useMultisampledRTT( renderTarget ) ) {
  50809. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50810. } else if ( useMultisample ) {
  50811. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50812. } else {
  50813. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50814. }
  50815. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50816. } else {
  50817. const textures = renderTarget.textures;
  50818. for ( let i = 0; i < textures.length; i ++ ) {
  50819. const texture = textures[ i ];
  50820. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50821. const glType = utils.convert( texture.type );
  50822. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50823. if ( useMultisampledRTT( renderTarget ) ) {
  50824. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50825. } else if ( useMultisample ) {
  50826. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50827. } else {
  50828. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50829. }
  50830. }
  50831. }
  50832. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50833. }
  50834. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50835. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50836. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50837. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50838. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50839. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50840. }
  50841. const textureProperties = properties.get( renderTarget.depthTexture );
  50842. textureProperties.__renderTarget = renderTarget;
  50843. // upload an empty depth texture with framebuffer size
  50844. if ( ! textureProperties.__webglTexture ||
  50845. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50846. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50847. renderTarget.depthTexture.image.width = renderTarget.width;
  50848. renderTarget.depthTexture.image.height = renderTarget.height;
  50849. renderTarget.depthTexture.needsUpdate = true;
  50850. }
  50851. if ( isCube ) {
  50852. // For cube depth textures, initialize and bind without uploading image data
  50853. if ( textureProperties.__webglInit === undefined ) {
  50854. textureProperties.__webglInit = true;
  50855. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50856. }
  50857. // Only create and allocate storage once
  50858. if ( textureProperties.__webglTexture === undefined ) {
  50859. textureProperties.__webglTexture = _gl.createTexture();
  50860. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50861. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50862. // Allocate storage for all 6 faces with correct depth texture format
  50863. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50864. const glType = utils.convert( renderTarget.depthTexture.type );
  50865. // Use proper internal format for depth textures
  50866. let glInternalFormat;
  50867. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50868. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50869. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50870. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50871. }
  50872. for ( let i = 0; i < 6; i ++ ) {
  50873. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50874. }
  50875. }
  50876. } else {
  50877. setTexture2D( renderTarget.depthTexture, 0 );
  50878. }
  50879. const webglDepthTexture = textureProperties.__webglTexture;
  50880. const samples = getRenderTargetSamples( renderTarget );
  50881. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50882. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50883. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50884. if ( useMultisampledRTT( renderTarget ) ) {
  50885. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50886. } else {
  50887. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50888. }
  50889. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50890. if ( useMultisampledRTT( renderTarget ) ) {
  50891. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50892. } else {
  50893. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50894. }
  50895. } else {
  50896. throw new Error( 'Unknown depthTexture format' );
  50897. }
  50898. }
  50899. // Setup GL resources for a non-texture depth buffer
  50900. function setupDepthRenderbuffer( renderTarget ) {
  50901. const renderTargetProperties = properties.get( renderTarget );
  50902. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50903. // if the bound depth texture has changed
  50904. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50905. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50906. const depthTexture = renderTarget.depthTexture;
  50907. if ( renderTargetProperties.__depthDisposeCallback ) {
  50908. renderTargetProperties.__depthDisposeCallback();
  50909. }
  50910. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50911. if ( depthTexture ) {
  50912. const disposeEvent = () => {
  50913. delete renderTargetProperties.__boundDepthTexture;
  50914. delete renderTargetProperties.__depthDisposeCallback;
  50915. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50916. };
  50917. depthTexture.addEventListener( 'dispose', disposeEvent );
  50918. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50919. }
  50920. renderTargetProperties.__boundDepthTexture = depthTexture;
  50921. }
  50922. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50923. if ( isCube ) {
  50924. // For cube render targets with depth texture, setup each face
  50925. for ( let i = 0; i < 6; i ++ ) {
  50926. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50927. }
  50928. } else {
  50929. const mipmaps = renderTarget.texture.mipmaps;
  50930. if ( mipmaps && mipmaps.length > 0 ) {
  50931. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50932. } else {
  50933. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50934. }
  50935. }
  50936. } else {
  50937. if ( isCube ) {
  50938. renderTargetProperties.__webglDepthbuffer = [];
  50939. for ( let i = 0; i < 6; i ++ ) {
  50940. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50941. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50942. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50943. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50944. } else {
  50945. // attach buffer if it's been created already
  50946. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50947. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50948. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50949. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50950. }
  50951. }
  50952. } else {
  50953. const mipmaps = renderTarget.texture.mipmaps;
  50954. if ( mipmaps && mipmaps.length > 0 ) {
  50955. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50956. } else {
  50957. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50958. }
  50959. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50960. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50961. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50962. } else {
  50963. // attach buffer if it's been created already
  50964. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50965. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50966. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50967. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50968. }
  50969. }
  50970. }
  50971. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50972. }
  50973. // rebind framebuffer with external textures
  50974. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50975. const renderTargetProperties = properties.get( renderTarget );
  50976. if ( colorTexture !== undefined ) {
  50977. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50978. }
  50979. if ( depthTexture !== undefined ) {
  50980. setupDepthRenderbuffer( renderTarget );
  50981. }
  50982. }
  50983. // Set up GL resources for the render target
  50984. function setupRenderTarget( renderTarget ) {
  50985. const texture = renderTarget.texture;
  50986. const renderTargetProperties = properties.get( renderTarget );
  50987. const textureProperties = properties.get( texture );
  50988. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50989. const textures = renderTarget.textures;
  50990. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50991. const isMultipleRenderTargets = ( textures.length > 1 );
  50992. if ( ! isMultipleRenderTargets ) {
  50993. if ( textureProperties.__webglTexture === undefined ) {
  50994. textureProperties.__webglTexture = _gl.createTexture();
  50995. }
  50996. textureProperties.__version = texture.version;
  50997. info.memory.textures ++;
  50998. }
  50999. // Setup framebuffer
  51000. if ( isCube ) {
  51001. renderTargetProperties.__webglFramebuffer = [];
  51002. for ( let i = 0; i < 6; i ++ ) {
  51003. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  51004. renderTargetProperties.__webglFramebuffer[ i ] = [];
  51005. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  51006. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  51007. }
  51008. } else {
  51009. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  51010. }
  51011. }
  51012. } else {
  51013. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  51014. renderTargetProperties.__webglFramebuffer = [];
  51015. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  51016. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  51017. }
  51018. } else {
  51019. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  51020. }
  51021. if ( isMultipleRenderTargets ) {
  51022. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  51023. const attachmentProperties = properties.get( textures[ i ] );
  51024. if ( attachmentProperties.__webglTexture === undefined ) {
  51025. attachmentProperties.__webglTexture = _gl.createTexture();
  51026. info.memory.textures ++;
  51027. }
  51028. }
  51029. }
  51030. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  51031. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  51032. renderTargetProperties.__webglColorRenderbuffer = [];
  51033. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51034. for ( let i = 0; i < textures.length; i ++ ) {
  51035. const texture = textures[ i ];
  51036. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  51037. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  51038. const glFormat = utils.convert( texture.format, texture.colorSpace );
  51039. const glType = utils.convert( texture.type );
  51040. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  51041. const samples = getRenderTargetSamples( renderTarget );
  51042. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  51043. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  51044. }
  51045. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  51046. if ( renderTarget.depthBuffer ) {
  51047. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  51048. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  51049. }
  51050. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  51051. }
  51052. }
  51053. // Setup color buffer
  51054. if ( isCube ) {
  51055. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  51056. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  51057. for ( let i = 0; i < 6; i ++ ) {
  51058. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  51059. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  51060. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  51061. }
  51062. } else {
  51063. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  51064. }
  51065. }
  51066. if ( textureNeedsGenerateMipmaps( texture ) ) {
  51067. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  51068. }
  51069. state.unbindTexture();
  51070. } else if ( isMultipleRenderTargets ) {
  51071. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  51072. const attachment = textures[ i ];
  51073. const attachmentProperties = properties.get( attachment );
  51074. let glTextureType = _gl.TEXTURE_2D;
  51075. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  51076. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  51077. }
  51078. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  51079. setTextureParameters( glTextureType, attachment );
  51080. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  51081. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  51082. generateMipmap( glTextureType );
  51083. }
  51084. }
  51085. state.unbindTexture();
  51086. } else {
  51087. let glTextureType = _gl.TEXTURE_2D;
  51088. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  51089. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  51090. }
  51091. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  51092. setTextureParameters( glTextureType, texture );
  51093. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  51094. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  51095. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  51096. }
  51097. } else {
  51098. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  51099. }
  51100. if ( textureNeedsGenerateMipmaps( texture ) ) {
  51101. generateMipmap( glTextureType );
  51102. }
  51103. state.unbindTexture();
  51104. }
  51105. // Setup depth and stencil buffers
  51106. if ( renderTarget.depthBuffer ) {
  51107. setupDepthRenderbuffer( renderTarget );
  51108. }
  51109. }
  51110. function updateRenderTargetMipmap( renderTarget ) {
  51111. const textures = renderTarget.textures;
  51112. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  51113. const texture = textures[ i ];
  51114. if ( textureNeedsGenerateMipmaps( texture ) ) {
  51115. const targetType = getTargetType( renderTarget );
  51116. const webglTexture = properties.get( texture ).__webglTexture;
  51117. state.bindTexture( targetType, webglTexture );
  51118. generateMipmap( targetType );
  51119. state.unbindTexture();
  51120. }
  51121. }
  51122. }
  51123. const invalidationArrayRead = [];
  51124. const invalidationArrayDraw = [];
  51125. function updateMultisampleRenderTarget( renderTarget ) {
  51126. if ( renderTarget.samples > 0 ) {
  51127. if ( useMultisampledRTT( renderTarget ) === false ) {
  51128. const textures = renderTarget.textures;
  51129. const width = renderTarget.width;
  51130. const height = renderTarget.height;
  51131. let mask = _gl.COLOR_BUFFER_BIT;
  51132. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  51133. const renderTargetProperties = properties.get( renderTarget );
  51134. const isMultipleRenderTargets = ( textures.length > 1 );
  51135. // If MRT we need to remove FBO attachments
  51136. if ( isMultipleRenderTargets ) {
  51137. for ( let i = 0; i < textures.length; i ++ ) {
  51138. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51139. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  51140. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  51141. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  51142. }
  51143. }
  51144. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51145. const mipmaps = renderTarget.texture.mipmaps;
  51146. if ( mipmaps && mipmaps.length > 0 ) {
  51147. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  51148. } else {
  51149. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  51150. }
  51151. for ( let i = 0; i < textures.length; i ++ ) {
  51152. if ( renderTarget.resolveDepthBuffer ) {
  51153. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  51154. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  51155. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  51156. }
  51157. if ( isMultipleRenderTargets ) {
  51158. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  51159. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  51160. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  51161. }
  51162. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  51163. if ( supportsInvalidateFramebuffer === true ) {
  51164. invalidationArrayRead.length = 0;
  51165. invalidationArrayDraw.length = 0;
  51166. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  51167. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  51168. invalidationArrayRead.push( depthStyle );
  51169. invalidationArrayDraw.push( depthStyle );
  51170. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  51171. }
  51172. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  51173. }
  51174. }
  51175. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  51176. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  51177. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  51178. if ( isMultipleRenderTargets ) {
  51179. for ( let i = 0; i < textures.length; i ++ ) {
  51180. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51181. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  51182. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  51183. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  51184. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  51185. }
  51186. }
  51187. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51188. } else {
  51189. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  51190. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  51191. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  51192. }
  51193. }
  51194. }
  51195. }
  51196. function getRenderTargetSamples( renderTarget ) {
  51197. return Math.min( capabilities.maxSamples, renderTarget.samples );
  51198. }
  51199. function useMultisampledRTT( renderTarget ) {
  51200. const renderTargetProperties = properties.get( renderTarget );
  51201. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  51202. }
  51203. function updateVideoTexture( texture ) {
  51204. const frame = info.render.frame;
  51205. // Check the last frame we updated the VideoTexture
  51206. if ( _videoTextures.get( texture ) !== frame ) {
  51207. _videoTextures.set( texture, frame );
  51208. texture.update();
  51209. }
  51210. }
  51211. function verifyColorSpace( texture, image ) {
  51212. const colorSpace = texture.colorSpace;
  51213. const format = texture.format;
  51214. const type = texture.type;
  51215. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  51216. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  51217. // sRGB
  51218. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  51219. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  51220. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  51221. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  51222. }
  51223. } else {
  51224. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  51225. }
  51226. }
  51227. return image;
  51228. }
  51229. function getDimensions( image ) {
  51230. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  51231. // if intrinsic data are not available, fallback to width/height
  51232. _imageDimensions.width = image.naturalWidth || image.width;
  51233. _imageDimensions.height = image.naturalHeight || image.height;
  51234. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  51235. _imageDimensions.width = image.displayWidth;
  51236. _imageDimensions.height = image.displayHeight;
  51237. } else {
  51238. _imageDimensions.width = image.width;
  51239. _imageDimensions.height = image.height;
  51240. }
  51241. return _imageDimensions;
  51242. }
  51243. //
  51244. this.allocateTextureUnit = allocateTextureUnit;
  51245. this.resetTextureUnits = resetTextureUnits;
  51246. this.setTexture2D = setTexture2D;
  51247. this.setTexture2DArray = setTexture2DArray;
  51248. this.setTexture3D = setTexture3D;
  51249. this.setTextureCube = setTextureCube;
  51250. this.rebindTextures = rebindTextures;
  51251. this.setupRenderTarget = setupRenderTarget;
  51252. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  51253. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  51254. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  51255. this.setupFrameBufferTexture = setupFrameBufferTexture;
  51256. this.useMultisampledRTT = useMultisampledRTT;
  51257. this.isReversedDepthBuffer = function () {
  51258. return state.buffers.depth.getReversed();
  51259. };
  51260. }
  51261. function WebGLUtils( gl, extensions ) {
  51262. function convert( p, colorSpace = NoColorSpace ) {
  51263. let extension;
  51264. const transfer = ColorManagement.getTransfer( colorSpace );
  51265. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  51266. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  51267. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  51268. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  51269. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  51270. if ( p === ByteType ) return gl.BYTE;
  51271. if ( p === ShortType ) return gl.SHORT;
  51272. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  51273. if ( p === IntType ) return gl.INT;
  51274. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  51275. if ( p === FloatType ) return gl.FLOAT;
  51276. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  51277. if ( p === AlphaFormat ) return gl.ALPHA;
  51278. if ( p === RGBFormat ) return gl.RGB;
  51279. if ( p === RGBAFormat ) return gl.RGBA;
  51280. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  51281. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  51282. // WebGL2 formats.
  51283. if ( p === RedFormat ) return gl.RED;
  51284. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  51285. if ( p === RGFormat ) return gl.RG;
  51286. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  51287. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  51288. // S3TC
  51289. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  51290. if ( transfer === SRGBTransfer ) {
  51291. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  51292. if ( extension !== null ) {
  51293. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  51294. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  51295. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  51296. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  51297. } else {
  51298. return null;
  51299. }
  51300. } else {
  51301. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  51302. if ( extension !== null ) {
  51303. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  51304. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  51305. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  51306. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  51307. } else {
  51308. return null;
  51309. }
  51310. }
  51311. }
  51312. // PVRTC
  51313. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  51314. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  51315. if ( extension !== null ) {
  51316. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  51317. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  51318. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  51319. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  51320. } else {
  51321. return null;
  51322. }
  51323. }
  51324. // ETC
  51325. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  51326. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  51327. if ( extension !== null ) {
  51328. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  51329. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  51330. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  51331. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  51332. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  51333. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  51334. } else {
  51335. return null;
  51336. }
  51337. }
  51338. // ASTC
  51339. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  51340. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  51341. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  51342. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  51343. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  51344. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  51345. if ( extension !== null ) {
  51346. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  51347. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  51348. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  51349. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  51350. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  51351. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  51352. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  51353. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  51354. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  51355. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  51356. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  51357. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  51358. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  51359. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  51360. } else {
  51361. return null;
  51362. }
  51363. }
  51364. // BPTC
  51365. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  51366. extension = extensions.get( 'EXT_texture_compression_bptc' );
  51367. if ( extension !== null ) {
  51368. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  51369. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  51370. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  51371. } else {
  51372. return null;
  51373. }
  51374. }
  51375. // RGTC
  51376. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  51377. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  51378. if ( extension !== null ) {
  51379. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  51380. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  51381. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  51382. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  51383. } else {
  51384. return null;
  51385. }
  51386. }
  51387. //
  51388. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  51389. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  51390. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  51391. }
  51392. return { convert: convert };
  51393. }
  51394. const _occlusion_vertex = `
  51395. void main() {
  51396. gl_Position = vec4( position, 1.0 );
  51397. }`;
  51398. const _occlusion_fragment = `
  51399. uniform sampler2DArray depthColor;
  51400. uniform float depthWidth;
  51401. uniform float depthHeight;
  51402. void main() {
  51403. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  51404. if ( coord.x >= 1.0 ) {
  51405. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  51406. } else {
  51407. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  51408. }
  51409. }`;
  51410. /**
  51411. * A XR module that manages the access to the Depth Sensing API.
  51412. */
  51413. class WebXRDepthSensing {
  51414. /**
  51415. * Constructs a new depth sensing module.
  51416. */
  51417. constructor() {
  51418. /**
  51419. * An opaque texture representing the depth of the user's environment.
  51420. *
  51421. * @type {?ExternalTexture}
  51422. */
  51423. this.texture = null;
  51424. /**
  51425. * A plane mesh for visualizing the depth texture.
  51426. *
  51427. * @type {?Mesh}
  51428. */
  51429. this.mesh = null;
  51430. /**
  51431. * The depth near value.
  51432. *
  51433. * @type {number}
  51434. */
  51435. this.depthNear = 0;
  51436. /**
  51437. * The depth near far.
  51438. *
  51439. * @type {number}
  51440. */
  51441. this.depthFar = 0;
  51442. }
  51443. /**
  51444. * Inits the depth sensing module
  51445. *
  51446. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  51447. * @param {XRRenderState} renderState - The XR render state.
  51448. */
  51449. init( depthData, renderState ) {
  51450. if ( this.texture === null ) {
  51451. const texture = new ExternalTexture( depthData.texture );
  51452. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  51453. this.depthNear = depthData.depthNear;
  51454. this.depthFar = depthData.depthFar;
  51455. }
  51456. this.texture = texture;
  51457. }
  51458. }
  51459. /**
  51460. * Returns a plane mesh that visualizes the depth texture.
  51461. *
  51462. * @param {ArrayCamera} cameraXR - The XR camera.
  51463. * @return {?Mesh} The plane mesh.
  51464. */
  51465. getMesh( cameraXR ) {
  51466. if ( this.texture !== null ) {
  51467. if ( this.mesh === null ) {
  51468. const viewport = cameraXR.cameras[ 0 ].viewport;
  51469. const material = new ShaderMaterial( {
  51470. vertexShader: _occlusion_vertex,
  51471. fragmentShader: _occlusion_fragment,
  51472. uniforms: {
  51473. depthColor: { value: this.texture },
  51474. depthWidth: { value: viewport.z },
  51475. depthHeight: { value: viewport.w }
  51476. }
  51477. } );
  51478. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  51479. }
  51480. }
  51481. return this.mesh;
  51482. }
  51483. /**
  51484. * Resets the module
  51485. */
  51486. reset() {
  51487. this.texture = null;
  51488. this.mesh = null;
  51489. }
  51490. /**
  51491. * Returns a texture representing the depth of the user's environment.
  51492. *
  51493. * @return {?ExternalTexture} The depth texture.
  51494. */
  51495. getDepthTexture() {
  51496. return this.texture;
  51497. }
  51498. }
  51499. /**
  51500. * This class represents an abstraction of the WebXR Device API and is
  51501. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  51502. * interface that allows users to enable/disable XR and perform XR related
  51503. * tasks like for instance retrieving controllers.
  51504. *
  51505. * @augments EventDispatcher
  51506. * @hideconstructor
  51507. */
  51508. class WebXRManager extends EventDispatcher {
  51509. /**
  51510. * Constructs a new WebGL renderer.
  51511. *
  51512. * @param {WebGLRenderer} renderer - The renderer.
  51513. * @param {WebGL2RenderingContext} gl - The rendering context.
  51514. */
  51515. constructor( renderer, gl ) {
  51516. super();
  51517. const scope = this;
  51518. let session = null;
  51519. let framebufferScaleFactor = 1.0;
  51520. let referenceSpace = null;
  51521. let referenceSpaceType = 'local-floor';
  51522. // Set default foveation to maximum.
  51523. let foveation = 1.0;
  51524. let customReferenceSpace = null;
  51525. let pose = null;
  51526. let glBinding = null;
  51527. let glProjLayer = null;
  51528. let glBaseLayer = null;
  51529. let xrFrame = null;
  51530. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  51531. const depthSensing = new WebXRDepthSensing();
  51532. const cameraAccessTextures = {};
  51533. const attributes = gl.getContextAttributes();
  51534. let initialRenderTarget = null;
  51535. let newRenderTarget = null;
  51536. const controllers = [];
  51537. const controllerInputSources = [];
  51538. const currentSize = new Vector2();
  51539. let currentPixelRatio = null;
  51540. //
  51541. const cameraL = new PerspectiveCamera();
  51542. cameraL.viewport = new Vector4();
  51543. const cameraR = new PerspectiveCamera();
  51544. cameraR.viewport = new Vector4();
  51545. const cameras = [ cameraL, cameraR ];
  51546. const cameraXR = new ArrayCamera();
  51547. let _currentDepthNear = null;
  51548. let _currentDepthFar = null;
  51549. //
  51550. /**
  51551. * Whether the manager's XR camera should be automatically updated or not.
  51552. *
  51553. * @type {boolean}
  51554. * @default true
  51555. */
  51556. this.cameraAutoUpdate = true;
  51557. /**
  51558. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  51559. * if you are going to use XR in your app.
  51560. *
  51561. * @type {boolean}
  51562. * @default false
  51563. */
  51564. this.enabled = false;
  51565. /**
  51566. * Whether XR presentation is active or not.
  51567. *
  51568. * @type {boolean}
  51569. * @readonly
  51570. * @default false
  51571. */
  51572. this.isPresenting = false;
  51573. /**
  51574. * Returns a group representing the `target ray` space of the XR controller.
  51575. * Use this space for visualizing 3D objects that support the user in pointing
  51576. * tasks like UI interaction.
  51577. *
  51578. * @param {number} index - The index of the controller.
  51579. * @return {Group} A group representing the `target ray` space.
  51580. */
  51581. this.getController = function ( index ) {
  51582. let controller = controllers[ index ];
  51583. if ( controller === undefined ) {
  51584. controller = new WebXRController();
  51585. controllers[ index ] = controller;
  51586. }
  51587. return controller.getTargetRaySpace();
  51588. };
  51589. /**
  51590. * Returns a group representing the `grip` space of the XR controller.
  51591. * Use this space for visualizing 3D objects that support the user in pointing
  51592. * tasks like UI interaction.
  51593. *
  51594. * Note: If you want to show something in the user's hand AND offer a
  51595. * pointing ray at the same time, you'll want to attached the handheld object
  51596. * to the group returned by `getControllerGrip()` and the ray to the
  51597. * group returned by `getController()`. The idea is to have two
  51598. * different groups in two different coordinate spaces for the same WebXR
  51599. * controller.
  51600. *
  51601. * @param {number} index - The index of the controller.
  51602. * @return {Group} A group representing the `grip` space.
  51603. */
  51604. this.getControllerGrip = function ( index ) {
  51605. let controller = controllers[ index ];
  51606. if ( controller === undefined ) {
  51607. controller = new WebXRController();
  51608. controllers[ index ] = controller;
  51609. }
  51610. return controller.getGripSpace();
  51611. };
  51612. /**
  51613. * Returns a group representing the `hand` space of the XR controller.
  51614. * Use this space for visualizing 3D objects that support the user in pointing
  51615. * tasks like UI interaction.
  51616. *
  51617. * @param {number} index - The index of the controller.
  51618. * @return {Group} A group representing the `hand` space.
  51619. */
  51620. this.getHand = function ( index ) {
  51621. let controller = controllers[ index ];
  51622. if ( controller === undefined ) {
  51623. controller = new WebXRController();
  51624. controllers[ index ] = controller;
  51625. }
  51626. return controller.getHandSpace();
  51627. };
  51628. //
  51629. function onSessionEvent( event ) {
  51630. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  51631. if ( controllerIndex === -1 ) {
  51632. return;
  51633. }
  51634. const controller = controllers[ controllerIndex ];
  51635. if ( controller !== undefined ) {
  51636. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  51637. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  51638. }
  51639. }
  51640. function onSessionEnd() {
  51641. session.removeEventListener( 'select', onSessionEvent );
  51642. session.removeEventListener( 'selectstart', onSessionEvent );
  51643. session.removeEventListener( 'selectend', onSessionEvent );
  51644. session.removeEventListener( 'squeeze', onSessionEvent );
  51645. session.removeEventListener( 'squeezestart', onSessionEvent );
  51646. session.removeEventListener( 'squeezeend', onSessionEvent );
  51647. session.removeEventListener( 'end', onSessionEnd );
  51648. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  51649. for ( let i = 0; i < controllers.length; i ++ ) {
  51650. const inputSource = controllerInputSources[ i ];
  51651. if ( inputSource === null ) continue;
  51652. controllerInputSources[ i ] = null;
  51653. controllers[ i ].disconnect( inputSource );
  51654. }
  51655. _currentDepthNear = null;
  51656. _currentDepthFar = null;
  51657. depthSensing.reset();
  51658. for ( const key in cameraAccessTextures ) {
  51659. delete cameraAccessTextures[ key ];
  51660. }
  51661. // restore framebuffer/rendering state
  51662. renderer.setRenderTarget( initialRenderTarget );
  51663. glBaseLayer = null;
  51664. glProjLayer = null;
  51665. glBinding = null;
  51666. session = null;
  51667. newRenderTarget = null;
  51668. //
  51669. animation.stop();
  51670. scope.isPresenting = false;
  51671. renderer.setPixelRatio( currentPixelRatio );
  51672. renderer.setSize( currentSize.width, currentSize.height, false );
  51673. scope.dispatchEvent( { type: 'sessionend' } );
  51674. }
  51675. /**
  51676. * Sets the framebuffer scale factor.
  51677. *
  51678. * This method can not be used during a XR session.
  51679. *
  51680. * @param {number} value - The framebuffer scale factor.
  51681. */
  51682. this.setFramebufferScaleFactor = function ( value ) {
  51683. framebufferScaleFactor = value;
  51684. if ( scope.isPresenting === true ) {
  51685. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51686. }
  51687. };
  51688. /**
  51689. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51690. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51691. * improve tracking. Default is `local-floor`. Valid values can be found here
  51692. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51693. *
  51694. * This method can not be used during a XR session.
  51695. *
  51696. * @param {string} value - The reference space type.
  51697. */
  51698. this.setReferenceSpaceType = function ( value ) {
  51699. referenceSpaceType = value;
  51700. if ( scope.isPresenting === true ) {
  51701. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51702. }
  51703. };
  51704. /**
  51705. * Returns the XR reference space.
  51706. *
  51707. * @return {XRReferenceSpace} The XR reference space.
  51708. */
  51709. this.getReferenceSpace = function () {
  51710. return customReferenceSpace || referenceSpace;
  51711. };
  51712. /**
  51713. * Sets a custom XR reference space.
  51714. *
  51715. * @param {XRReferenceSpace} space - The XR reference space.
  51716. */
  51717. this.setReferenceSpace = function ( space ) {
  51718. customReferenceSpace = space;
  51719. };
  51720. /**
  51721. * Returns the current base layer.
  51722. *
  51723. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51724. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51725. *
  51726. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51727. */
  51728. this.getBaseLayer = function () {
  51729. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51730. };
  51731. /**
  51732. * Returns the current XR binding.
  51733. *
  51734. * Creates a new binding if needed and the browser is
  51735. * capable of doing so.
  51736. *
  51737. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51738. */
  51739. this.getBinding = function () {
  51740. if ( glBinding === null && supportsGlBinding ) {
  51741. glBinding = new XRWebGLBinding( session, gl );
  51742. }
  51743. return glBinding;
  51744. };
  51745. /**
  51746. * Returns the current XR frame.
  51747. *
  51748. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51749. */
  51750. this.getFrame = function () {
  51751. return xrFrame;
  51752. };
  51753. /**
  51754. * Returns the current XR session.
  51755. *
  51756. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51757. */
  51758. this.getSession = function () {
  51759. return session;
  51760. };
  51761. /**
  51762. * After a XR session has been requested usually with one of the `*Button` modules, it
  51763. * is injected into the renderer with this method. This method triggers the start of
  51764. * the actual XR rendering.
  51765. *
  51766. * @async
  51767. * @param {XRSession} value - The XR session to set.
  51768. * @return {Promise} A Promise that resolves when the session has been set.
  51769. */
  51770. this.setSession = async function ( value ) {
  51771. session = value;
  51772. if ( session !== null ) {
  51773. initialRenderTarget = renderer.getRenderTarget();
  51774. session.addEventListener( 'select', onSessionEvent );
  51775. session.addEventListener( 'selectstart', onSessionEvent );
  51776. session.addEventListener( 'selectend', onSessionEvent );
  51777. session.addEventListener( 'squeeze', onSessionEvent );
  51778. session.addEventListener( 'squeezestart', onSessionEvent );
  51779. session.addEventListener( 'squeezeend', onSessionEvent );
  51780. session.addEventListener( 'end', onSessionEnd );
  51781. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51782. if ( attributes.xrCompatible !== true ) {
  51783. await gl.makeXRCompatible();
  51784. }
  51785. currentPixelRatio = renderer.getPixelRatio();
  51786. renderer.getSize( currentSize );
  51787. // Check that the browser implements the necessary APIs to use an
  51788. // XRProjectionLayer rather than an XRWebGLLayer
  51789. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51790. if ( ! supportsLayers ) {
  51791. const layerInit = {
  51792. antialias: attributes.antialias,
  51793. alpha: true,
  51794. depth: attributes.depth,
  51795. stencil: attributes.stencil,
  51796. framebufferScaleFactor: framebufferScaleFactor
  51797. };
  51798. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51799. session.updateRenderState( { baseLayer: glBaseLayer } );
  51800. renderer.setPixelRatio( 1 );
  51801. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51802. newRenderTarget = new WebGLRenderTarget(
  51803. glBaseLayer.framebufferWidth,
  51804. glBaseLayer.framebufferHeight,
  51805. {
  51806. format: RGBAFormat,
  51807. type: UnsignedByteType,
  51808. colorSpace: renderer.outputColorSpace,
  51809. stencilBuffer: attributes.stencil,
  51810. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51811. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51812. }
  51813. );
  51814. } else {
  51815. let depthFormat = null;
  51816. let depthType = null;
  51817. let glDepthFormat = null;
  51818. if ( attributes.depth ) {
  51819. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51820. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51821. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51822. }
  51823. const projectionlayerInit = {
  51824. colorFormat: gl.RGBA8,
  51825. depthFormat: glDepthFormat,
  51826. scaleFactor: framebufferScaleFactor
  51827. };
  51828. glBinding = this.getBinding();
  51829. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51830. session.updateRenderState( { layers: [ glProjLayer ] } );
  51831. renderer.setPixelRatio( 1 );
  51832. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51833. newRenderTarget = new WebGLRenderTarget(
  51834. glProjLayer.textureWidth,
  51835. glProjLayer.textureHeight,
  51836. {
  51837. format: RGBAFormat,
  51838. type: UnsignedByteType,
  51839. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51840. stencilBuffer: attributes.stencil,
  51841. colorSpace: renderer.outputColorSpace,
  51842. samples: attributes.antialias ? 4 : 0,
  51843. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51844. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51845. } );
  51846. }
  51847. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51848. this.setFoveation( foveation );
  51849. customReferenceSpace = null;
  51850. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51851. animation.setContext( session );
  51852. animation.start();
  51853. scope.isPresenting = true;
  51854. scope.dispatchEvent( { type: 'sessionstart' } );
  51855. }
  51856. };
  51857. /**
  51858. * Returns the environment blend mode from the current XR session.
  51859. *
  51860. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51861. */
  51862. this.getEnvironmentBlendMode = function () {
  51863. if ( session !== null ) {
  51864. return session.environmentBlendMode;
  51865. }
  51866. };
  51867. /**
  51868. * Returns the current depth texture computed via depth sensing.
  51869. *
  51870. * See {@link WebXRDepthSensing#getDepthTexture}.
  51871. *
  51872. * @return {?Texture} The depth texture.
  51873. */
  51874. this.getDepthTexture = function () {
  51875. return depthSensing.getDepthTexture();
  51876. };
  51877. function onInputSourcesChange( event ) {
  51878. // Notify disconnected
  51879. for ( let i = 0; i < event.removed.length; i ++ ) {
  51880. const inputSource = event.removed[ i ];
  51881. const index = controllerInputSources.indexOf( inputSource );
  51882. if ( index >= 0 ) {
  51883. controllerInputSources[ index ] = null;
  51884. controllers[ index ].disconnect( inputSource );
  51885. }
  51886. }
  51887. // Notify connected
  51888. for ( let i = 0; i < event.added.length; i ++ ) {
  51889. const inputSource = event.added[ i ];
  51890. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51891. if ( controllerIndex === -1 ) {
  51892. // Assign input source a controller that currently has no input source
  51893. for ( let i = 0; i < controllers.length; i ++ ) {
  51894. if ( i >= controllerInputSources.length ) {
  51895. controllerInputSources.push( inputSource );
  51896. controllerIndex = i;
  51897. break;
  51898. } else if ( controllerInputSources[ i ] === null ) {
  51899. controllerInputSources[ i ] = inputSource;
  51900. controllerIndex = i;
  51901. break;
  51902. }
  51903. }
  51904. // If all controllers do currently receive input we ignore new ones
  51905. if ( controllerIndex === -1 ) break;
  51906. }
  51907. const controller = controllers[ controllerIndex ];
  51908. if ( controller ) {
  51909. controller.connect( inputSource );
  51910. }
  51911. }
  51912. }
  51913. //
  51914. const cameraLPos = new Vector3();
  51915. const cameraRPos = new Vector3();
  51916. /**
  51917. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51918. * the cameras' projection and world matrices have already been set.
  51919. * And that near and far planes are identical for both cameras.
  51920. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51921. *
  51922. * @param {ArrayCamera} camera - The camera to update.
  51923. * @param {PerspectiveCamera} cameraL - The left camera.
  51924. * @param {PerspectiveCamera} cameraR - The right camera.
  51925. */
  51926. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51927. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51928. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51929. const ipd = cameraLPos.distanceTo( cameraRPos );
  51930. const projL = cameraL.projectionMatrix.elements;
  51931. const projR = cameraR.projectionMatrix.elements;
  51932. // VR systems will have identical far and near planes, and
  51933. // most likely identical top and bottom frustum extents.
  51934. // Use the left camera for these values.
  51935. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51936. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51937. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51938. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51939. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51940. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51941. const left = near * leftFov;
  51942. const right = near * rightFov;
  51943. // Calculate the new camera's position offset from the
  51944. // left camera. xOffset should be roughly half `ipd`.
  51945. const zOffset = ipd / ( - leftFov + rightFov );
  51946. const xOffset = zOffset * - leftFov;
  51947. // TODO: Better way to apply this offset?
  51948. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51949. camera.translateX( xOffset );
  51950. camera.translateZ( zOffset );
  51951. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51952. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51953. // Check if the projection uses an infinite far plane.
  51954. if ( projL[ 10 ] === -1 ) {
  51955. // Use the projection matrix from the left eye.
  51956. // The camera offset is sufficient to include the view volumes
  51957. // of both eyes (assuming symmetric projections).
  51958. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51959. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51960. } else {
  51961. // Find the union of the frustum values of the cameras and scale
  51962. // the values so that the near plane's position does not change in world space,
  51963. // although must now be relative to the new union camera.
  51964. const near2 = near + zOffset;
  51965. const far2 = far + zOffset;
  51966. const left2 = left - xOffset;
  51967. const right2 = right + ( ipd - xOffset );
  51968. const top2 = topFov * far / far2 * near2;
  51969. const bottom2 = bottomFov * far / far2 * near2;
  51970. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51971. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51972. }
  51973. }
  51974. function updateCamera( camera, parent ) {
  51975. if ( parent === null ) {
  51976. camera.matrixWorld.copy( camera.matrix );
  51977. } else {
  51978. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51979. }
  51980. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51981. }
  51982. /**
  51983. * Updates the state of the XR camera. Use this method on app level if you
  51984. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51985. * camera of the scene as a parameter. The passed in camera's transformation
  51986. * is automatically adjusted to the position of the XR camera when calling
  51987. * this method.
  51988. *
  51989. * @param {Camera} camera - The camera.
  51990. */
  51991. this.updateCamera = function ( camera ) {
  51992. if ( session === null ) return;
  51993. let depthNear = camera.near;
  51994. let depthFar = camera.far;
  51995. if ( depthSensing.texture !== null ) {
  51996. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51997. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51998. }
  51999. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  52000. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  52001. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  52002. // Note that the new renderState won't apply until the next frame. See #18320
  52003. session.updateRenderState( {
  52004. depthNear: cameraXR.near,
  52005. depthFar: cameraXR.far
  52006. } );
  52007. _currentDepthNear = cameraXR.near;
  52008. _currentDepthFar = cameraXR.far;
  52009. }
  52010. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  52011. cameraXR.layers.mask = camera.layers.mask | 0b110;
  52012. cameraL.layers.mask = cameraXR.layers.mask & -5;
  52013. cameraR.layers.mask = cameraXR.layers.mask & -3;
  52014. const parent = camera.parent;
  52015. const cameras = cameraXR.cameras;
  52016. updateCamera( cameraXR, parent );
  52017. for ( let i = 0; i < cameras.length; i ++ ) {
  52018. updateCamera( cameras[ i ], parent );
  52019. }
  52020. // update projection matrix for proper view frustum culling
  52021. if ( cameras.length === 2 ) {
  52022. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  52023. } else {
  52024. // assume single camera setup (AR)
  52025. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  52026. }
  52027. // update user camera and its children
  52028. updateUserCamera( camera, cameraXR, parent );
  52029. };
  52030. function updateUserCamera( camera, cameraXR, parent ) {
  52031. if ( parent === null ) {
  52032. camera.matrix.copy( cameraXR.matrixWorld );
  52033. } else {
  52034. camera.matrix.copy( parent.matrixWorld );
  52035. camera.matrix.invert();
  52036. camera.matrix.multiply( cameraXR.matrixWorld );
  52037. }
  52038. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  52039. camera.updateMatrixWorld( true );
  52040. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  52041. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  52042. if ( camera.isPerspectiveCamera ) {
  52043. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  52044. camera.zoom = 1;
  52045. }
  52046. }
  52047. /**
  52048. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  52049. * of the active XR session. For each view it holds a separate camera object.
  52050. *
  52051. * The camera's `fov` is currently not used and does not reflect the fov of
  52052. * the XR camera. If you need the fov on app level, you have to compute in
  52053. * manually from the XR camera's projection matrices.
  52054. *
  52055. * @return {ArrayCamera} The XR camera.
  52056. */
  52057. this.getCamera = function () {
  52058. return cameraXR;
  52059. };
  52060. /**
  52061. * Returns the amount of foveation used by the XR compositor for the projection layer.
  52062. *
  52063. * @return {number|undefined} The amount of foveation.
  52064. */
  52065. this.getFoveation = function () {
  52066. if ( glProjLayer === null && glBaseLayer === null ) {
  52067. return undefined;
  52068. }
  52069. return foveation;
  52070. };
  52071. /**
  52072. * Sets the foveation value.
  52073. *
  52074. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  52075. * and `1` means maximum foveation (the edges render at lower resolution).
  52076. */
  52077. this.setFoveation = function ( value ) {
  52078. // 0 = no foveation = full resolution
  52079. // 1 = maximum foveation = the edges render at lower resolution
  52080. foveation = value;
  52081. if ( glProjLayer !== null ) {
  52082. glProjLayer.fixedFoveation = value;
  52083. }
  52084. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  52085. glBaseLayer.fixedFoveation = value;
  52086. }
  52087. };
  52088. /**
  52089. * Returns `true` if depth sensing is supported.
  52090. *
  52091. * @return {boolean} Whether depth sensing is supported or not.
  52092. */
  52093. this.hasDepthSensing = function () {
  52094. return depthSensing.texture !== null;
  52095. };
  52096. /**
  52097. * Returns the depth sensing mesh.
  52098. *
  52099. * See {@link WebXRDepthSensing#getMesh}.
  52100. *
  52101. * @return {Mesh} The depth sensing mesh.
  52102. */
  52103. this.getDepthSensingMesh = function () {
  52104. return depthSensing.getMesh( cameraXR );
  52105. };
  52106. /**
  52107. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  52108. * Only available during the current animation loop.
  52109. *
  52110. * @param {XRCamera} xrCamera - The camera to query.
  52111. * @return {?Texture} An opaque texture representing the current raw camera frame.
  52112. */
  52113. this.getCameraTexture = function ( xrCamera ) {
  52114. return cameraAccessTextures[ xrCamera ];
  52115. };
  52116. // Animation Loop
  52117. let onAnimationFrameCallback = null;
  52118. function onAnimationFrame( time, frame ) {
  52119. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  52120. xrFrame = frame;
  52121. if ( pose !== null ) {
  52122. const views = pose.views;
  52123. if ( glBaseLayer !== null ) {
  52124. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  52125. renderer.setRenderTarget( newRenderTarget );
  52126. }
  52127. let cameraXRNeedsUpdate = false;
  52128. // check if it's necessary to rebuild cameraXR's camera list
  52129. if ( views.length !== cameraXR.cameras.length ) {
  52130. cameraXR.cameras.length = 0;
  52131. cameraXRNeedsUpdate = true;
  52132. }
  52133. for ( let i = 0; i < views.length; i ++ ) {
  52134. const view = views[ i ];
  52135. let viewport = null;
  52136. if ( glBaseLayer !== null ) {
  52137. viewport = glBaseLayer.getViewport( view );
  52138. } else {
  52139. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  52140. viewport = glSubImage.viewport;
  52141. // For side-by-side projection, we only produce a single texture for both eyes.
  52142. if ( i === 0 ) {
  52143. renderer.setRenderTargetTextures(
  52144. newRenderTarget,
  52145. glSubImage.colorTexture,
  52146. glSubImage.depthStencilTexture );
  52147. renderer.setRenderTarget( newRenderTarget );
  52148. }
  52149. }
  52150. let camera = cameras[ i ];
  52151. if ( camera === undefined ) {
  52152. camera = new PerspectiveCamera();
  52153. camera.layers.enable( i );
  52154. camera.viewport = new Vector4();
  52155. cameras[ i ] = camera;
  52156. }
  52157. camera.matrix.fromArray( view.transform.matrix );
  52158. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  52159. camera.projectionMatrix.fromArray( view.projectionMatrix );
  52160. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  52161. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  52162. if ( i === 0 ) {
  52163. cameraXR.matrix.copy( camera.matrix );
  52164. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  52165. }
  52166. if ( cameraXRNeedsUpdate === true ) {
  52167. cameraXR.cameras.push( camera );
  52168. }
  52169. }
  52170. //
  52171. const enabledFeatures = session.enabledFeatures;
  52172. const gpuDepthSensingEnabled = enabledFeatures &&
  52173. enabledFeatures.includes( 'depth-sensing' ) &&
  52174. session.depthUsage == 'gpu-optimized';
  52175. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  52176. glBinding = scope.getBinding();
  52177. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  52178. if ( depthData && depthData.isValid && depthData.texture ) {
  52179. depthSensing.init( depthData, session.renderState );
  52180. }
  52181. }
  52182. const cameraAccessEnabled = enabledFeatures &&
  52183. enabledFeatures.includes( 'camera-access' );
  52184. if ( cameraAccessEnabled && supportsGlBinding ) {
  52185. renderer.state.unbindTexture();
  52186. glBinding = scope.getBinding();
  52187. for ( let i = 0; i < views.length; i ++ ) {
  52188. const camera = views[ i ].camera;
  52189. if ( camera ) {
  52190. let cameraTex = cameraAccessTextures[ camera ];
  52191. if ( ! cameraTex ) {
  52192. cameraTex = new ExternalTexture();
  52193. cameraAccessTextures[ camera ] = cameraTex;
  52194. }
  52195. const glTexture = glBinding.getCameraImage( camera );
  52196. cameraTex.sourceTexture = glTexture;
  52197. }
  52198. }
  52199. }
  52200. }
  52201. //
  52202. for ( let i = 0; i < controllers.length; i ++ ) {
  52203. const inputSource = controllerInputSources[ i ];
  52204. const controller = controllers[ i ];
  52205. if ( inputSource !== null && controller !== undefined ) {
  52206. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  52207. }
  52208. }
  52209. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  52210. if ( frame.detectedPlanes ) {
  52211. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  52212. }
  52213. xrFrame = null;
  52214. }
  52215. const animation = new WebGLAnimation();
  52216. animation.setAnimationLoop( onAnimationFrame );
  52217. this.setAnimationLoop = function ( callback ) {
  52218. onAnimationFrameCallback = callback;
  52219. };
  52220. this.dispose = function () {};
  52221. }
  52222. }
  52223. const _e1 = /*@__PURE__*/ new Euler();
  52224. const _m1 = /*@__PURE__*/ new Matrix4();
  52225. function WebGLMaterials( renderer, properties ) {
  52226. function refreshTransformUniform( map, uniform ) {
  52227. if ( map.matrixAutoUpdate === true ) {
  52228. map.updateMatrix();
  52229. }
  52230. uniform.value.copy( map.matrix );
  52231. }
  52232. function refreshFogUniforms( uniforms, fog ) {
  52233. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  52234. if ( fog.isFog ) {
  52235. uniforms.fogNear.value = fog.near;
  52236. uniforms.fogFar.value = fog.far;
  52237. } else if ( fog.isFogExp2 ) {
  52238. uniforms.fogDensity.value = fog.density;
  52239. }
  52240. }
  52241. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  52242. if ( material.isMeshBasicMaterial ) {
  52243. refreshUniformsCommon( uniforms, material );
  52244. } else if ( material.isMeshLambertMaterial ) {
  52245. refreshUniformsCommon( uniforms, material );
  52246. if ( material.envMap ) {
  52247. uniforms.envMapIntensity.value = material.envMapIntensity;
  52248. }
  52249. } else if ( material.isMeshToonMaterial ) {
  52250. refreshUniformsCommon( uniforms, material );
  52251. refreshUniformsToon( uniforms, material );
  52252. } else if ( material.isMeshPhongMaterial ) {
  52253. refreshUniformsCommon( uniforms, material );
  52254. refreshUniformsPhong( uniforms, material );
  52255. if ( material.envMap ) {
  52256. uniforms.envMapIntensity.value = material.envMapIntensity;
  52257. }
  52258. } else if ( material.isMeshStandardMaterial ) {
  52259. refreshUniformsCommon( uniforms, material );
  52260. refreshUniformsStandard( uniforms, material );
  52261. if ( material.isMeshPhysicalMaterial ) {
  52262. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  52263. }
  52264. } else if ( material.isMeshMatcapMaterial ) {
  52265. refreshUniformsCommon( uniforms, material );
  52266. refreshUniformsMatcap( uniforms, material );
  52267. } else if ( material.isMeshDepthMaterial ) {
  52268. refreshUniformsCommon( uniforms, material );
  52269. } else if ( material.isMeshDistanceMaterial ) {
  52270. refreshUniformsCommon( uniforms, material );
  52271. refreshUniformsDistance( uniforms, material );
  52272. } else if ( material.isMeshNormalMaterial ) {
  52273. refreshUniformsCommon( uniforms, material );
  52274. } else if ( material.isLineBasicMaterial ) {
  52275. refreshUniformsLine( uniforms, material );
  52276. if ( material.isLineDashedMaterial ) {
  52277. refreshUniformsDash( uniforms, material );
  52278. }
  52279. } else if ( material.isPointsMaterial ) {
  52280. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  52281. } else if ( material.isSpriteMaterial ) {
  52282. refreshUniformsSprites( uniforms, material );
  52283. } else if ( material.isShadowMaterial ) {
  52284. uniforms.color.value.copy( material.color );
  52285. uniforms.opacity.value = material.opacity;
  52286. } else if ( material.isShaderMaterial ) {
  52287. material.uniformsNeedUpdate = false; // #15581
  52288. }
  52289. }
  52290. function refreshUniformsCommon( uniforms, material ) {
  52291. uniforms.opacity.value = material.opacity;
  52292. if ( material.color ) {
  52293. uniforms.diffuse.value.copy( material.color );
  52294. }
  52295. if ( material.emissive ) {
  52296. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  52297. }
  52298. if ( material.map ) {
  52299. uniforms.map.value = material.map;
  52300. refreshTransformUniform( material.map, uniforms.mapTransform );
  52301. }
  52302. if ( material.alphaMap ) {
  52303. uniforms.alphaMap.value = material.alphaMap;
  52304. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52305. }
  52306. if ( material.bumpMap ) {
  52307. uniforms.bumpMap.value = material.bumpMap;
  52308. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  52309. uniforms.bumpScale.value = material.bumpScale;
  52310. if ( material.side === BackSide ) {
  52311. uniforms.bumpScale.value *= -1;
  52312. }
  52313. }
  52314. if ( material.normalMap ) {
  52315. uniforms.normalMap.value = material.normalMap;
  52316. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  52317. uniforms.normalScale.value.copy( material.normalScale );
  52318. if ( material.side === BackSide ) {
  52319. uniforms.normalScale.value.negate();
  52320. }
  52321. }
  52322. if ( material.displacementMap ) {
  52323. uniforms.displacementMap.value = material.displacementMap;
  52324. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  52325. uniforms.displacementScale.value = material.displacementScale;
  52326. uniforms.displacementBias.value = material.displacementBias;
  52327. }
  52328. if ( material.emissiveMap ) {
  52329. uniforms.emissiveMap.value = material.emissiveMap;
  52330. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  52331. }
  52332. if ( material.specularMap ) {
  52333. uniforms.specularMap.value = material.specularMap;
  52334. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  52335. }
  52336. if ( material.alphaTest > 0 ) {
  52337. uniforms.alphaTest.value = material.alphaTest;
  52338. }
  52339. const materialProperties = properties.get( material );
  52340. const envMap = materialProperties.envMap;
  52341. const envMapRotation = materialProperties.envMapRotation;
  52342. if ( envMap ) {
  52343. uniforms.envMap.value = envMap;
  52344. _e1.copy( envMapRotation );
  52345. // accommodate left-handed frame
  52346. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  52347. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  52348. // environment maps which are not cube render targets or PMREMs follow a different convention
  52349. _e1.y *= -1;
  52350. _e1.z *= -1;
  52351. }
  52352. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  52353. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  52354. uniforms.reflectivity.value = material.reflectivity;
  52355. uniforms.ior.value = material.ior;
  52356. uniforms.refractionRatio.value = material.refractionRatio;
  52357. }
  52358. if ( material.lightMap ) {
  52359. uniforms.lightMap.value = material.lightMap;
  52360. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  52361. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  52362. }
  52363. if ( material.aoMap ) {
  52364. uniforms.aoMap.value = material.aoMap;
  52365. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  52366. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  52367. }
  52368. }
  52369. function refreshUniformsLine( uniforms, material ) {
  52370. uniforms.diffuse.value.copy( material.color );
  52371. uniforms.opacity.value = material.opacity;
  52372. if ( material.map ) {
  52373. uniforms.map.value = material.map;
  52374. refreshTransformUniform( material.map, uniforms.mapTransform );
  52375. }
  52376. }
  52377. function refreshUniformsDash( uniforms, material ) {
  52378. uniforms.dashSize.value = material.dashSize;
  52379. uniforms.totalSize.value = material.dashSize + material.gapSize;
  52380. uniforms.scale.value = material.scale;
  52381. }
  52382. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  52383. uniforms.diffuse.value.copy( material.color );
  52384. uniforms.opacity.value = material.opacity;
  52385. uniforms.size.value = material.size * pixelRatio;
  52386. uniforms.scale.value = height * 0.5;
  52387. if ( material.map ) {
  52388. uniforms.map.value = material.map;
  52389. refreshTransformUniform( material.map, uniforms.uvTransform );
  52390. }
  52391. if ( material.alphaMap ) {
  52392. uniforms.alphaMap.value = material.alphaMap;
  52393. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52394. }
  52395. if ( material.alphaTest > 0 ) {
  52396. uniforms.alphaTest.value = material.alphaTest;
  52397. }
  52398. }
  52399. function refreshUniformsSprites( uniforms, material ) {
  52400. uniforms.diffuse.value.copy( material.color );
  52401. uniforms.opacity.value = material.opacity;
  52402. uniforms.rotation.value = material.rotation;
  52403. if ( material.map ) {
  52404. uniforms.map.value = material.map;
  52405. refreshTransformUniform( material.map, uniforms.mapTransform );
  52406. }
  52407. if ( material.alphaMap ) {
  52408. uniforms.alphaMap.value = material.alphaMap;
  52409. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52410. }
  52411. if ( material.alphaTest > 0 ) {
  52412. uniforms.alphaTest.value = material.alphaTest;
  52413. }
  52414. }
  52415. function refreshUniformsPhong( uniforms, material ) {
  52416. uniforms.specular.value.copy( material.specular );
  52417. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  52418. }
  52419. function refreshUniformsToon( uniforms, material ) {
  52420. if ( material.gradientMap ) {
  52421. uniforms.gradientMap.value = material.gradientMap;
  52422. }
  52423. }
  52424. function refreshUniformsStandard( uniforms, material ) {
  52425. uniforms.metalness.value = material.metalness;
  52426. if ( material.metalnessMap ) {
  52427. uniforms.metalnessMap.value = material.metalnessMap;
  52428. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  52429. }
  52430. uniforms.roughness.value = material.roughness;
  52431. if ( material.roughnessMap ) {
  52432. uniforms.roughnessMap.value = material.roughnessMap;
  52433. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  52434. }
  52435. if ( material.envMap ) {
  52436. //uniforms.envMap.value = material.envMap; // part of uniforms common
  52437. uniforms.envMapIntensity.value = material.envMapIntensity;
  52438. }
  52439. }
  52440. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  52441. uniforms.ior.value = material.ior; // also part of uniforms common
  52442. if ( material.sheen > 0 ) {
  52443. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  52444. uniforms.sheenRoughness.value = material.sheenRoughness;
  52445. if ( material.sheenColorMap ) {
  52446. uniforms.sheenColorMap.value = material.sheenColorMap;
  52447. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  52448. }
  52449. if ( material.sheenRoughnessMap ) {
  52450. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  52451. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  52452. }
  52453. }
  52454. if ( material.clearcoat > 0 ) {
  52455. uniforms.clearcoat.value = material.clearcoat;
  52456. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  52457. if ( material.clearcoatMap ) {
  52458. uniforms.clearcoatMap.value = material.clearcoatMap;
  52459. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  52460. }
  52461. if ( material.clearcoatRoughnessMap ) {
  52462. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  52463. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  52464. }
  52465. if ( material.clearcoatNormalMap ) {
  52466. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  52467. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  52468. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  52469. if ( material.side === BackSide ) {
  52470. uniforms.clearcoatNormalScale.value.negate();
  52471. }
  52472. }
  52473. }
  52474. if ( material.dispersion > 0 ) {
  52475. uniforms.dispersion.value = material.dispersion;
  52476. }
  52477. if ( material.iridescence > 0 ) {
  52478. uniforms.iridescence.value = material.iridescence;
  52479. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  52480. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  52481. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  52482. if ( material.iridescenceMap ) {
  52483. uniforms.iridescenceMap.value = material.iridescenceMap;
  52484. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  52485. }
  52486. if ( material.iridescenceThicknessMap ) {
  52487. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  52488. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  52489. }
  52490. }
  52491. if ( material.transmission > 0 ) {
  52492. uniforms.transmission.value = material.transmission;
  52493. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  52494. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  52495. if ( material.transmissionMap ) {
  52496. uniforms.transmissionMap.value = material.transmissionMap;
  52497. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  52498. }
  52499. uniforms.thickness.value = material.thickness;
  52500. if ( material.thicknessMap ) {
  52501. uniforms.thicknessMap.value = material.thicknessMap;
  52502. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  52503. }
  52504. uniforms.attenuationDistance.value = material.attenuationDistance;
  52505. uniforms.attenuationColor.value.copy( material.attenuationColor );
  52506. }
  52507. if ( material.anisotropy > 0 ) {
  52508. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  52509. if ( material.anisotropyMap ) {
  52510. uniforms.anisotropyMap.value = material.anisotropyMap;
  52511. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  52512. }
  52513. }
  52514. uniforms.specularIntensity.value = material.specularIntensity;
  52515. uniforms.specularColor.value.copy( material.specularColor );
  52516. if ( material.specularColorMap ) {
  52517. uniforms.specularColorMap.value = material.specularColorMap;
  52518. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  52519. }
  52520. if ( material.specularIntensityMap ) {
  52521. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  52522. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  52523. }
  52524. }
  52525. function refreshUniformsMatcap( uniforms, material ) {
  52526. if ( material.matcap ) {
  52527. uniforms.matcap.value = material.matcap;
  52528. }
  52529. }
  52530. function refreshUniformsDistance( uniforms, material ) {
  52531. const light = properties.get( material ).light;
  52532. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  52533. uniforms.nearDistance.value = light.shadow.camera.near;
  52534. uniforms.farDistance.value = light.shadow.camera.far;
  52535. }
  52536. return {
  52537. refreshFogUniforms: refreshFogUniforms,
  52538. refreshMaterialUniforms: refreshMaterialUniforms
  52539. };
  52540. }
  52541. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  52542. let buffers = {};
  52543. let updateList = {};
  52544. let allocatedBindingPoints = [];
  52545. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  52546. function bind( uniformsGroup, program ) {
  52547. const webglProgram = program.program;
  52548. state.uniformBlockBinding( uniformsGroup, webglProgram );
  52549. }
  52550. function update( uniformsGroup, program ) {
  52551. let buffer = buffers[ uniformsGroup.id ];
  52552. if ( buffer === undefined ) {
  52553. prepareUniformsGroup( uniformsGroup );
  52554. buffer = createBuffer( uniformsGroup );
  52555. buffers[ uniformsGroup.id ] = buffer;
  52556. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  52557. }
  52558. // ensure to update the binding points/block indices mapping for this program
  52559. const webglProgram = program.program;
  52560. state.updateUBOMapping( uniformsGroup, webglProgram );
  52561. // update UBO once per frame
  52562. const frame = info.render.frame;
  52563. if ( updateList[ uniformsGroup.id ] !== frame ) {
  52564. updateBufferData( uniformsGroup );
  52565. updateList[ uniformsGroup.id ] = frame;
  52566. }
  52567. }
  52568. function createBuffer( uniformsGroup ) {
  52569. // the setup of an UBO is independent of a particular shader program but global
  52570. const bindingPointIndex = allocateBindingPointIndex();
  52571. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  52572. const buffer = gl.createBuffer();
  52573. const size = uniformsGroup.__size;
  52574. const usage = uniformsGroup.usage;
  52575. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52576. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  52577. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52578. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  52579. return buffer;
  52580. }
  52581. function allocateBindingPointIndex() {
  52582. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  52583. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  52584. allocatedBindingPoints.push( i );
  52585. return i;
  52586. }
  52587. }
  52588. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  52589. return 0;
  52590. }
  52591. function updateBufferData( uniformsGroup ) {
  52592. const buffer = buffers[ uniformsGroup.id ];
  52593. const uniforms = uniformsGroup.uniforms;
  52594. const cache = uniformsGroup.__cache;
  52595. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52596. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  52597. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52598. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52599. const uniform = uniformArray[ j ];
  52600. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  52601. const offset = uniform.__offset;
  52602. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52603. let arrayOffset = 0;
  52604. for ( let k = 0; k < values.length; k ++ ) {
  52605. const value = values[ k ];
  52606. const info = getUniformSize( value );
  52607. // TODO add integer and struct support
  52608. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52609. uniform.__data[ 0 ] = value;
  52610. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  52611. } else if ( value.isMatrix3 ) {
  52612. // manually converting 3x3 to 3x4
  52613. uniform.__data[ 0 ] = value.elements[ 0 ];
  52614. uniform.__data[ 1 ] = value.elements[ 1 ];
  52615. uniform.__data[ 2 ] = value.elements[ 2 ];
  52616. uniform.__data[ 3 ] = 0;
  52617. uniform.__data[ 4 ] = value.elements[ 3 ];
  52618. uniform.__data[ 5 ] = value.elements[ 4 ];
  52619. uniform.__data[ 6 ] = value.elements[ 5 ];
  52620. uniform.__data[ 7 ] = 0;
  52621. uniform.__data[ 8 ] = value.elements[ 6 ];
  52622. uniform.__data[ 9 ] = value.elements[ 7 ];
  52623. uniform.__data[ 10 ] = value.elements[ 8 ];
  52624. uniform.__data[ 11 ] = 0;
  52625. } else {
  52626. value.toArray( uniform.__data, arrayOffset );
  52627. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  52628. }
  52629. }
  52630. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  52631. }
  52632. }
  52633. }
  52634. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52635. }
  52636. function hasUniformChanged( uniform, index, indexArray, cache ) {
  52637. const value = uniform.value;
  52638. const indexString = index + '_' + indexArray;
  52639. if ( cache[ indexString ] === undefined ) {
  52640. // cache entry does not exist so far
  52641. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52642. cache[ indexString ] = value;
  52643. } else {
  52644. cache[ indexString ] = value.clone();
  52645. }
  52646. return true;
  52647. } else {
  52648. const cachedObject = cache[ indexString ];
  52649. // compare current value with cached entry
  52650. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52651. if ( cachedObject !== value ) {
  52652. cache[ indexString ] = value;
  52653. return true;
  52654. }
  52655. } else {
  52656. if ( cachedObject.equals( value ) === false ) {
  52657. cachedObject.copy( value );
  52658. return true;
  52659. }
  52660. }
  52661. }
  52662. return false;
  52663. }
  52664. function prepareUniformsGroup( uniformsGroup ) {
  52665. // determine total buffer size according to the STD140 layout
  52666. // Hint: STD140 is the only supported layout in WebGL 2
  52667. const uniforms = uniformsGroup.uniforms;
  52668. let offset = 0; // global buffer offset in bytes
  52669. const chunkSize = 16; // size of a chunk in bytes
  52670. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52671. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52672. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52673. const uniform = uniformArray[ j ];
  52674. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52675. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52676. const value = values[ k ];
  52677. const info = getUniformSize( value );
  52678. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52679. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52680. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52681. offset += chunkPadding;
  52682. // Check for chunk overflow
  52683. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52684. // Add padding and adjust offset
  52685. offset += ( chunkSize - chunkStart );
  52686. }
  52687. // the following two properties will be used for partial buffer updates
  52688. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52689. uniform.__offset = offset;
  52690. // Update the global offset
  52691. offset += info.storage;
  52692. }
  52693. }
  52694. }
  52695. // ensure correct final padding
  52696. const chunkOffset = offset % chunkSize;
  52697. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52698. //
  52699. uniformsGroup.__size = offset;
  52700. uniformsGroup.__cache = {};
  52701. return this;
  52702. }
  52703. function getUniformSize( value ) {
  52704. const info = {
  52705. boundary: 0, // bytes
  52706. storage: 0 // bytes
  52707. };
  52708. // determine sizes according to STD140
  52709. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52710. // float/int/bool
  52711. info.boundary = 4;
  52712. info.storage = 4;
  52713. } else if ( value.isVector2 ) {
  52714. // vec2
  52715. info.boundary = 8;
  52716. info.storage = 8;
  52717. } else if ( value.isVector3 || value.isColor ) {
  52718. // vec3
  52719. info.boundary = 16;
  52720. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52721. } else if ( value.isVector4 ) {
  52722. // vec4
  52723. info.boundary = 16;
  52724. info.storage = 16;
  52725. } else if ( value.isMatrix3 ) {
  52726. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52727. info.boundary = 48;
  52728. info.storage = 48;
  52729. } else if ( value.isMatrix4 ) {
  52730. // mat4
  52731. info.boundary = 64;
  52732. info.storage = 64;
  52733. } else if ( value.isTexture ) {
  52734. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52735. } else {
  52736. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52737. }
  52738. return info;
  52739. }
  52740. function onUniformsGroupsDispose( event ) {
  52741. const uniformsGroup = event.target;
  52742. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52743. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52744. allocatedBindingPoints.splice( index, 1 );
  52745. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52746. delete buffers[ uniformsGroup.id ];
  52747. delete updateList[ uniformsGroup.id ];
  52748. }
  52749. function dispose() {
  52750. for ( const id in buffers ) {
  52751. gl.deleteBuffer( buffers[ id ] );
  52752. }
  52753. allocatedBindingPoints = [];
  52754. buffers = {};
  52755. updateList = {};
  52756. }
  52757. return {
  52758. bind: bind,
  52759. update: update,
  52760. dispose: dispose
  52761. };
  52762. }
  52763. /**
  52764. * Precomputed DFG LUT for Image-Based Lighting
  52765. * Resolution: 16x16
  52766. * Samples: 4096 per texel
  52767. * Format: RG16F (2 half floats per texel: scale, bias)
  52768. */
  52769. const DATA = new Uint16Array( [
  52770. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  52771. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  52772. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  52773. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  52774. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  52775. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  52776. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  52777. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  52778. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  52779. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  52780. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  52781. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  52782. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  52783. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  52784. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  52785. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  52786. ] );
  52787. let lut = null;
  52788. function getDFGLUT() {
  52789. if ( lut === null ) {
  52790. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  52791. lut.name = 'DFG_LUT';
  52792. lut.minFilter = LinearFilter;
  52793. lut.magFilter = LinearFilter;
  52794. lut.wrapS = ClampToEdgeWrapping;
  52795. lut.wrapT = ClampToEdgeWrapping;
  52796. lut.generateMipmaps = false;
  52797. lut.needsUpdate = true;
  52798. }
  52799. return lut;
  52800. }
  52801. /**
  52802. * This renderer uses WebGL 2 to display scenes.
  52803. *
  52804. * WebGL 1 is not supported since `r163`.
  52805. */
  52806. class WebGLRenderer {
  52807. /**
  52808. * Constructs a new WebGL renderer.
  52809. *
  52810. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52811. */
  52812. constructor( parameters = {} ) {
  52813. const {
  52814. canvas = createCanvasElement(),
  52815. context = null,
  52816. depth = true,
  52817. stencil = false,
  52818. alpha = false,
  52819. antialias = false,
  52820. premultipliedAlpha = true,
  52821. preserveDrawingBuffer = false,
  52822. powerPreference = 'default',
  52823. failIfMajorPerformanceCaveat = false,
  52824. reversedDepthBuffer = false,
  52825. outputBufferType = UnsignedByteType,
  52826. } = parameters;
  52827. /**
  52828. * This flag can be used for type testing.
  52829. *
  52830. * @type {boolean}
  52831. * @readonly
  52832. * @default true
  52833. */
  52834. this.isWebGLRenderer = true;
  52835. let _alpha;
  52836. if ( context !== null ) {
  52837. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52838. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52839. }
  52840. _alpha = context.getContextAttributes().alpha;
  52841. } else {
  52842. _alpha = alpha;
  52843. }
  52844. const _outputBufferType = outputBufferType;
  52845. const INTEGER_FORMATS = new Set( [
  52846. RGBAIntegerFormat,
  52847. RGIntegerFormat,
  52848. RedIntegerFormat
  52849. ] );
  52850. const UNSIGNED_TYPES = new Set( [
  52851. UnsignedByteType,
  52852. UnsignedIntType,
  52853. UnsignedShortType,
  52854. UnsignedInt248Type,
  52855. UnsignedShort4444Type,
  52856. UnsignedShort5551Type
  52857. ] );
  52858. const uintClearColor = new Uint32Array( 4 );
  52859. const intClearColor = new Int32Array( 4 );
  52860. let currentRenderList = null;
  52861. let currentRenderState = null;
  52862. // render() can be called from within a callback triggered by another render.
  52863. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52864. const renderListStack = [];
  52865. const renderStateStack = [];
  52866. // internal render target for non-UnsignedByteType color buffer
  52867. let output = null;
  52868. // public properties
  52869. /**
  52870. * A canvas where the renderer draws its output. This is automatically created by the renderer
  52871. * in the constructor (if not provided already); you just need to add it to your page like so:
  52872. * ```js
  52873. * document.body.appendChild( renderer.domElement );
  52874. * ```
  52875. *
  52876. * @type {HTMLCanvasElement|OffscreenCanvas}
  52877. */
  52878. this.domElement = canvas;
  52879. /**
  52880. * A object with debug configuration settings.
  52881. *
  52882. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52883. * checked for errors during compilation and linkage process. It may be useful to disable
  52884. * this check in production for performance gain. It is strongly recommended to keep these
  52885. * checks enabled during development. If the shader does not compile and link, it will not
  52886. * work and associated material will not render.
  52887. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52888. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52889. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52890. * Assigning a custom function disables the default error reporting.
  52891. *
  52892. * @type {Object}
  52893. */
  52894. this.debug = {
  52895. /**
  52896. * Enables error checking and reporting when shader programs are being compiled.
  52897. * @type {boolean}
  52898. */
  52899. checkShaderErrors: true,
  52900. /**
  52901. * Callback for custom error reporting.
  52902. * @type {?Function}
  52903. */
  52904. onShaderError: null
  52905. };
  52906. // clearing
  52907. /**
  52908. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52909. *
  52910. * @type {boolean}
  52911. * @default true
  52912. */
  52913. this.autoClear = true;
  52914. /**
  52915. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52916. * the color buffer or not.
  52917. *
  52918. * @type {boolean}
  52919. * @default true
  52920. */
  52921. this.autoClearColor = true;
  52922. /**
  52923. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52924. * the depth buffer or not.
  52925. *
  52926. * @type {boolean}
  52927. * @default true
  52928. */
  52929. this.autoClearDepth = true;
  52930. /**
  52931. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52932. * the stencil buffer or not.
  52933. *
  52934. * @type {boolean}
  52935. * @default true
  52936. */
  52937. this.autoClearStencil = true;
  52938. // scene graph
  52939. /**
  52940. * Whether the renderer should sort objects or not.
  52941. *
  52942. * Note: Sorting is used to attempt to properly render objects that have some
  52943. * degree of transparency. By definition, sorting objects may not work in all
  52944. * cases. Depending on the needs of application, it may be necessary to turn
  52945. * off sorting and use other methods to deal with transparency rendering e.g.
  52946. * manually determining each object's rendering order.
  52947. *
  52948. * @type {boolean}
  52949. * @default true
  52950. */
  52951. this.sortObjects = true;
  52952. // user-defined clipping
  52953. /**
  52954. * User-defined clipping planes specified in world space. These planes apply globally.
  52955. * Points in space whose dot product with the plane is negative are cut away.
  52956. *
  52957. * @type {Array<Plane>}
  52958. */
  52959. this.clippingPlanes = [];
  52960. /**
  52961. * Whether the renderer respects object-level clipping planes or not.
  52962. *
  52963. * @type {boolean}
  52964. * @default false
  52965. */
  52966. this.localClippingEnabled = false;
  52967. // tone mapping
  52968. /**
  52969. * The tone mapping technique of the renderer.
  52970. *
  52971. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52972. * @default NoToneMapping
  52973. */
  52974. this.toneMapping = NoToneMapping;
  52975. /**
  52976. * Exposure level of tone mapping.
  52977. *
  52978. * @type {number}
  52979. * @default 1
  52980. */
  52981. this.toneMappingExposure = 1.0;
  52982. // transmission
  52983. /**
  52984. * The normalized resolution scale for the transmission render target, measured in percentage
  52985. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52986. * when using {@link MeshPhysicalMaterial#transmission}.
  52987. *
  52988. * @type {number}
  52989. * @default 1
  52990. */
  52991. this.transmissionResolutionScale = 1.0;
  52992. // internal properties
  52993. const _this = this;
  52994. let _isContextLost = false;
  52995. // internal state cache
  52996. this._outputColorSpace = SRGBColorSpace;
  52997. let _currentActiveCubeFace = 0;
  52998. let _currentActiveMipmapLevel = 0;
  52999. let _currentRenderTarget = null;
  53000. let _currentMaterialId = -1;
  53001. let _currentCamera = null;
  53002. const _currentViewport = new Vector4();
  53003. const _currentScissor = new Vector4();
  53004. let _currentScissorTest = null;
  53005. const _currentClearColor = new Color( 0x000000 );
  53006. let _currentClearAlpha = 0;
  53007. //
  53008. let _width = canvas.width;
  53009. let _height = canvas.height;
  53010. let _pixelRatio = 1;
  53011. let _opaqueSort = null;
  53012. let _transparentSort = null;
  53013. const _viewport = new Vector4( 0, 0, _width, _height );
  53014. const _scissor = new Vector4( 0, 0, _width, _height );
  53015. let _scissorTest = false;
  53016. // frustum
  53017. const _frustum = new Frustum();
  53018. // clipping
  53019. let _clippingEnabled = false;
  53020. let _localClippingEnabled = false;
  53021. // camera matrices cache
  53022. const _projScreenMatrix = new Matrix4();
  53023. const _vector3 = new Vector3();
  53024. const _vector4 = new Vector4();
  53025. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  53026. let _renderBackground = false;
  53027. function getTargetPixelRatio() {
  53028. return _currentRenderTarget === null ? _pixelRatio : 1;
  53029. }
  53030. // initialize
  53031. let _gl = context;
  53032. function getContext( contextName, contextAttributes ) {
  53033. return canvas.getContext( contextName, contextAttributes );
  53034. }
  53035. try {
  53036. const contextAttributes = {
  53037. alpha: true,
  53038. depth,
  53039. stencil,
  53040. antialias,
  53041. premultipliedAlpha,
  53042. preserveDrawingBuffer,
  53043. powerPreference,
  53044. failIfMajorPerformanceCaveat,
  53045. };
  53046. // OffscreenCanvas does not have setAttribute, see #22811
  53047. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  53048. // event listeners must be registered before WebGL context is created, see #12753
  53049. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  53050. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  53051. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53052. if ( _gl === null ) {
  53053. const contextName = 'webgl2';
  53054. _gl = getContext( contextName, contextAttributes );
  53055. if ( _gl === null ) {
  53056. if ( getContext( contextName ) ) {
  53057. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  53058. } else {
  53059. throw new Error( 'Error creating WebGL context.' );
  53060. }
  53061. }
  53062. }
  53063. } catch ( e ) {
  53064. error( 'WebGLRenderer: ' + e.message );
  53065. throw e;
  53066. }
  53067. let extensions, capabilities, state, info;
  53068. let properties, textures, environments, attributes, geometries, objects;
  53069. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  53070. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  53071. let utils, bindingStates, uniformsGroups;
  53072. function initGLContext() {
  53073. extensions = new WebGLExtensions( _gl );
  53074. extensions.init();
  53075. utils = new WebGLUtils( _gl, extensions );
  53076. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  53077. state = new WebGLState( _gl, extensions );
  53078. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  53079. state.buffers.depth.setReversed( true );
  53080. }
  53081. info = new WebGLInfo( _gl );
  53082. properties = new WebGLProperties();
  53083. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  53084. environments = new WebGLEnvironments( _this );
  53085. attributes = new WebGLAttributes( _gl );
  53086. bindingStates = new WebGLBindingStates( _gl, attributes );
  53087. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  53088. objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info );
  53089. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  53090. clipping = new WebGLClipping( properties );
  53091. programCache = new WebGLPrograms( _this, environments, extensions, capabilities, bindingStates, clipping );
  53092. materials = new WebGLMaterials( _this, properties );
  53093. renderLists = new WebGLRenderLists();
  53094. renderStates = new WebGLRenderStates( extensions );
  53095. background = new WebGLBackground( _this, environments, state, objects, _alpha, premultipliedAlpha );
  53096. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  53097. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  53098. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  53099. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  53100. info.programs = programCache.programs;
  53101. /**
  53102. * Holds details about the capabilities of the current rendering context.
  53103. *
  53104. * @name WebGLRenderer#capabilities
  53105. * @type {WebGLRenderer~Capabilities}
  53106. */
  53107. _this.capabilities = capabilities;
  53108. /**
  53109. * Provides methods for retrieving and testing WebGL extensions.
  53110. *
  53111. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  53112. * and return the extension object if available.
  53113. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  53114. *
  53115. * @name WebGLRenderer#extensions
  53116. * @type {Object}
  53117. */
  53118. _this.extensions = extensions;
  53119. /**
  53120. * Used to track properties of other objects like native WebGL objects.
  53121. *
  53122. * @name WebGLRenderer#properties
  53123. * @type {Object}
  53124. */
  53125. _this.properties = properties;
  53126. /**
  53127. * Manages the render lists of the renderer.
  53128. *
  53129. * @name WebGLRenderer#renderLists
  53130. * @type {Object}
  53131. */
  53132. _this.renderLists = renderLists;
  53133. /**
  53134. * Interface for managing shadows.
  53135. *
  53136. * @name WebGLRenderer#shadowMap
  53137. * @type {WebGLRenderer~ShadowMap}
  53138. */
  53139. _this.shadowMap = shadowMap;
  53140. /**
  53141. * Interface for managing the WebGL state.
  53142. *
  53143. * @name WebGLRenderer#state
  53144. * @type {Object}
  53145. */
  53146. _this.state = state;
  53147. /**
  53148. * Holds a series of statistical information about the GPU memory
  53149. * and the rendering process. Useful for debugging and monitoring.
  53150. *
  53151. * By default these data are reset at each render call but when having
  53152. * multiple render passes per frame (e.g. when using post processing) it can
  53153. * be preferred to reset with a custom pattern. First, set `autoReset` to
  53154. * `false`.
  53155. * ```js
  53156. * renderer.info.autoReset = false;
  53157. * ```
  53158. * Call `reset()` whenever you have finished to render a single frame.
  53159. * ```js
  53160. * renderer.info.reset();
  53161. * ```
  53162. *
  53163. * @name WebGLRenderer#info
  53164. * @type {WebGLRenderer~Info}
  53165. */
  53166. _this.info = info;
  53167. }
  53168. initGLContext();
  53169. // initialize internal render target for non-UnsignedByteType color buffer
  53170. if ( _outputBufferType !== UnsignedByteType ) {
  53171. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  53172. }
  53173. // xr
  53174. const xr = new WebXRManager( _this, _gl );
  53175. /**
  53176. * A reference to the XR manager.
  53177. *
  53178. * @type {WebXRManager}
  53179. */
  53180. this.xr = xr;
  53181. /**
  53182. * Returns the rendering context.
  53183. *
  53184. * @return {WebGL2RenderingContext} The rendering context.
  53185. */
  53186. this.getContext = function () {
  53187. return _gl;
  53188. };
  53189. /**
  53190. * Returns the rendering context attributes.
  53191. *
  53192. * @return {WebGLContextAttributes} The rendering context attributes.
  53193. */
  53194. this.getContextAttributes = function () {
  53195. return _gl.getContextAttributes();
  53196. };
  53197. /**
  53198. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  53199. */
  53200. this.forceContextLoss = function () {
  53201. const extension = extensions.get( 'WEBGL_lose_context' );
  53202. if ( extension ) extension.loseContext();
  53203. };
  53204. /**
  53205. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  53206. */
  53207. this.forceContextRestore = function () {
  53208. const extension = extensions.get( 'WEBGL_lose_context' );
  53209. if ( extension ) extension.restoreContext();
  53210. };
  53211. /**
  53212. * Returns the pixel ratio.
  53213. *
  53214. * @return {number} The pixel ratio.
  53215. */
  53216. this.getPixelRatio = function () {
  53217. return _pixelRatio;
  53218. };
  53219. /**
  53220. * Sets the given pixel ratio and resizes the canvas if necessary.
  53221. *
  53222. * @param {number} value - The pixel ratio.
  53223. */
  53224. this.setPixelRatio = function ( value ) {
  53225. if ( value === undefined ) return;
  53226. _pixelRatio = value;
  53227. this.setSize( _width, _height, false );
  53228. };
  53229. /**
  53230. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  53231. *
  53232. * @param {Vector2} target - The method writes the result in this target object.
  53233. * @return {Vector2} The renderer's size in logical pixels.
  53234. */
  53235. this.getSize = function ( target ) {
  53236. return target.set( _width, _height );
  53237. };
  53238. /**
  53239. * Resizes the output canvas to (width, height) with device pixel ratio taken
  53240. * into account, and also sets the viewport to fit that size, starting in (0,
  53241. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  53242. *
  53243. * @param {number} width - The width in logical pixels.
  53244. * @param {number} height - The height in logical pixels.
  53245. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  53246. */
  53247. this.setSize = function ( width, height, updateStyle = true ) {
  53248. if ( xr.isPresenting ) {
  53249. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  53250. return;
  53251. }
  53252. _width = width;
  53253. _height = height;
  53254. canvas.width = Math.floor( width * _pixelRatio );
  53255. canvas.height = Math.floor( height * _pixelRatio );
  53256. if ( updateStyle === true ) {
  53257. canvas.style.width = width + 'px';
  53258. canvas.style.height = height + 'px';
  53259. }
  53260. if ( output !== null ) {
  53261. output.setSize( canvas.width, canvas.height );
  53262. }
  53263. this.setViewport( 0, 0, width, height );
  53264. };
  53265. /**
  53266. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  53267. *
  53268. * @param {Vector2} target - The method writes the result in this target object.
  53269. * @return {Vector2} The drawing buffer size.
  53270. */
  53271. this.getDrawingBufferSize = function ( target ) {
  53272. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  53273. };
  53274. /**
  53275. * This method allows to define the drawing buffer size by specifying
  53276. * width, height and pixel ratio all at once. The size of the drawing
  53277. * buffer is computed with this formula:
  53278. * ```js
  53279. * size.x = width * pixelRatio;
  53280. * size.y = height * pixelRatio;
  53281. * ```
  53282. *
  53283. * @param {number} width - The width in logical pixels.
  53284. * @param {number} height - The height in logical pixels.
  53285. * @param {number} pixelRatio - The pixel ratio.
  53286. */
  53287. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  53288. _width = width;
  53289. _height = height;
  53290. _pixelRatio = pixelRatio;
  53291. canvas.width = Math.floor( width * pixelRatio );
  53292. canvas.height = Math.floor( height * pixelRatio );
  53293. this.setViewport( 0, 0, width, height );
  53294. };
  53295. /**
  53296. * Sets the post-processing effects to be applied after rendering.
  53297. *
  53298. * @param {Array} effects - An array of post-processing effects.
  53299. */
  53300. this.setEffects = function ( effects ) {
  53301. if ( _outputBufferType === UnsignedByteType ) {
  53302. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  53303. return;
  53304. }
  53305. if ( effects ) {
  53306. for ( let i = 0; i < effects.length; i ++ ) {
  53307. if ( effects[ i ].isOutputPass === true ) {
  53308. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  53309. break;
  53310. }
  53311. }
  53312. }
  53313. output.setEffects( effects || [] );
  53314. };
  53315. /**
  53316. * Returns the current viewport definition.
  53317. *
  53318. * @param {Vector2} target - The method writes the result in this target object.
  53319. * @return {Vector2} The current viewport definition.
  53320. */
  53321. this.getCurrentViewport = function ( target ) {
  53322. return target.copy( _currentViewport );
  53323. };
  53324. /**
  53325. * Returns the viewport definition.
  53326. *
  53327. * @param {Vector4} target - The method writes the result in this target object.
  53328. * @return {Vector4} The viewport definition.
  53329. */
  53330. this.getViewport = function ( target ) {
  53331. return target.copy( _viewport );
  53332. };
  53333. /**
  53334. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  53335. *
  53336. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  53337. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  53338. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  53339. * @param {number} width - The width of the viewport in logical pixel unit.
  53340. * @param {number} height - The height of the viewport in logical pixel unit.
  53341. */
  53342. this.setViewport = function ( x, y, width, height ) {
  53343. if ( x.isVector4 ) {
  53344. _viewport.set( x.x, x.y, x.z, x.w );
  53345. } else {
  53346. _viewport.set( x, y, width, height );
  53347. }
  53348. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  53349. };
  53350. /**
  53351. * Returns the scissor region.
  53352. *
  53353. * @param {Vector4} target - The method writes the result in this target object.
  53354. * @return {Vector4} The scissor region.
  53355. */
  53356. this.getScissor = function ( target ) {
  53357. return target.copy( _scissor );
  53358. };
  53359. /**
  53360. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  53361. *
  53362. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  53363. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  53364. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  53365. * @param {number} width - The width of the scissor region in logical pixel unit.
  53366. * @param {number} height - The height of the scissor region in logical pixel unit.
  53367. */
  53368. this.setScissor = function ( x, y, width, height ) {
  53369. if ( x.isVector4 ) {
  53370. _scissor.set( x.x, x.y, x.z, x.w );
  53371. } else {
  53372. _scissor.set( x, y, width, height );
  53373. }
  53374. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  53375. };
  53376. /**
  53377. * Returns `true` if the scissor test is enabled.
  53378. *
  53379. * @return {boolean} Whether the scissor test is enabled or not.
  53380. */
  53381. this.getScissorTest = function () {
  53382. return _scissorTest;
  53383. };
  53384. /**
  53385. * Enable or disable the scissor test. When this is enabled, only the pixels
  53386. * within the defined scissor area will be affected by further renderer
  53387. * actions.
  53388. *
  53389. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  53390. */
  53391. this.setScissorTest = function ( boolean ) {
  53392. state.setScissorTest( _scissorTest = boolean );
  53393. };
  53394. /**
  53395. * Sets a custom opaque sort function for the render lists. Pass `null`
  53396. * to use the default `painterSortStable` function.
  53397. *
  53398. * @param {?Function} method - The opaque sort function.
  53399. */
  53400. this.setOpaqueSort = function ( method ) {
  53401. _opaqueSort = method;
  53402. };
  53403. /**
  53404. * Sets a custom transparent sort function for the render lists. Pass `null`
  53405. * to use the default `reversePainterSortStable` function.
  53406. *
  53407. * @param {?Function} method - The opaque sort function.
  53408. */
  53409. this.setTransparentSort = function ( method ) {
  53410. _transparentSort = method;
  53411. };
  53412. // Clearing
  53413. /**
  53414. * Returns the clear color.
  53415. *
  53416. * @param {Color} target - The method writes the result in this target object.
  53417. * @return {Color} The clear color.
  53418. */
  53419. this.getClearColor = function ( target ) {
  53420. return target.copy( background.getClearColor() );
  53421. };
  53422. /**
  53423. * Sets the clear color and alpha.
  53424. *
  53425. * @param {Color} color - The clear color.
  53426. * @param {number} [alpha=1] - The clear alpha.
  53427. */
  53428. this.setClearColor = function () {
  53429. background.setClearColor( ...arguments );
  53430. };
  53431. /**
  53432. * Returns the clear alpha. Ranges within `[0,1]`.
  53433. *
  53434. * @return {number} The clear alpha.
  53435. */
  53436. this.getClearAlpha = function () {
  53437. return background.getClearAlpha();
  53438. };
  53439. /**
  53440. * Sets the clear alpha.
  53441. *
  53442. * @param {number} alpha - The clear alpha.
  53443. */
  53444. this.setClearAlpha = function () {
  53445. background.setClearAlpha( ...arguments );
  53446. };
  53447. /**
  53448. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  53449. * This method initializes the buffers to the current clear color values.
  53450. *
  53451. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  53452. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  53453. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  53454. */
  53455. this.clear = function ( color = true, depth = true, stencil = true ) {
  53456. let bits = 0;
  53457. if ( color ) {
  53458. // check if we're trying to clear an integer target
  53459. let isIntegerFormat = false;
  53460. if ( _currentRenderTarget !== null ) {
  53461. const targetFormat = _currentRenderTarget.texture.format;
  53462. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  53463. }
  53464. // use the appropriate clear functions to clear the target if it's a signed
  53465. // or unsigned integer target
  53466. if ( isIntegerFormat ) {
  53467. const targetType = _currentRenderTarget.texture.type;
  53468. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  53469. const clearColor = background.getClearColor();
  53470. const a = background.getClearAlpha();
  53471. const r = clearColor.r;
  53472. const g = clearColor.g;
  53473. const b = clearColor.b;
  53474. if ( isUnsignedType ) {
  53475. uintClearColor[ 0 ] = r;
  53476. uintClearColor[ 1 ] = g;
  53477. uintClearColor[ 2 ] = b;
  53478. uintClearColor[ 3 ] = a;
  53479. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  53480. } else {
  53481. intClearColor[ 0 ] = r;
  53482. intClearColor[ 1 ] = g;
  53483. intClearColor[ 2 ] = b;
  53484. intClearColor[ 3 ] = a;
  53485. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  53486. }
  53487. } else {
  53488. bits |= _gl.COLOR_BUFFER_BIT;
  53489. }
  53490. }
  53491. if ( depth ) {
  53492. bits |= _gl.DEPTH_BUFFER_BIT;
  53493. }
  53494. if ( stencil ) {
  53495. bits |= _gl.STENCIL_BUFFER_BIT;
  53496. this.state.buffers.stencil.setMask( 0xffffffff );
  53497. }
  53498. if ( bits !== 0 ) {
  53499. _gl.clear( bits );
  53500. }
  53501. };
  53502. /**
  53503. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  53504. */
  53505. this.clearColor = function () {
  53506. this.clear( true, false, false );
  53507. };
  53508. /**
  53509. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  53510. */
  53511. this.clearDepth = function () {
  53512. this.clear( false, true, false );
  53513. };
  53514. /**
  53515. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  53516. */
  53517. this.clearStencil = function () {
  53518. this.clear( false, false, true );
  53519. };
  53520. /**
  53521. * Frees the GPU-related resources allocated by this instance. Call this
  53522. * method whenever this instance is no longer used in your app.
  53523. */
  53524. this.dispose = function () {
  53525. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  53526. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  53527. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53528. background.dispose();
  53529. renderLists.dispose();
  53530. renderStates.dispose();
  53531. properties.dispose();
  53532. environments.dispose();
  53533. objects.dispose();
  53534. bindingStates.dispose();
  53535. uniformsGroups.dispose();
  53536. programCache.dispose();
  53537. xr.dispose();
  53538. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  53539. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  53540. animation.stop();
  53541. };
  53542. // Events
  53543. function onContextLost( event ) {
  53544. event.preventDefault();
  53545. log( 'WebGLRenderer: Context Lost.' );
  53546. _isContextLost = true;
  53547. }
  53548. function onContextRestore( /* event */ ) {
  53549. log( 'WebGLRenderer: Context Restored.' );
  53550. _isContextLost = false;
  53551. const infoAutoReset = info.autoReset;
  53552. const shadowMapEnabled = shadowMap.enabled;
  53553. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  53554. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  53555. const shadowMapType = shadowMap.type;
  53556. initGLContext();
  53557. info.autoReset = infoAutoReset;
  53558. shadowMap.enabled = shadowMapEnabled;
  53559. shadowMap.autoUpdate = shadowMapAutoUpdate;
  53560. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  53561. shadowMap.type = shadowMapType;
  53562. }
  53563. function onContextCreationError( event ) {
  53564. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  53565. }
  53566. function onMaterialDispose( event ) {
  53567. const material = event.target;
  53568. material.removeEventListener( 'dispose', onMaterialDispose );
  53569. deallocateMaterial( material );
  53570. }
  53571. // Buffer deallocation
  53572. function deallocateMaterial( material ) {
  53573. releaseMaterialProgramReferences( material );
  53574. properties.remove( material );
  53575. }
  53576. function releaseMaterialProgramReferences( material ) {
  53577. const programs = properties.get( material ).programs;
  53578. if ( programs !== undefined ) {
  53579. programs.forEach( function ( program ) {
  53580. programCache.releaseProgram( program );
  53581. } );
  53582. if ( material.isShaderMaterial ) {
  53583. programCache.releaseShaderCache( material );
  53584. }
  53585. }
  53586. }
  53587. // Buffer rendering
  53588. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  53589. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  53590. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53591. const program = setProgram( camera, scene, geometry, material, object );
  53592. state.setMaterial( material, frontFaceCW );
  53593. //
  53594. let index = geometry.index;
  53595. let rangeFactor = 1;
  53596. if ( material.wireframe === true ) {
  53597. index = geometries.getWireframeAttribute( geometry );
  53598. if ( index === undefined ) return;
  53599. rangeFactor = 2;
  53600. }
  53601. //
  53602. const drawRange = geometry.drawRange;
  53603. const position = geometry.attributes.position;
  53604. let drawStart = drawRange.start * rangeFactor;
  53605. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  53606. if ( group !== null ) {
  53607. drawStart = Math.max( drawStart, group.start * rangeFactor );
  53608. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  53609. }
  53610. if ( index !== null ) {
  53611. drawStart = Math.max( drawStart, 0 );
  53612. drawEnd = Math.min( drawEnd, index.count );
  53613. } else if ( position !== undefined && position !== null ) {
  53614. drawStart = Math.max( drawStart, 0 );
  53615. drawEnd = Math.min( drawEnd, position.count );
  53616. }
  53617. const drawCount = drawEnd - drawStart;
  53618. if ( drawCount < 0 || drawCount === Infinity ) return;
  53619. //
  53620. bindingStates.setup( object, material, program, geometry, index );
  53621. let attribute;
  53622. let renderer = bufferRenderer;
  53623. if ( index !== null ) {
  53624. attribute = attributes.get( index );
  53625. renderer = indexedBufferRenderer;
  53626. renderer.setIndex( attribute );
  53627. }
  53628. //
  53629. if ( object.isMesh ) {
  53630. if ( material.wireframe === true ) {
  53631. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  53632. renderer.setMode( _gl.LINES );
  53633. } else {
  53634. renderer.setMode( _gl.TRIANGLES );
  53635. }
  53636. } else if ( object.isLine ) {
  53637. let lineWidth = material.linewidth;
  53638. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  53639. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  53640. if ( object.isLineSegments ) {
  53641. renderer.setMode( _gl.LINES );
  53642. } else if ( object.isLineLoop ) {
  53643. renderer.setMode( _gl.LINE_LOOP );
  53644. } else {
  53645. renderer.setMode( _gl.LINE_STRIP );
  53646. }
  53647. } else if ( object.isPoints ) {
  53648. renderer.setMode( _gl.POINTS );
  53649. } else if ( object.isSprite ) {
  53650. renderer.setMode( _gl.TRIANGLES );
  53651. }
  53652. if ( object.isBatchedMesh ) {
  53653. if ( object._multiDrawInstances !== null ) {
  53654. // @deprecated, r174
  53655. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53656. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  53657. } else {
  53658. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  53659. const starts = object._multiDrawStarts;
  53660. const counts = object._multiDrawCounts;
  53661. const drawCount = object._multiDrawCount;
  53662. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  53663. const uniforms = properties.get( material ).currentProgram.getUniforms();
  53664. for ( let i = 0; i < drawCount; i ++ ) {
  53665. uniforms.setValue( _gl, '_gl_DrawID', i );
  53666. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  53667. }
  53668. } else {
  53669. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  53670. }
  53671. }
  53672. } else if ( object.isInstancedMesh ) {
  53673. renderer.renderInstances( drawStart, drawCount, object.count );
  53674. } else if ( geometry.isInstancedBufferGeometry ) {
  53675. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  53676. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  53677. renderer.renderInstances( drawStart, drawCount, instanceCount );
  53678. } else {
  53679. renderer.render( drawStart, drawCount );
  53680. }
  53681. };
  53682. // Compile
  53683. function prepareMaterial( material, scene, object ) {
  53684. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53685. material.side = BackSide;
  53686. material.needsUpdate = true;
  53687. getProgram( material, scene, object );
  53688. material.side = FrontSide;
  53689. material.needsUpdate = true;
  53690. getProgram( material, scene, object );
  53691. material.side = DoubleSide;
  53692. } else {
  53693. getProgram( material, scene, object );
  53694. }
  53695. }
  53696. /**
  53697. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53698. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53699. * optional parameter for applying the target scene.
  53700. *
  53701. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53702. *
  53703. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53704. * @param {Camera} camera - The camera.
  53705. * @param {?Scene} [targetScene=null] - The target scene.
  53706. * @return {Set<Material>} The precompiled materials.
  53707. */
  53708. this.compile = function ( scene, camera, targetScene = null ) {
  53709. if ( targetScene === null ) targetScene = scene;
  53710. currentRenderState = renderStates.get( targetScene );
  53711. currentRenderState.init( camera );
  53712. renderStateStack.push( currentRenderState );
  53713. // gather lights from both the target scene and the new object that will be added to the scene.
  53714. targetScene.traverseVisible( function ( object ) {
  53715. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53716. currentRenderState.pushLight( object );
  53717. if ( object.castShadow ) {
  53718. currentRenderState.pushShadow( object );
  53719. }
  53720. }
  53721. } );
  53722. if ( scene !== targetScene ) {
  53723. scene.traverseVisible( function ( object ) {
  53724. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53725. currentRenderState.pushLight( object );
  53726. if ( object.castShadow ) {
  53727. currentRenderState.pushShadow( object );
  53728. }
  53729. }
  53730. } );
  53731. }
  53732. currentRenderState.setupLights();
  53733. // Only initialize materials in the new scene, not the targetScene.
  53734. const materials = new Set();
  53735. scene.traverse( function ( object ) {
  53736. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53737. return;
  53738. }
  53739. const material = object.material;
  53740. if ( material ) {
  53741. if ( Array.isArray( material ) ) {
  53742. for ( let i = 0; i < material.length; i ++ ) {
  53743. const material2 = material[ i ];
  53744. prepareMaterial( material2, targetScene, object );
  53745. materials.add( material2 );
  53746. }
  53747. } else {
  53748. prepareMaterial( material, targetScene, object );
  53749. materials.add( material );
  53750. }
  53751. }
  53752. } );
  53753. currentRenderState = renderStateStack.pop();
  53754. return materials;
  53755. };
  53756. // compileAsync
  53757. /**
  53758. * Asynchronous version of {@link WebGLRenderer#compile}.
  53759. *
  53760. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53761. * it is recommended to use this version of `compile()` whenever possible.
  53762. *
  53763. * @async
  53764. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53765. * @param {Camera} camera - The camera.
  53766. * @param {?Scene} [targetScene=null] - The target scene.
  53767. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53768. */
  53769. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53770. const materials = this.compile( scene, camera, targetScene );
  53771. // Wait for all the materials in the new object to indicate that they're
  53772. // ready to be used before resolving the promise.
  53773. return new Promise( ( resolve ) => {
  53774. function checkMaterialsReady() {
  53775. materials.forEach( function ( material ) {
  53776. const materialProperties = properties.get( material );
  53777. const program = materialProperties.currentProgram;
  53778. if ( program.isReady() ) {
  53779. // remove any programs that report they're ready to use from the list
  53780. materials.delete( material );
  53781. }
  53782. } );
  53783. // once the list of compiling materials is empty, call the callback
  53784. if ( materials.size === 0 ) {
  53785. resolve( scene );
  53786. return;
  53787. }
  53788. // if some materials are still not ready, wait a bit and check again
  53789. setTimeout( checkMaterialsReady, 10 );
  53790. }
  53791. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53792. // If we can check the compilation status of the materials without
  53793. // blocking then do so right away.
  53794. checkMaterialsReady();
  53795. } else {
  53796. // Otherwise start by waiting a bit to give the materials we just
  53797. // initialized a chance to finish.
  53798. setTimeout( checkMaterialsReady, 10 );
  53799. }
  53800. } );
  53801. };
  53802. // Animation Loop
  53803. let onAnimationFrameCallback = null;
  53804. function onAnimationFrame( time ) {
  53805. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53806. }
  53807. function onXRSessionStart() {
  53808. animation.stop();
  53809. }
  53810. function onXRSessionEnd() {
  53811. animation.start();
  53812. }
  53813. const animation = new WebGLAnimation();
  53814. animation.setAnimationLoop( onAnimationFrame );
  53815. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53816. /**
  53817. * Applications are advised to always define the animation loop
  53818. * with this method and not manually with `requestAnimationFrame()`
  53819. * for best compatibility.
  53820. *
  53821. * @param {?onAnimationCallback} callback - The application's animation loop.
  53822. */
  53823. this.setAnimationLoop = function ( callback ) {
  53824. onAnimationFrameCallback = callback;
  53825. xr.setAnimationLoop( callback );
  53826. ( callback === null ) ? animation.stop() : animation.start();
  53827. };
  53828. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53829. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53830. // Rendering
  53831. /**
  53832. * Renders the given scene (or other type of 3D object) using the given camera.
  53833. *
  53834. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53835. * or to the canvas as usual.
  53836. *
  53837. * By default render buffers are cleared before rendering but you can prevent
  53838. * this by setting the property `autoClear` to `false`. If you want to prevent
  53839. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53840. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53841. *
  53842. * @param {Object3D} scene - The scene to render.
  53843. * @param {Camera} camera - The camera.
  53844. */
  53845. this.render = function ( scene, camera ) {
  53846. if ( camera !== undefined && camera.isCamera !== true ) {
  53847. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53848. return;
  53849. }
  53850. if ( _isContextLost === true ) return;
  53851. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  53852. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  53853. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  53854. // update scene graph
  53855. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53856. // update camera matrices and frustum
  53857. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53858. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  53859. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53860. camera = xr.getCamera(); // use XR camera for rendering
  53861. }
  53862. //
  53863. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53864. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53865. currentRenderState.init( camera );
  53866. renderStateStack.push( currentRenderState );
  53867. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53868. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53869. _localClippingEnabled = this.localClippingEnabled;
  53870. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53871. currentRenderList = renderLists.get( scene, renderListStack.length );
  53872. currentRenderList.init();
  53873. renderListStack.push( currentRenderList );
  53874. if ( xr.enabled === true && xr.isPresenting === true ) {
  53875. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53876. if ( depthSensingMesh !== null ) {
  53877. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53878. }
  53879. }
  53880. projectObject( scene, camera, 0, _this.sortObjects );
  53881. currentRenderList.finish();
  53882. if ( _this.sortObjects === true ) {
  53883. currentRenderList.sort( _opaqueSort, _transparentSort );
  53884. }
  53885. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53886. if ( _renderBackground ) {
  53887. background.addToRenderList( currentRenderList, scene );
  53888. }
  53889. //
  53890. this.info.render.frame ++;
  53891. if ( _clippingEnabled === true ) clipping.beginShadows();
  53892. const shadowsArray = currentRenderState.state.shadowsArray;
  53893. shadowMap.render( shadowsArray, scene, camera );
  53894. if ( _clippingEnabled === true ) clipping.endShadows();
  53895. //
  53896. if ( this.info.autoReset === true ) this.info.reset();
  53897. // render scene (skip if first effect is a render pass - it will render the scene itself)
  53898. const skipSceneRender = useOutput && output.hasRenderPass();
  53899. if ( skipSceneRender === false ) {
  53900. const opaqueObjects = currentRenderList.opaque;
  53901. const transmissiveObjects = currentRenderList.transmissive;
  53902. currentRenderState.setupLights();
  53903. if ( camera.isArrayCamera ) {
  53904. const cameras = camera.cameras;
  53905. if ( transmissiveObjects.length > 0 ) {
  53906. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53907. const camera2 = cameras[ i ];
  53908. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53909. }
  53910. }
  53911. if ( _renderBackground ) background.render( scene );
  53912. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53913. const camera2 = cameras[ i ];
  53914. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53915. }
  53916. } else {
  53917. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53918. if ( _renderBackground ) background.render( scene );
  53919. renderScene( currentRenderList, scene, camera );
  53920. }
  53921. }
  53922. //
  53923. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53924. // resolve multisample renderbuffers to a single-sample texture if necessary
  53925. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53926. // Generate mipmap if we're using any kind of mipmap filtering
  53927. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53928. }
  53929. // copy from internal render target to canvas using fullscreen quad
  53930. if ( useOutput ) {
  53931. output.end( _this );
  53932. }
  53933. //
  53934. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53935. // _gl.finish();
  53936. bindingStates.resetDefaultState();
  53937. _currentMaterialId = -1;
  53938. _currentCamera = null;
  53939. renderStateStack.pop();
  53940. if ( renderStateStack.length > 0 ) {
  53941. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53942. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53943. } else {
  53944. currentRenderState = null;
  53945. }
  53946. renderListStack.pop();
  53947. if ( renderListStack.length > 0 ) {
  53948. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53949. } else {
  53950. currentRenderList = null;
  53951. }
  53952. };
  53953. function projectObject( object, camera, groupOrder, sortObjects ) {
  53954. if ( object.visible === false ) return;
  53955. const visible = object.layers.test( camera.layers );
  53956. if ( visible ) {
  53957. if ( object.isGroup ) {
  53958. groupOrder = object.renderOrder;
  53959. } else if ( object.isLOD ) {
  53960. if ( object.autoUpdate === true ) object.update( camera );
  53961. } else if ( object.isLight ) {
  53962. currentRenderState.pushLight( object );
  53963. if ( object.castShadow ) {
  53964. currentRenderState.pushShadow( object );
  53965. }
  53966. } else if ( object.isSprite ) {
  53967. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53968. if ( sortObjects ) {
  53969. _vector4.setFromMatrixPosition( object.matrixWorld )
  53970. .applyMatrix4( _projScreenMatrix );
  53971. }
  53972. const geometry = objects.update( object );
  53973. const material = object.material;
  53974. if ( material.visible ) {
  53975. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53976. }
  53977. }
  53978. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53979. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53980. const geometry = objects.update( object );
  53981. const material = object.material;
  53982. if ( sortObjects ) {
  53983. if ( object.boundingSphere !== undefined ) {
  53984. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53985. _vector4.copy( object.boundingSphere.center );
  53986. } else {
  53987. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53988. _vector4.copy( geometry.boundingSphere.center );
  53989. }
  53990. _vector4
  53991. .applyMatrix4( object.matrixWorld )
  53992. .applyMatrix4( _projScreenMatrix );
  53993. }
  53994. if ( Array.isArray( material ) ) {
  53995. const groups = geometry.groups;
  53996. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53997. const group = groups[ i ];
  53998. const groupMaterial = material[ group.materialIndex ];
  53999. if ( groupMaterial && groupMaterial.visible ) {
  54000. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  54001. }
  54002. }
  54003. } else if ( material.visible ) {
  54004. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  54005. }
  54006. }
  54007. }
  54008. }
  54009. const children = object.children;
  54010. for ( let i = 0, l = children.length; i < l; i ++ ) {
  54011. projectObject( children[ i ], camera, groupOrder, sortObjects );
  54012. }
  54013. }
  54014. function renderScene( currentRenderList, scene, camera, viewport ) {
  54015. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  54016. currentRenderState.setupLightsView( camera );
  54017. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  54018. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  54019. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  54020. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  54021. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  54022. // Ensure depth buffer writing is enabled so it can be cleared on next render
  54023. state.buffers.depth.setTest( true );
  54024. state.buffers.depth.setMask( true );
  54025. state.buffers.color.setMask( true );
  54026. state.setPolygonOffset( false );
  54027. }
  54028. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  54029. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  54030. if ( overrideMaterial !== null ) {
  54031. return;
  54032. }
  54033. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  54034. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  54035. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  54036. generateMipmaps: true,
  54037. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  54038. minFilter: LinearMipmapLinearFilter,
  54039. samples: capabilities.samples,
  54040. stencilBuffer: stencil,
  54041. resolveDepthBuffer: false,
  54042. resolveStencilBuffer: false,
  54043. colorSpace: ColorManagement.workingColorSpace,
  54044. } );
  54045. // debug
  54046. /*
  54047. const geometry = new PlaneGeometry();
  54048. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  54049. const mesh = new Mesh( geometry, material );
  54050. scene.add( mesh );
  54051. */
  54052. }
  54053. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  54054. const activeViewport = camera.viewport || _currentViewport;
  54055. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  54056. //
  54057. const currentRenderTarget = _this.getRenderTarget();
  54058. const currentActiveCubeFace = _this.getActiveCubeFace();
  54059. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  54060. _this.setRenderTarget( transmissionRenderTarget );
  54061. _this.getClearColor( _currentClearColor );
  54062. _currentClearAlpha = _this.getClearAlpha();
  54063. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  54064. _this.clear();
  54065. if ( _renderBackground ) background.render( scene );
  54066. // Turn off the features which can affect the frag color for opaque objects pass.
  54067. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  54068. const currentToneMapping = _this.toneMapping;
  54069. _this.toneMapping = NoToneMapping;
  54070. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  54071. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  54072. const currentCameraViewport = camera.viewport;
  54073. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  54074. currentRenderState.setupLightsView( camera );
  54075. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  54076. renderObjects( opaqueObjects, scene, camera );
  54077. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  54078. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  54079. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  54080. let renderTargetNeedsUpdate = false;
  54081. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  54082. const renderItem = transmissiveObjects[ i ];
  54083. const { object, geometry, material, group } = renderItem;
  54084. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  54085. const currentSide = material.side;
  54086. material.side = BackSide;
  54087. material.needsUpdate = true;
  54088. renderObject( object, scene, camera, geometry, material, group );
  54089. material.side = currentSide;
  54090. material.needsUpdate = true;
  54091. renderTargetNeedsUpdate = true;
  54092. }
  54093. }
  54094. if ( renderTargetNeedsUpdate === true ) {
  54095. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  54096. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  54097. }
  54098. }
  54099. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  54100. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  54101. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  54102. _this.toneMapping = currentToneMapping;
  54103. }
  54104. function renderObjects( renderList, scene, camera ) {
  54105. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  54106. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  54107. const renderItem = renderList[ i ];
  54108. const { object, geometry, group } = renderItem;
  54109. let material = renderItem.material;
  54110. if ( material.allowOverride === true && overrideMaterial !== null ) {
  54111. material = overrideMaterial;
  54112. }
  54113. if ( object.layers.test( camera.layers ) ) {
  54114. renderObject( object, scene, camera, geometry, material, group );
  54115. }
  54116. }
  54117. }
  54118. function renderObject( object, scene, camera, geometry, material, group ) {
  54119. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  54120. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  54121. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  54122. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  54123. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  54124. material.side = BackSide;
  54125. material.needsUpdate = true;
  54126. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  54127. material.side = FrontSide;
  54128. material.needsUpdate = true;
  54129. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  54130. material.side = DoubleSide;
  54131. } else {
  54132. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  54133. }
  54134. object.onAfterRender( _this, scene, camera, geometry, material, group );
  54135. }
  54136. function getProgram( material, scene, object ) {
  54137. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  54138. const materialProperties = properties.get( material );
  54139. const lights = currentRenderState.state.lights;
  54140. const shadowsArray = currentRenderState.state.shadowsArray;
  54141. const lightsStateVersion = lights.state.version;
  54142. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  54143. const programCacheKey = programCache.getProgramCacheKey( parameters );
  54144. let programs = materialProperties.programs;
  54145. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  54146. materialProperties.environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null;
  54147. materialProperties.fog = scene.fog;
  54148. const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap );
  54149. materialProperties.envMap = environments.get( material.envMap || materialProperties.environment, usePMREM );
  54150. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  54151. if ( programs === undefined ) {
  54152. // new material
  54153. material.addEventListener( 'dispose', onMaterialDispose );
  54154. programs = new Map();
  54155. materialProperties.programs = programs;
  54156. }
  54157. let program = programs.get( programCacheKey );
  54158. if ( program !== undefined ) {
  54159. // early out if program and light state is identical
  54160. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  54161. updateCommonMaterialProperties( material, parameters );
  54162. return program;
  54163. }
  54164. } else {
  54165. parameters.uniforms = programCache.getUniforms( material );
  54166. material.onBeforeCompile( parameters, _this );
  54167. program = programCache.acquireProgram( parameters, programCacheKey );
  54168. programs.set( programCacheKey, program );
  54169. materialProperties.uniforms = parameters.uniforms;
  54170. }
  54171. const uniforms = materialProperties.uniforms;
  54172. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  54173. uniforms.clippingPlanes = clipping.uniform;
  54174. }
  54175. updateCommonMaterialProperties( material, parameters );
  54176. // store the light setup it was created for
  54177. materialProperties.needsLights = materialNeedsLights( material );
  54178. materialProperties.lightsStateVersion = lightsStateVersion;
  54179. if ( materialProperties.needsLights ) {
  54180. // wire up the material to this renderer's lighting state
  54181. uniforms.ambientLightColor.value = lights.state.ambient;
  54182. uniforms.lightProbe.value = lights.state.probe;
  54183. uniforms.directionalLights.value = lights.state.directional;
  54184. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  54185. uniforms.spotLights.value = lights.state.spot;
  54186. uniforms.spotLightShadows.value = lights.state.spotShadow;
  54187. uniforms.rectAreaLights.value = lights.state.rectArea;
  54188. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  54189. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  54190. uniforms.pointLights.value = lights.state.point;
  54191. uniforms.pointLightShadows.value = lights.state.pointShadow;
  54192. uniforms.hemisphereLights.value = lights.state.hemi;
  54193. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  54194. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  54195. uniforms.spotLightMap.value = lights.state.spotLightMap;
  54196. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  54197. // TODO (abelnation): add area lights shadow info to uniforms
  54198. }
  54199. materialProperties.currentProgram = program;
  54200. materialProperties.uniformsList = null;
  54201. return program;
  54202. }
  54203. function getUniformList( materialProperties ) {
  54204. if ( materialProperties.uniformsList === null ) {
  54205. const progUniforms = materialProperties.currentProgram.getUniforms();
  54206. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  54207. }
  54208. return materialProperties.uniformsList;
  54209. }
  54210. function updateCommonMaterialProperties( material, parameters ) {
  54211. const materialProperties = properties.get( material );
  54212. materialProperties.outputColorSpace = parameters.outputColorSpace;
  54213. materialProperties.batching = parameters.batching;
  54214. materialProperties.batchingColor = parameters.batchingColor;
  54215. materialProperties.instancing = parameters.instancing;
  54216. materialProperties.instancingColor = parameters.instancingColor;
  54217. materialProperties.instancingMorph = parameters.instancingMorph;
  54218. materialProperties.skinning = parameters.skinning;
  54219. materialProperties.morphTargets = parameters.morphTargets;
  54220. materialProperties.morphNormals = parameters.morphNormals;
  54221. materialProperties.morphColors = parameters.morphColors;
  54222. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  54223. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  54224. materialProperties.numIntersection = parameters.numClipIntersection;
  54225. materialProperties.vertexAlphas = parameters.vertexAlphas;
  54226. materialProperties.vertexTangents = parameters.vertexTangents;
  54227. materialProperties.toneMapping = parameters.toneMapping;
  54228. }
  54229. function setProgram( camera, scene, geometry, material, object ) {
  54230. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  54231. textures.resetTextureUnits();
  54232. const fog = scene.fog;
  54233. const environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null;
  54234. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  54235. const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap );
  54236. const envMap = environments.get( material.envMap || environment, usePMREM );
  54237. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  54238. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  54239. const morphTargets = !! geometry.morphAttributes.position;
  54240. const morphNormals = !! geometry.morphAttributes.normal;
  54241. const morphColors = !! geometry.morphAttributes.color;
  54242. let toneMapping = NoToneMapping;
  54243. if ( material.toneMapped ) {
  54244. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  54245. toneMapping = _this.toneMapping;
  54246. }
  54247. }
  54248. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  54249. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  54250. const materialProperties = properties.get( material );
  54251. const lights = currentRenderState.state.lights;
  54252. if ( _clippingEnabled === true ) {
  54253. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  54254. const useCache =
  54255. camera === _currentCamera &&
  54256. material.id === _currentMaterialId;
  54257. // we might want to call this function with some ClippingGroup
  54258. // object instead of the material, once it becomes feasible
  54259. // (#8465, #8379)
  54260. clipping.setState( material, camera, useCache );
  54261. }
  54262. }
  54263. //
  54264. let needsProgramChange = false;
  54265. if ( material.version === materialProperties.__version ) {
  54266. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  54267. needsProgramChange = true;
  54268. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  54269. needsProgramChange = true;
  54270. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  54271. needsProgramChange = true;
  54272. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  54273. needsProgramChange = true;
  54274. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  54275. needsProgramChange = true;
  54276. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  54277. needsProgramChange = true;
  54278. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  54279. needsProgramChange = true;
  54280. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  54281. needsProgramChange = true;
  54282. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  54283. needsProgramChange = true;
  54284. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  54285. needsProgramChange = true;
  54286. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  54287. needsProgramChange = true;
  54288. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  54289. needsProgramChange = true;
  54290. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  54291. needsProgramChange = true;
  54292. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  54293. needsProgramChange = true;
  54294. } else if ( materialProperties.envMap !== envMap ) {
  54295. needsProgramChange = true;
  54296. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  54297. needsProgramChange = true;
  54298. } else if ( materialProperties.numClippingPlanes !== undefined &&
  54299. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  54300. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  54301. needsProgramChange = true;
  54302. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  54303. needsProgramChange = true;
  54304. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  54305. needsProgramChange = true;
  54306. } else if ( materialProperties.morphTargets !== morphTargets ) {
  54307. needsProgramChange = true;
  54308. } else if ( materialProperties.morphNormals !== morphNormals ) {
  54309. needsProgramChange = true;
  54310. } else if ( materialProperties.morphColors !== morphColors ) {
  54311. needsProgramChange = true;
  54312. } else if ( materialProperties.toneMapping !== toneMapping ) {
  54313. needsProgramChange = true;
  54314. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  54315. needsProgramChange = true;
  54316. }
  54317. } else {
  54318. needsProgramChange = true;
  54319. materialProperties.__version = material.version;
  54320. }
  54321. //
  54322. let program = materialProperties.currentProgram;
  54323. if ( needsProgramChange === true ) {
  54324. program = getProgram( material, scene, object );
  54325. }
  54326. let refreshProgram = false;
  54327. let refreshMaterial = false;
  54328. let refreshLights = false;
  54329. const p_uniforms = program.getUniforms(),
  54330. m_uniforms = materialProperties.uniforms;
  54331. if ( state.useProgram( program.program ) ) {
  54332. refreshProgram = true;
  54333. refreshMaterial = true;
  54334. refreshLights = true;
  54335. }
  54336. if ( material.id !== _currentMaterialId ) {
  54337. _currentMaterialId = material.id;
  54338. refreshMaterial = true;
  54339. }
  54340. if ( refreshProgram || _currentCamera !== camera ) {
  54341. // common camera uniforms
  54342. const reversedDepthBuffer = state.buffers.depth.getReversed();
  54343. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  54344. camera._reversedDepth = true;
  54345. camera.updateProjectionMatrix();
  54346. }
  54347. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  54348. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  54349. const uCamPos = p_uniforms.map.cameraPosition;
  54350. if ( uCamPos !== undefined ) {
  54351. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  54352. }
  54353. if ( capabilities.logarithmicDepthBuffer ) {
  54354. p_uniforms.setValue( _gl, 'logDepthBufFC',
  54355. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  54356. }
  54357. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  54358. if ( material.isMeshPhongMaterial ||
  54359. material.isMeshToonMaterial ||
  54360. material.isMeshLambertMaterial ||
  54361. material.isMeshBasicMaterial ||
  54362. material.isMeshStandardMaterial ||
  54363. material.isShaderMaterial ) {
  54364. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  54365. }
  54366. if ( _currentCamera !== camera ) {
  54367. _currentCamera = camera;
  54368. // lighting uniforms depend on the camera so enforce an update
  54369. // now, in case this material supports lights - or later, when
  54370. // the next material that does gets activated:
  54371. refreshMaterial = true; // set to true on material change
  54372. refreshLights = true; // remains set until update done
  54373. }
  54374. }
  54375. // Pre-allocate texture units for shadow samplers before setting data textures
  54376. if ( materialProperties.needsLights ) {
  54377. // Set shadow map uniforms first to ensure they get the first texture units
  54378. if ( lights.state.directionalShadowMap.length > 0 ) {
  54379. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  54380. }
  54381. if ( lights.state.spotShadowMap.length > 0 ) {
  54382. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  54383. }
  54384. if ( lights.state.pointShadowMap.length > 0 ) {
  54385. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  54386. }
  54387. }
  54388. // skinning and morph target uniforms must be set even if material didn't change
  54389. // auto-setting of texture unit for bone and morph texture must go before other textures
  54390. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  54391. if ( object.isSkinnedMesh ) {
  54392. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  54393. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  54394. const skeleton = object.skeleton;
  54395. if ( skeleton ) {
  54396. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  54397. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  54398. }
  54399. }
  54400. if ( object.isBatchedMesh ) {
  54401. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  54402. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  54403. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  54404. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  54405. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  54406. if ( object._colorsTexture !== null ) {
  54407. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  54408. }
  54409. }
  54410. const morphAttributes = geometry.morphAttributes;
  54411. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  54412. morphtargets.update( object, geometry, program );
  54413. }
  54414. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  54415. materialProperties.receiveShadow = object.receiveShadow;
  54416. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  54417. }
  54418. if ( ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) && material.envMap === null && scene.environment !== null ) {
  54419. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  54420. }
  54421. // Set DFG LUT for physically-based materials
  54422. if ( m_uniforms.dfgLUT !== undefined ) {
  54423. m_uniforms.dfgLUT.value = getDFGLUT();
  54424. }
  54425. if ( refreshMaterial ) {
  54426. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  54427. if ( materialProperties.needsLights ) {
  54428. // the current material requires lighting info
  54429. // note: all lighting uniforms are always set correctly
  54430. // they simply reference the renderer's state for their
  54431. // values
  54432. //
  54433. // use the current material's .needsUpdate flags to set
  54434. // the GL state when required
  54435. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  54436. }
  54437. // refresh uniforms common to several materials
  54438. if ( fog && material.fog === true ) {
  54439. materials.refreshFogUniforms( m_uniforms, fog );
  54440. }
  54441. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  54442. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54443. }
  54444. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  54445. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54446. material.uniformsNeedUpdate = false;
  54447. }
  54448. if ( material.isSpriteMaterial ) {
  54449. p_uniforms.setValue( _gl, 'center', object.center );
  54450. }
  54451. // common matrices
  54452. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  54453. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  54454. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  54455. // UBOs
  54456. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  54457. const groups = material.uniformsGroups;
  54458. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  54459. const group = groups[ i ];
  54460. uniformsGroups.update( group, program );
  54461. uniformsGroups.bind( group, program );
  54462. }
  54463. }
  54464. return program;
  54465. }
  54466. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  54467. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  54468. uniforms.ambientLightColor.needsUpdate = value;
  54469. uniforms.lightProbe.needsUpdate = value;
  54470. uniforms.directionalLights.needsUpdate = value;
  54471. uniforms.directionalLightShadows.needsUpdate = value;
  54472. uniforms.pointLights.needsUpdate = value;
  54473. uniforms.pointLightShadows.needsUpdate = value;
  54474. uniforms.spotLights.needsUpdate = value;
  54475. uniforms.spotLightShadows.needsUpdate = value;
  54476. uniforms.rectAreaLights.needsUpdate = value;
  54477. uniforms.hemisphereLights.needsUpdate = value;
  54478. }
  54479. function materialNeedsLights( material ) {
  54480. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  54481. material.isMeshStandardMaterial || material.isShadowMaterial ||
  54482. ( material.isShaderMaterial && material.lights === true );
  54483. }
  54484. /**
  54485. * Returns the active cube face.
  54486. *
  54487. * @return {number} The active cube face.
  54488. */
  54489. this.getActiveCubeFace = function () {
  54490. return _currentActiveCubeFace;
  54491. };
  54492. /**
  54493. * Returns the active mipmap level.
  54494. *
  54495. * @return {number} The active mipmap level.
  54496. */
  54497. this.getActiveMipmapLevel = function () {
  54498. return _currentActiveMipmapLevel;
  54499. };
  54500. /**
  54501. * Returns the active render target.
  54502. *
  54503. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  54504. * is currently set.
  54505. */
  54506. this.getRenderTarget = function () {
  54507. return _currentRenderTarget;
  54508. };
  54509. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  54510. const renderTargetProperties = properties.get( renderTarget );
  54511. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  54512. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  54513. // The multisample_render_to_texture extension doesn't work properly if there
  54514. // are midframe flushes and an external depth buffer. Disable use of the extension.
  54515. renderTargetProperties.__useRenderToTexture = false;
  54516. }
  54517. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  54518. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  54519. renderTargetProperties.__hasExternalTextures = true;
  54520. };
  54521. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  54522. const renderTargetProperties = properties.get( renderTarget );
  54523. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  54524. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  54525. };
  54526. const _scratchFrameBuffer = _gl.createFramebuffer();
  54527. /**
  54528. * Sets the active rendertarget.
  54529. *
  54530. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  54531. * the canvas is set as the active render target instead.
  54532. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  54533. * Indicates the z layer to render in to when using 3D or array render targets.
  54534. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  54535. */
  54536. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  54537. _currentRenderTarget = renderTarget;
  54538. _currentActiveCubeFace = activeCubeFace;
  54539. _currentActiveMipmapLevel = activeMipmapLevel;
  54540. let framebuffer = null;
  54541. let isCube = false;
  54542. let isRenderTarget3D = false;
  54543. if ( renderTarget ) {
  54544. const renderTargetProperties = properties.get( renderTarget );
  54545. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  54546. // Externally-managed framebuffer (e.g. XR)
  54547. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  54548. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  54549. _currentViewport.copy( renderTarget.viewport );
  54550. _currentScissor.copy( renderTarget.scissor );
  54551. _currentScissorTest = renderTarget.scissorTest;
  54552. state.viewport( _currentViewport );
  54553. state.scissor( _currentScissor );
  54554. state.setScissorTest( _currentScissorTest );
  54555. _currentMaterialId = -1;
  54556. return;
  54557. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  54558. textures.setupRenderTarget( renderTarget );
  54559. } else if ( renderTargetProperties.__hasExternalTextures ) {
  54560. // Color and depth texture must be rebound in order for the swapchain to update.
  54561. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  54562. } else if ( renderTarget.depthBuffer ) {
  54563. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  54564. const depthTexture = renderTarget.depthTexture;
  54565. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  54566. // check if the depth texture is compatible
  54567. if (
  54568. depthTexture !== null &&
  54569. properties.has( depthTexture ) &&
  54570. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  54571. ) {
  54572. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  54573. }
  54574. // Swap the depth buffer to the currently attached one
  54575. textures.setupDepthRenderbuffer( renderTarget );
  54576. }
  54577. }
  54578. const texture = renderTarget.texture;
  54579. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54580. isRenderTarget3D = true;
  54581. }
  54582. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54583. if ( renderTarget.isWebGLCubeRenderTarget ) {
  54584. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  54585. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  54586. } else {
  54587. framebuffer = __webglFramebuffer[ activeCubeFace ];
  54588. }
  54589. isCube = true;
  54590. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  54591. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  54592. } else {
  54593. if ( Array.isArray( __webglFramebuffer ) ) {
  54594. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  54595. } else {
  54596. framebuffer = __webglFramebuffer;
  54597. }
  54598. }
  54599. _currentViewport.copy( renderTarget.viewport );
  54600. _currentScissor.copy( renderTarget.scissor );
  54601. _currentScissorTest = renderTarget.scissorTest;
  54602. } else {
  54603. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  54604. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  54605. _currentScissorTest = _scissorTest;
  54606. }
  54607. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  54608. // being bound that are different sizes.
  54609. if ( activeMipmapLevel !== 0 ) {
  54610. framebuffer = _scratchFrameBuffer;
  54611. }
  54612. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54613. if ( framebufferBound ) {
  54614. state.drawBuffers( renderTarget, framebuffer );
  54615. }
  54616. state.viewport( _currentViewport );
  54617. state.scissor( _currentScissor );
  54618. state.setScissorTest( _currentScissorTest );
  54619. if ( isCube ) {
  54620. const textureProperties = properties.get( renderTarget.texture );
  54621. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  54622. } else if ( isRenderTarget3D ) {
  54623. const layer = activeCubeFace;
  54624. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  54625. const textureProperties = properties.get( renderTarget.textures[ i ] );
  54626. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  54627. }
  54628. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  54629. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  54630. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  54631. const textureProperties = properties.get( renderTarget.texture );
  54632. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  54633. }
  54634. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  54635. };
  54636. /**
  54637. * Reads the pixel data from the given render target into the given buffer.
  54638. *
  54639. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54640. * @param {number} x - The `x` coordinate of the copy region's origin.
  54641. * @param {number} y - The `y` coordinate of the copy region's origin.
  54642. * @param {number} width - The width of the copy region.
  54643. * @param {number} height - The height of the copy region.
  54644. * @param {TypedArray} buffer - The result buffer.
  54645. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54646. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54647. */
  54648. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54649. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54650. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54651. return;
  54652. }
  54653. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54654. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54655. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54656. }
  54657. if ( framebuffer ) {
  54658. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54659. try {
  54660. const texture = renderTarget.textures[ textureIndex ];
  54661. const textureFormat = texture.format;
  54662. const textureType = texture.type;
  54663. // when using MRT, select the correct color buffer for the subsequent read command
  54664. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54665. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54666. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  54667. return;
  54668. }
  54669. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54670. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54671. return;
  54672. }
  54673. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54674. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54675. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  54676. }
  54677. } finally {
  54678. // restore framebuffer of current render target if necessary
  54679. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54680. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54681. }
  54682. }
  54683. };
  54684. /**
  54685. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  54686. *
  54687. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  54688. *
  54689. * @async
  54690. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54691. * @param {number} x - The `x` coordinate of the copy region's origin.
  54692. * @param {number} y - The `y` coordinate of the copy region's origin.
  54693. * @param {number} width - The width of the copy region.
  54694. * @param {number} height - The height of the copy region.
  54695. * @param {TypedArray} buffer - The result buffer.
  54696. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54697. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54698. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54699. */
  54700. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54701. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54702. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54703. }
  54704. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54705. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54706. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54707. }
  54708. if ( framebuffer ) {
  54709. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54710. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54711. // set the active frame buffer to the one we want to read
  54712. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54713. const texture = renderTarget.textures[ textureIndex ];
  54714. const textureFormat = texture.format;
  54715. const textureType = texture.type;
  54716. // when using MRT, select the correct color buffer for the subsequent read command
  54717. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54718. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54719. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54720. }
  54721. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54722. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54723. }
  54724. const glBuffer = _gl.createBuffer();
  54725. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54726. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54727. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54728. // reset the frame buffer to the currently set buffer before waiting
  54729. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54730. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54731. // check if the commands have finished every 8 ms
  54732. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54733. _gl.flush();
  54734. await probeAsync( _gl, sync, 4 );
  54735. // read the data and delete the buffer
  54736. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54737. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54738. _gl.deleteBuffer( glBuffer );
  54739. _gl.deleteSync( sync );
  54740. return buffer;
  54741. } else {
  54742. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54743. }
  54744. }
  54745. };
  54746. /**
  54747. * Copies pixels from the current bound framebuffer into the given texture.
  54748. *
  54749. * @param {FramebufferTexture} texture - The texture.
  54750. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54751. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54752. */
  54753. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54754. const levelScale = Math.pow( 2, - level );
  54755. const width = Math.floor( texture.image.width * levelScale );
  54756. const height = Math.floor( texture.image.height * levelScale );
  54757. const x = position !== null ? position.x : 0;
  54758. const y = position !== null ? position.y : 0;
  54759. textures.setTexture2D( texture, 0 );
  54760. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54761. state.unbindTexture();
  54762. };
  54763. const _srcFramebuffer = _gl.createFramebuffer();
  54764. const _dstFramebuffer = _gl.createFramebuffer();
  54765. /**
  54766. * Copies data of the given source texture into a destination texture.
  54767. *
  54768. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54769. * {@link WebGLRenderer#initRenderTarget}.
  54770. *
  54771. * @param {Texture} srcTexture - The source texture.
  54772. * @param {Texture} dstTexture - The destination texture.
  54773. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54774. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54775. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54776. * @param {?number} [dstLevel=0] - The destination mipmap level.
  54777. */
  54778. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54779. // gather the necessary dimensions to copy
  54780. let width, height, depth, minX, minY, minZ;
  54781. let dstX, dstY, dstZ;
  54782. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54783. if ( srcRegion !== null ) {
  54784. width = srcRegion.max.x - srcRegion.min.x;
  54785. height = srcRegion.max.y - srcRegion.min.y;
  54786. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54787. minX = srcRegion.min.x;
  54788. minY = srcRegion.min.y;
  54789. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54790. } else {
  54791. const levelScale = Math.pow( 2, - srcLevel );
  54792. width = Math.floor( image.width * levelScale );
  54793. height = Math.floor( image.height * levelScale );
  54794. if ( srcTexture.isDataArrayTexture ) {
  54795. depth = image.depth;
  54796. } else if ( srcTexture.isData3DTexture ) {
  54797. depth = Math.floor( image.depth * levelScale );
  54798. } else {
  54799. depth = 1;
  54800. }
  54801. minX = 0;
  54802. minY = 0;
  54803. minZ = 0;
  54804. }
  54805. if ( dstPosition !== null ) {
  54806. dstX = dstPosition.x;
  54807. dstY = dstPosition.y;
  54808. dstZ = dstPosition.z;
  54809. } else {
  54810. dstX = 0;
  54811. dstY = 0;
  54812. dstZ = 0;
  54813. }
  54814. // Set up the destination target
  54815. const glFormat = utils.convert( dstTexture.format );
  54816. const glType = utils.convert( dstTexture.type );
  54817. let glTarget;
  54818. if ( dstTexture.isData3DTexture ) {
  54819. textures.setTexture3D( dstTexture, 0 );
  54820. glTarget = _gl.TEXTURE_3D;
  54821. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54822. textures.setTexture2DArray( dstTexture, 0 );
  54823. glTarget = _gl.TEXTURE_2D_ARRAY;
  54824. } else {
  54825. textures.setTexture2D( dstTexture, 0 );
  54826. glTarget = _gl.TEXTURE_2D;
  54827. }
  54828. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54829. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54830. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54831. // used for copying data from cpu
  54832. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54833. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54834. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54835. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54836. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54837. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54838. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54839. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54840. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54841. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54842. // set up the src texture
  54843. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54844. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54845. if ( srcTexture.isDepthTexture ) {
  54846. const srcTextureProperties = properties.get( srcTexture );
  54847. const dstTextureProperties = properties.get( dstTexture );
  54848. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54849. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54850. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54851. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54852. for ( let i = 0; i < depth; i ++ ) {
  54853. // if the source or destination are a 3d target then a layer needs to be bound
  54854. if ( isSrc3D ) {
  54855. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54856. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54857. }
  54858. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54859. }
  54860. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54861. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54862. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54863. // get the appropriate frame buffers
  54864. const srcTextureProperties = properties.get( srcTexture );
  54865. const dstTextureProperties = properties.get( dstTexture );
  54866. // bind the frame buffer targets
  54867. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54868. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54869. for ( let i = 0; i < depth; i ++ ) {
  54870. // assign the correct layers and mip maps to the frame buffers
  54871. if ( isSrc3D ) {
  54872. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54873. } else {
  54874. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54875. }
  54876. if ( isDst3D ) {
  54877. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54878. } else {
  54879. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54880. }
  54881. // copy the data using the fastest function that can achieve the copy
  54882. if ( srcLevel !== 0 ) {
  54883. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54884. } else if ( isDst3D ) {
  54885. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54886. } else {
  54887. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54888. }
  54889. }
  54890. // unbind read, draw buffers
  54891. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54892. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54893. } else {
  54894. if ( isDst3D ) {
  54895. // copy data into the 3d texture
  54896. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54897. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54898. } else if ( dstTexture.isCompressedArrayTexture ) {
  54899. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54900. } else {
  54901. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54902. }
  54903. } else {
  54904. // copy data into the 2d texture
  54905. if ( srcTexture.isDataTexture ) {
  54906. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54907. } else if ( srcTexture.isCompressedTexture ) {
  54908. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54909. } else {
  54910. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54911. }
  54912. }
  54913. }
  54914. // reset values
  54915. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54916. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54917. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54918. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54919. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54920. // Generate mipmaps only when copying level 0
  54921. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54922. _gl.generateMipmap( glTarget );
  54923. }
  54924. state.unbindTexture();
  54925. };
  54926. /**
  54927. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54928. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54929. * rendered to.
  54930. *
  54931. * @param {WebGLRenderTarget} target - The render target.
  54932. */
  54933. this.initRenderTarget = function ( target ) {
  54934. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54935. textures.setupRenderTarget( target );
  54936. }
  54937. };
  54938. /**
  54939. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54940. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54941. *
  54942. * @param {Texture} texture - The texture.
  54943. */
  54944. this.initTexture = function ( texture ) {
  54945. if ( texture.isCubeTexture ) {
  54946. textures.setTextureCube( texture, 0 );
  54947. } else if ( texture.isData3DTexture ) {
  54948. textures.setTexture3D( texture, 0 );
  54949. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54950. textures.setTexture2DArray( texture, 0 );
  54951. } else {
  54952. textures.setTexture2D( texture, 0 );
  54953. }
  54954. state.unbindTexture();
  54955. };
  54956. /**
  54957. * Can be used to reset the internal WebGL state. This method is mostly
  54958. * relevant for applications which share a single WebGL context across
  54959. * multiple WebGL libraries.
  54960. */
  54961. this.resetState = function () {
  54962. _currentActiveCubeFace = 0;
  54963. _currentActiveMipmapLevel = 0;
  54964. _currentRenderTarget = null;
  54965. state.reset();
  54966. bindingStates.reset();
  54967. };
  54968. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54969. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54970. }
  54971. }
  54972. /**
  54973. * Defines the coordinate system of the renderer.
  54974. *
  54975. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54976. *
  54977. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54978. * @default WebGLCoordinateSystem
  54979. * @readonly
  54980. */
  54981. get coordinateSystem() {
  54982. return WebGLCoordinateSystem;
  54983. }
  54984. /**
  54985. * Defines the output color space of the renderer.
  54986. *
  54987. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54988. * @default SRGBColorSpace
  54989. */
  54990. get outputColorSpace() {
  54991. return this._outputColorSpace;
  54992. }
  54993. set outputColorSpace( colorSpace ) {
  54994. this._outputColorSpace = colorSpace;
  54995. const gl = this.getContext();
  54996. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54997. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54998. }
  54999. }
  55000. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  55001. exports.AddEquation = AddEquation;
  55002. exports.AddOperation = AddOperation;
  55003. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  55004. exports.AdditiveBlending = AdditiveBlending;
  55005. exports.AgXToneMapping = AgXToneMapping;
  55006. exports.AlphaFormat = AlphaFormat;
  55007. exports.AlwaysCompare = AlwaysCompare;
  55008. exports.AlwaysDepth = AlwaysDepth;
  55009. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  55010. exports.AmbientLight = AmbientLight;
  55011. exports.AnimationAction = AnimationAction;
  55012. exports.AnimationClip = AnimationClip;
  55013. exports.AnimationLoader = AnimationLoader;
  55014. exports.AnimationMixer = AnimationMixer;
  55015. exports.AnimationObjectGroup = AnimationObjectGroup;
  55016. exports.AnimationUtils = AnimationUtils;
  55017. exports.ArcCurve = ArcCurve;
  55018. exports.ArrayCamera = ArrayCamera;
  55019. exports.ArrowHelper = ArrowHelper;
  55020. exports.AttachedBindMode = AttachedBindMode;
  55021. exports.Audio = Audio;
  55022. exports.AudioAnalyser = AudioAnalyser;
  55023. exports.AudioContext = AudioContext;
  55024. exports.AudioListener = AudioListener;
  55025. exports.AudioLoader = AudioLoader;
  55026. exports.AxesHelper = AxesHelper;
  55027. exports.BackSide = BackSide;
  55028. exports.BasicDepthPacking = BasicDepthPacking;
  55029. exports.BasicShadowMap = BasicShadowMap;
  55030. exports.BatchedMesh = BatchedMesh;
  55031. exports.BezierInterpolant = BezierInterpolant;
  55032. exports.Bone = Bone;
  55033. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  55034. exports.Box2 = Box2;
  55035. exports.Box3 = Box3;
  55036. exports.Box3Helper = Box3Helper;
  55037. exports.BoxGeometry = BoxGeometry;
  55038. exports.BoxHelper = BoxHelper;
  55039. exports.BufferAttribute = BufferAttribute;
  55040. exports.BufferGeometry = BufferGeometry;
  55041. exports.BufferGeometryLoader = BufferGeometryLoader;
  55042. exports.ByteType = ByteType;
  55043. exports.Cache = Cache;
  55044. exports.Camera = Camera;
  55045. exports.CameraHelper = CameraHelper;
  55046. exports.CanvasTexture = CanvasTexture;
  55047. exports.CapsuleGeometry = CapsuleGeometry;
  55048. exports.CatmullRomCurve3 = CatmullRomCurve3;
  55049. exports.CineonToneMapping = CineonToneMapping;
  55050. exports.CircleGeometry = CircleGeometry;
  55051. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  55052. exports.Clock = Clock;
  55053. exports.Color = Color;
  55054. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  55055. exports.ColorManagement = ColorManagement;
  55056. exports.Compatibility = Compatibility;
  55057. exports.CompressedArrayTexture = CompressedArrayTexture;
  55058. exports.CompressedCubeTexture = CompressedCubeTexture;
  55059. exports.CompressedTexture = CompressedTexture;
  55060. exports.CompressedTextureLoader = CompressedTextureLoader;
  55061. exports.ConeGeometry = ConeGeometry;
  55062. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  55063. exports.ConstantColorFactor = ConstantColorFactor;
  55064. exports.Controls = Controls;
  55065. exports.CubeCamera = CubeCamera;
  55066. exports.CubeDepthTexture = CubeDepthTexture;
  55067. exports.CubeReflectionMapping = CubeReflectionMapping;
  55068. exports.CubeRefractionMapping = CubeRefractionMapping;
  55069. exports.CubeTexture = CubeTexture;
  55070. exports.CubeTextureLoader = CubeTextureLoader;
  55071. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  55072. exports.CubicBezierCurve = CubicBezierCurve;
  55073. exports.CubicBezierCurve3 = CubicBezierCurve3;
  55074. exports.CubicInterpolant = CubicInterpolant;
  55075. exports.CullFaceBack = CullFaceBack;
  55076. exports.CullFaceFront = CullFaceFront;
  55077. exports.CullFaceFrontBack = CullFaceFrontBack;
  55078. exports.CullFaceNone = CullFaceNone;
  55079. exports.Curve = Curve;
  55080. exports.CurvePath = CurvePath;
  55081. exports.CustomBlending = CustomBlending;
  55082. exports.CustomToneMapping = CustomToneMapping;
  55083. exports.CylinderGeometry = CylinderGeometry;
  55084. exports.Cylindrical = Cylindrical;
  55085. exports.Data3DTexture = Data3DTexture;
  55086. exports.DataArrayTexture = DataArrayTexture;
  55087. exports.DataTexture = DataTexture;
  55088. exports.DataTextureLoader = DataTextureLoader;
  55089. exports.DataUtils = DataUtils;
  55090. exports.DecrementStencilOp = DecrementStencilOp;
  55091. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  55092. exports.DefaultLoadingManager = DefaultLoadingManager;
  55093. exports.DepthFormat = DepthFormat;
  55094. exports.DepthStencilFormat = DepthStencilFormat;
  55095. exports.DepthTexture = DepthTexture;
  55096. exports.DetachedBindMode = DetachedBindMode;
  55097. exports.DirectionalLight = DirectionalLight;
  55098. exports.DirectionalLightHelper = DirectionalLightHelper;
  55099. exports.DiscreteInterpolant = DiscreteInterpolant;
  55100. exports.DodecahedronGeometry = DodecahedronGeometry;
  55101. exports.DoubleSide = DoubleSide;
  55102. exports.DstAlphaFactor = DstAlphaFactor;
  55103. exports.DstColorFactor = DstColorFactor;
  55104. exports.DynamicCopyUsage = DynamicCopyUsage;
  55105. exports.DynamicDrawUsage = DynamicDrawUsage;
  55106. exports.DynamicReadUsage = DynamicReadUsage;
  55107. exports.EdgesGeometry = EdgesGeometry;
  55108. exports.EllipseCurve = EllipseCurve;
  55109. exports.EqualCompare = EqualCompare;
  55110. exports.EqualDepth = EqualDepth;
  55111. exports.EqualStencilFunc = EqualStencilFunc;
  55112. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  55113. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  55114. exports.Euler = Euler;
  55115. exports.EventDispatcher = EventDispatcher;
  55116. exports.ExternalTexture = ExternalTexture;
  55117. exports.ExtrudeGeometry = ExtrudeGeometry;
  55118. exports.FileLoader = FileLoader;
  55119. exports.Float16BufferAttribute = Float16BufferAttribute;
  55120. exports.Float32BufferAttribute = Float32BufferAttribute;
  55121. exports.FloatType = FloatType;
  55122. exports.Fog = Fog;
  55123. exports.FogExp2 = FogExp2;
  55124. exports.FramebufferTexture = FramebufferTexture;
  55125. exports.FrontSide = FrontSide;
  55126. exports.Frustum = Frustum;
  55127. exports.FrustumArray = FrustumArray;
  55128. exports.GLBufferAttribute = GLBufferAttribute;
  55129. exports.GLSL1 = GLSL1;
  55130. exports.GLSL3 = GLSL3;
  55131. exports.GreaterCompare = GreaterCompare;
  55132. exports.GreaterDepth = GreaterDepth;
  55133. exports.GreaterEqualCompare = GreaterEqualCompare;
  55134. exports.GreaterEqualDepth = GreaterEqualDepth;
  55135. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  55136. exports.GreaterStencilFunc = GreaterStencilFunc;
  55137. exports.GridHelper = GridHelper;
  55138. exports.Group = Group;
  55139. exports.HalfFloatType = HalfFloatType;
  55140. exports.HemisphereLight = HemisphereLight;
  55141. exports.HemisphereLightHelper = HemisphereLightHelper;
  55142. exports.IcosahedronGeometry = IcosahedronGeometry;
  55143. exports.ImageBitmapLoader = ImageBitmapLoader;
  55144. exports.ImageLoader = ImageLoader;
  55145. exports.ImageUtils = ImageUtils;
  55146. exports.IncrementStencilOp = IncrementStencilOp;
  55147. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  55148. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  55149. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  55150. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  55151. exports.InstancedMesh = InstancedMesh;
  55152. exports.Int16BufferAttribute = Int16BufferAttribute;
  55153. exports.Int32BufferAttribute = Int32BufferAttribute;
  55154. exports.Int8BufferAttribute = Int8BufferAttribute;
  55155. exports.IntType = IntType;
  55156. exports.InterleavedBuffer = InterleavedBuffer;
  55157. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  55158. exports.Interpolant = Interpolant;
  55159. exports.InterpolateBezier = InterpolateBezier;
  55160. exports.InterpolateDiscrete = InterpolateDiscrete;
  55161. exports.InterpolateLinear = InterpolateLinear;
  55162. exports.InterpolateSmooth = InterpolateSmooth;
  55163. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  55164. exports.InterpolationSamplingType = InterpolationSamplingType;
  55165. exports.InvertStencilOp = InvertStencilOp;
  55166. exports.KeepStencilOp = KeepStencilOp;
  55167. exports.KeyframeTrack = KeyframeTrack;
  55168. exports.LOD = LOD;
  55169. exports.LatheGeometry = LatheGeometry;
  55170. exports.Layers = Layers;
  55171. exports.LessCompare = LessCompare;
  55172. exports.LessDepth = LessDepth;
  55173. exports.LessEqualCompare = LessEqualCompare;
  55174. exports.LessEqualDepth = LessEqualDepth;
  55175. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  55176. exports.LessStencilFunc = LessStencilFunc;
  55177. exports.Light = Light;
  55178. exports.LightProbe = LightProbe;
  55179. exports.Line = Line;
  55180. exports.Line3 = Line3;
  55181. exports.LineBasicMaterial = LineBasicMaterial;
  55182. exports.LineCurve = LineCurve;
  55183. exports.LineCurve3 = LineCurve3;
  55184. exports.LineDashedMaterial = LineDashedMaterial;
  55185. exports.LineLoop = LineLoop;
  55186. exports.LineSegments = LineSegments;
  55187. exports.LinearFilter = LinearFilter;
  55188. exports.LinearInterpolant = LinearInterpolant;
  55189. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  55190. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  55191. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  55192. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  55193. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  55194. exports.LinearToneMapping = LinearToneMapping;
  55195. exports.LinearTransfer = LinearTransfer;
  55196. exports.Loader = Loader;
  55197. exports.LoaderUtils = LoaderUtils;
  55198. exports.LoadingManager = LoadingManager;
  55199. exports.LoopOnce = LoopOnce;
  55200. exports.LoopPingPong = LoopPingPong;
  55201. exports.LoopRepeat = LoopRepeat;
  55202. exports.MOUSE = MOUSE;
  55203. exports.Material = Material;
  55204. exports.MaterialBlending = MaterialBlending;
  55205. exports.MaterialLoader = MaterialLoader;
  55206. exports.MathUtils = MathUtils;
  55207. exports.Matrix2 = Matrix2;
  55208. exports.Matrix3 = Matrix3;
  55209. exports.Matrix4 = Matrix4;
  55210. exports.MaxEquation = MaxEquation;
  55211. exports.Mesh = Mesh;
  55212. exports.MeshBasicMaterial = MeshBasicMaterial;
  55213. exports.MeshDepthMaterial = MeshDepthMaterial;
  55214. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  55215. exports.MeshLambertMaterial = MeshLambertMaterial;
  55216. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  55217. exports.MeshNormalMaterial = MeshNormalMaterial;
  55218. exports.MeshPhongMaterial = MeshPhongMaterial;
  55219. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  55220. exports.MeshStandardMaterial = MeshStandardMaterial;
  55221. exports.MeshToonMaterial = MeshToonMaterial;
  55222. exports.MinEquation = MinEquation;
  55223. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  55224. exports.MixOperation = MixOperation;
  55225. exports.MultiplyBlending = MultiplyBlending;
  55226. exports.MultiplyOperation = MultiplyOperation;
  55227. exports.NearestFilter = NearestFilter;
  55228. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  55229. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  55230. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  55231. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  55232. exports.NeutralToneMapping = NeutralToneMapping;
  55233. exports.NeverCompare = NeverCompare;
  55234. exports.NeverDepth = NeverDepth;
  55235. exports.NeverStencilFunc = NeverStencilFunc;
  55236. exports.NoBlending = NoBlending;
  55237. exports.NoColorSpace = NoColorSpace;
  55238. exports.NoNormalPacking = NoNormalPacking;
  55239. exports.NoToneMapping = NoToneMapping;
  55240. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  55241. exports.NormalBlending = NormalBlending;
  55242. exports.NormalGAPacking = NormalGAPacking;
  55243. exports.NormalRGPacking = NormalRGPacking;
  55244. exports.NotEqualCompare = NotEqualCompare;
  55245. exports.NotEqualDepth = NotEqualDepth;
  55246. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  55247. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  55248. exports.Object3D = Object3D;
  55249. exports.ObjectLoader = ObjectLoader;
  55250. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  55251. exports.OctahedronGeometry = OctahedronGeometry;
  55252. exports.OneFactor = OneFactor;
  55253. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  55254. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  55255. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  55256. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  55257. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  55258. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  55259. exports.OrthographicCamera = OrthographicCamera;
  55260. exports.PCFShadowMap = PCFShadowMap;
  55261. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  55262. exports.PMREMGenerator = PMREMGenerator;
  55263. exports.Path = Path;
  55264. exports.PerspectiveCamera = PerspectiveCamera;
  55265. exports.Plane = Plane;
  55266. exports.PlaneGeometry = PlaneGeometry;
  55267. exports.PlaneHelper = PlaneHelper;
  55268. exports.PointLight = PointLight;
  55269. exports.PointLightHelper = PointLightHelper;
  55270. exports.Points = Points;
  55271. exports.PointsMaterial = PointsMaterial;
  55272. exports.PolarGridHelper = PolarGridHelper;
  55273. exports.PolyhedronGeometry = PolyhedronGeometry;
  55274. exports.PositionalAudio = PositionalAudio;
  55275. exports.PropertyBinding = PropertyBinding;
  55276. exports.PropertyMixer = PropertyMixer;
  55277. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  55278. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  55279. exports.Quaternion = Quaternion;
  55280. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  55281. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  55282. exports.R11_EAC_Format = R11_EAC_Format;
  55283. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  55284. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  55285. exports.REVISION = REVISION;
  55286. exports.RG11_EAC_Format = RG11_EAC_Format;
  55287. exports.RGBADepthPacking = RGBADepthPacking;
  55288. exports.RGBAFormat = RGBAFormat;
  55289. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  55290. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  55291. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  55292. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  55293. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  55294. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  55295. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  55296. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  55297. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  55298. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  55299. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  55300. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  55301. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  55302. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  55303. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  55304. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  55305. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  55306. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  55307. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  55308. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  55309. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  55310. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  55311. exports.RGBDepthPacking = RGBDepthPacking;
  55312. exports.RGBFormat = RGBFormat;
  55313. exports.RGBIntegerFormat = RGBIntegerFormat;
  55314. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  55315. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  55316. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  55317. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  55318. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  55319. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  55320. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  55321. exports.RGDepthPacking = RGDepthPacking;
  55322. exports.RGFormat = RGFormat;
  55323. exports.RGIntegerFormat = RGIntegerFormat;
  55324. exports.RawShaderMaterial = RawShaderMaterial;
  55325. exports.Ray = Ray;
  55326. exports.Raycaster = Raycaster;
  55327. exports.RectAreaLight = RectAreaLight;
  55328. exports.RedFormat = RedFormat;
  55329. exports.RedIntegerFormat = RedIntegerFormat;
  55330. exports.ReinhardToneMapping = ReinhardToneMapping;
  55331. exports.RenderTarget = RenderTarget;
  55332. exports.RenderTarget3D = RenderTarget3D;
  55333. exports.RepeatWrapping = RepeatWrapping;
  55334. exports.ReplaceStencilOp = ReplaceStencilOp;
  55335. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  55336. exports.RingGeometry = RingGeometry;
  55337. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  55338. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  55339. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  55340. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  55341. exports.SRGBColorSpace = SRGBColorSpace;
  55342. exports.SRGBTransfer = SRGBTransfer;
  55343. exports.Scene = Scene;
  55344. exports.ShaderChunk = ShaderChunk;
  55345. exports.ShaderLib = ShaderLib;
  55346. exports.ShaderMaterial = ShaderMaterial;
  55347. exports.ShadowMaterial = ShadowMaterial;
  55348. exports.Shape = Shape;
  55349. exports.ShapeGeometry = ShapeGeometry;
  55350. exports.ShapePath = ShapePath;
  55351. exports.ShapeUtils = ShapeUtils;
  55352. exports.ShortType = ShortType;
  55353. exports.Skeleton = Skeleton;
  55354. exports.SkeletonHelper = SkeletonHelper;
  55355. exports.SkinnedMesh = SkinnedMesh;
  55356. exports.Source = Source;
  55357. exports.Sphere = Sphere;
  55358. exports.SphereGeometry = SphereGeometry;
  55359. exports.Spherical = Spherical;
  55360. exports.SphericalHarmonics3 = SphericalHarmonics3;
  55361. exports.SplineCurve = SplineCurve;
  55362. exports.SpotLight = SpotLight;
  55363. exports.SpotLightHelper = SpotLightHelper;
  55364. exports.Sprite = Sprite;
  55365. exports.SpriteMaterial = SpriteMaterial;
  55366. exports.SrcAlphaFactor = SrcAlphaFactor;
  55367. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  55368. exports.SrcColorFactor = SrcColorFactor;
  55369. exports.StaticCopyUsage = StaticCopyUsage;
  55370. exports.StaticDrawUsage = StaticDrawUsage;
  55371. exports.StaticReadUsage = StaticReadUsage;
  55372. exports.StereoCamera = StereoCamera;
  55373. exports.StreamCopyUsage = StreamCopyUsage;
  55374. exports.StreamDrawUsage = StreamDrawUsage;
  55375. exports.StreamReadUsage = StreamReadUsage;
  55376. exports.StringKeyframeTrack = StringKeyframeTrack;
  55377. exports.SubtractEquation = SubtractEquation;
  55378. exports.SubtractiveBlending = SubtractiveBlending;
  55379. exports.TOUCH = TOUCH;
  55380. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  55381. exports.TetrahedronGeometry = TetrahedronGeometry;
  55382. exports.Texture = Texture;
  55383. exports.TextureLoader = TextureLoader;
  55384. exports.TextureUtils = TextureUtils;
  55385. exports.Timer = Timer;
  55386. exports.TimestampQuery = TimestampQuery;
  55387. exports.TorusGeometry = TorusGeometry;
  55388. exports.TorusKnotGeometry = TorusKnotGeometry;
  55389. exports.Triangle = Triangle;
  55390. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  55391. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  55392. exports.TrianglesDrawMode = TrianglesDrawMode;
  55393. exports.TubeGeometry = TubeGeometry;
  55394. exports.UVMapping = UVMapping;
  55395. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  55396. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  55397. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  55398. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  55399. exports.Uniform = Uniform;
  55400. exports.UniformsGroup = UniformsGroup;
  55401. exports.UniformsLib = UniformsLib;
  55402. exports.UniformsUtils = UniformsUtils;
  55403. exports.UnsignedByteType = UnsignedByteType;
  55404. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  55405. exports.UnsignedInt248Type = UnsignedInt248Type;
  55406. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  55407. exports.UnsignedIntType = UnsignedIntType;
  55408. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  55409. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  55410. exports.UnsignedShortType = UnsignedShortType;
  55411. exports.VSMShadowMap = VSMShadowMap;
  55412. exports.Vector2 = Vector2;
  55413. exports.Vector3 = Vector3;
  55414. exports.Vector4 = Vector4;
  55415. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  55416. exports.VideoFrameTexture = VideoFrameTexture;
  55417. exports.VideoTexture = VideoTexture;
  55418. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  55419. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  55420. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  55421. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  55422. exports.WebGLRenderTarget = WebGLRenderTarget;
  55423. exports.WebGLRenderer = WebGLRenderer;
  55424. exports.WebGLUtils = WebGLUtils;
  55425. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  55426. exports.WebXRController = WebXRController;
  55427. exports.WireframeGeometry = WireframeGeometry;
  55428. exports.WrapAroundEnding = WrapAroundEnding;
  55429. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  55430. exports.ZeroFactor = ZeroFactor;
  55431. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  55432. exports.ZeroStencilOp = ZeroStencilOp;
  55433. exports.createCanvasElement = createCanvasElement;
  55434. exports.error = error;
  55435. exports.getConsoleFunction = getConsoleFunction;
  55436. exports.log = log;
  55437. exports.setConsoleFunction = setConsoleFunction;
  55438. exports.warn = warn;
  55439. exports.warnOnce = warnOnce;
粤ICP备19079148号