three.cjs 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '183dev';
  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. * Zero curvature ending for animations.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const ZeroCurvatureEnding = 2400;
  1038. /**
  1039. * Zero slope ending for animations.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const ZeroSlopeEnding = 2401;
  1045. /**
  1046. * Wrap around ending for animations.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const WrapAroundEnding = 2402;
  1052. /**
  1053. * Default animation blend mode.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const NormalAnimationBlendMode = 2500;
  1059. /**
  1060. * Additive animation blend mode. Can be used to layer motions on top of
  1061. * each other to build complex performances from smaller re-usable assets.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const AdditiveAnimationBlendMode = 2501;
  1067. /**
  1068. * For every three vertices draw a single triangle.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const TrianglesDrawMode = 0;
  1074. /**
  1075. * For each vertex draw a triangle from the last three vertices.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const TriangleStripDrawMode = 1;
  1081. /**
  1082. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const TriangleFanDrawMode = 2;
  1088. /**
  1089. * The depth value is inverted (1.0 - z) for visualization purposes.
  1090. *
  1091. * @type {number}
  1092. * @constant
  1093. */
  1094. const BasicDepthPacking = 3200;
  1095. /**
  1096. * The depth value is packed into 32 bit RGBA.
  1097. *
  1098. * @type {number}
  1099. * @constant
  1100. */
  1101. const RGBADepthPacking = 3201;
  1102. /**
  1103. * The depth value is packed into 24 bit RGB.
  1104. *
  1105. * @type {number}
  1106. * @constant
  1107. */
  1108. const RGBDepthPacking = 3202;
  1109. /**
  1110. * The depth value is packed into 16 bit RG.
  1111. *
  1112. * @type {number}
  1113. * @constant
  1114. */
  1115. const RGDepthPacking = 3203;
  1116. /**
  1117. * Normal information is relative to the underlying surface.
  1118. *
  1119. * @type {number}
  1120. * @constant
  1121. */
  1122. const TangentSpaceNormalMap = 0;
  1123. /**
  1124. * Normal information is relative to the object orientation.
  1125. *
  1126. * @type {number}
  1127. * @constant
  1128. */
  1129. const ObjectSpaceNormalMap = 1;
  1130. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1131. /**
  1132. * No color space.
  1133. *
  1134. * @type {string}
  1135. * @constant
  1136. */
  1137. const NoColorSpace = '';
  1138. /**
  1139. * sRGB color space.
  1140. *
  1141. * @type {string}
  1142. * @constant
  1143. */
  1144. const SRGBColorSpace = 'srgb';
  1145. /**
  1146. * sRGB-linear color space.
  1147. *
  1148. * @type {string}
  1149. * @constant
  1150. */
  1151. const LinearSRGBColorSpace = 'srgb-linear';
  1152. /**
  1153. * Linear transfer function.
  1154. *
  1155. * @type {string}
  1156. * @constant
  1157. */
  1158. const LinearTransfer = 'linear';
  1159. /**
  1160. * sRGB transfer function.
  1161. *
  1162. * @type {string}
  1163. * @constant
  1164. */
  1165. const SRGBTransfer = 'srgb';
  1166. /**
  1167. * No normal map packing.
  1168. *
  1169. * @type {string}
  1170. * @constant
  1171. */
  1172. const NoNormalPacking = '';
  1173. /**
  1174. * Normal RG packing.
  1175. *
  1176. * @type {string}
  1177. * @constant
  1178. */
  1179. const NormalRGPacking = 'rg';
  1180. /**
  1181. * Normal GA packing.
  1182. *
  1183. * @type {string}
  1184. * @constant
  1185. */
  1186. const NormalGAPacking = 'ga';
  1187. /**
  1188. * Sets the stencil buffer value to `0`.
  1189. *
  1190. * @type {number}
  1191. * @constant
  1192. */
  1193. const ZeroStencilOp = 0;
  1194. /**
  1195. * Keeps the current value.
  1196. *
  1197. * @type {number}
  1198. * @constant
  1199. */
  1200. const KeepStencilOp = 7680;
  1201. /**
  1202. * Sets the stencil buffer value to the specified reference value.
  1203. *
  1204. * @type {number}
  1205. * @constant
  1206. */
  1207. const ReplaceStencilOp = 7681;
  1208. /**
  1209. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1210. *
  1211. * @type {number}
  1212. * @constant
  1213. */
  1214. const IncrementStencilOp = 7682;
  1215. /**
  1216. * Decrements the current stencil buffer value. Clamps to `0`.
  1217. *
  1218. * @type {number}
  1219. * @constant
  1220. */
  1221. const DecrementStencilOp = 7683;
  1222. /**
  1223. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1224. * the maximum representable unsigned value.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const IncrementWrapStencilOp = 34055;
  1230. /**
  1231. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1232. * unsigned value when decrementing a stencil buffer value of `0`.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const DecrementWrapStencilOp = 34056;
  1238. /**
  1239. * Inverts the current stencil buffer value bitwise.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const InvertStencilOp = 5386;
  1245. /**
  1246. * Will never return true.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const NeverStencilFunc = 512;
  1252. /**
  1253. * Will return true if the stencil reference value is less than the current stencil value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const LessStencilFunc = 513;
  1259. /**
  1260. * Will return true if the stencil reference value is equal to the current stencil value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const EqualStencilFunc = 514;
  1266. /**
  1267. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const LessEqualStencilFunc = 515;
  1273. /**
  1274. * Will return true if the stencil reference value is greater than the current stencil value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const GreaterStencilFunc = 516;
  1280. /**
  1281. * Will return true if the stencil reference value is not equal to the current stencil value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const NotEqualStencilFunc = 517;
  1287. /**
  1288. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const GreaterEqualStencilFunc = 518;
  1294. /**
  1295. * Will always return true.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const AlwaysStencilFunc = 519;
  1301. /**
  1302. * Never pass.
  1303. *
  1304. * @type {number}
  1305. * @constant
  1306. */
  1307. const NeverCompare = 512;
  1308. /**
  1309. * Pass if the incoming value is less than the texture value.
  1310. *
  1311. * @type {number}
  1312. * @constant
  1313. */
  1314. const LessCompare = 513;
  1315. /**
  1316. * Pass if the incoming value equals the texture value.
  1317. *
  1318. * @type {number}
  1319. * @constant
  1320. */
  1321. const EqualCompare = 514;
  1322. /**
  1323. * Pass if the incoming value is less than or equal to the texture value.
  1324. *
  1325. * @type {number}
  1326. * @constant
  1327. */
  1328. const LessEqualCompare = 515;
  1329. /**
  1330. * Pass if the incoming value is greater than the texture value.
  1331. *
  1332. * @type {number}
  1333. * @constant
  1334. */
  1335. const GreaterCompare = 516;
  1336. /**
  1337. * Pass if the incoming value is not equal to the texture value.
  1338. *
  1339. * @type {number}
  1340. * @constant
  1341. */
  1342. const NotEqualCompare = 517;
  1343. /**
  1344. * Pass if the incoming value is greater than or equal to the texture value.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const GreaterEqualCompare = 518;
  1350. /**
  1351. * Always pass.
  1352. *
  1353. * @type {number}
  1354. * @constant
  1355. */
  1356. const AlwaysCompare = 519;
  1357. /**
  1358. * The contents are intended to be specified once by the application, and used many
  1359. * times as the source for drawing and image specification commands.
  1360. *
  1361. * @type {number}
  1362. * @constant
  1363. */
  1364. const StaticDrawUsage = 35044;
  1365. /**
  1366. * The contents are intended to be respecified repeatedly by the application, and
  1367. * used many times as the source for drawing and image specification commands.
  1368. *
  1369. * @type {number}
  1370. * @constant
  1371. */
  1372. const DynamicDrawUsage = 35048;
  1373. /**
  1374. * The contents are intended to be specified once by the application, and used at most
  1375. * a few times as the source for drawing and image specification commands.
  1376. *
  1377. * @type {number}
  1378. * @constant
  1379. */
  1380. const StreamDrawUsage = 35040;
  1381. /**
  1382. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1383. * many times by the application.
  1384. *
  1385. * @type {number}
  1386. * @constant
  1387. */
  1388. const StaticReadUsage = 35045;
  1389. /**
  1390. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1391. * many times by the application.
  1392. *
  1393. * @type {number}
  1394. * @constant
  1395. */
  1396. const DynamicReadUsage = 35049;
  1397. /**
  1398. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1399. * a few times by the application
  1400. *
  1401. * @type {number}
  1402. * @constant
  1403. */
  1404. const StreamReadUsage = 35041;
  1405. /**
  1406. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1407. * the source for WebGL drawing and image specification commands.
  1408. *
  1409. * @type {number}
  1410. * @constant
  1411. */
  1412. const StaticCopyUsage = 35046;
  1413. /**
  1414. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1415. * as the source for WebGL drawing and image specification commands.
  1416. *
  1417. * @type {number}
  1418. * @constant
  1419. */
  1420. const DynamicCopyUsage = 35050;
  1421. /**
  1422. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1423. * as the source for WebGL drawing and image specification commands.
  1424. *
  1425. * @type {number}
  1426. * @constant
  1427. */
  1428. const StreamCopyUsage = 35042;
  1429. /**
  1430. * GLSL 1 shader code.
  1431. *
  1432. * @type {string}
  1433. * @constant
  1434. */
  1435. const GLSL1 = '100';
  1436. /**
  1437. * GLSL 3 shader code.
  1438. *
  1439. * @type {string}
  1440. * @constant
  1441. */
  1442. const GLSL3 = '300 es';
  1443. /**
  1444. * WebGL coordinate system.
  1445. *
  1446. * @type {number}
  1447. * @constant
  1448. */
  1449. const WebGLCoordinateSystem = 2000;
  1450. /**
  1451. * WebGPU coordinate system.
  1452. *
  1453. * @type {number}
  1454. * @constant
  1455. */
  1456. const WebGPUCoordinateSystem = 2001;
  1457. /**
  1458. * Represents the different timestamp query types.
  1459. *
  1460. * @type {ConstantsTimestampQuery}
  1461. * @constant
  1462. */
  1463. const TimestampQuery = {
  1464. COMPUTE: 'compute',
  1465. RENDER: 'render'
  1466. };
  1467. /**
  1468. * Represents mouse buttons and interaction types in context of controls.
  1469. *
  1470. * @type {ConstantsInterpolationSamplingType}
  1471. * @constant
  1472. */
  1473. const InterpolationSamplingType = {
  1474. PERSPECTIVE: 'perspective',
  1475. LINEAR: 'linear',
  1476. FLAT: 'flat'
  1477. };
  1478. /**
  1479. * Represents the different interpolation sampling modes.
  1480. *
  1481. * @type {ConstantsInterpolationSamplingMode}
  1482. * @constant
  1483. */
  1484. const InterpolationSamplingMode = {
  1485. NORMAL: 'normal',
  1486. CENTROID: 'centroid',
  1487. SAMPLE: 'sample',
  1488. FIRST: 'first',
  1489. EITHER: 'either'
  1490. };
  1491. /**
  1492. * Compatibility flags for features that may not be supported across all platforms.
  1493. *
  1494. * @type {Object}
  1495. * @constant
  1496. */
  1497. const Compatibility = {
  1498. TEXTURE_COMPARE: 'depthTextureCompare'
  1499. };
  1500. /**
  1501. * This type represents mouse buttons and interaction types in context of controls.
  1502. *
  1503. * @typedef {Object} ConstantsMouse
  1504. * @property {number} MIDDLE - The left mouse button.
  1505. * @property {number} LEFT - The middle mouse button.
  1506. * @property {number} RIGHT - The right mouse button.
  1507. * @property {number} ROTATE - A rotate interaction.
  1508. * @property {number} DOLLY - A dolly interaction.
  1509. * @property {number} PAN - A pan interaction.
  1510. **/
  1511. /**
  1512. * This type represents touch interaction types in context of controls.
  1513. *
  1514. * @typedef {Object} ConstantsTouch
  1515. * @property {number} ROTATE - A rotate interaction.
  1516. * @property {number} PAN - A pan interaction.
  1517. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1518. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1519. **/
  1520. /**
  1521. * This type represents the different timestamp query types.
  1522. *
  1523. * @typedef {Object} ConstantsTimestampQuery
  1524. * @property {string} COMPUTE - A `compute` timestamp query.
  1525. * @property {string} RENDER - A `render` timestamp query.
  1526. **/
  1527. /**
  1528. * Represents the different interpolation sampling types.
  1529. *
  1530. * @typedef {Object} ConstantsInterpolationSamplingType
  1531. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1532. * @property {string} LINEAR - Linear interpolation.
  1533. * @property {string} FLAT - Flat interpolation.
  1534. */
  1535. /**
  1536. * Represents the different interpolation sampling modes.
  1537. *
  1538. * @typedef {Object} ConstantsInterpolationSamplingMode
  1539. * @property {string} NORMAL - Normal sampling mode.
  1540. * @property {string} CENTROID - Centroid sampling mode.
  1541. * @property {string} SAMPLE - Sample-specific sampling mode.
  1542. * @property {string} FIRST - Flat interpolation using the first vertex.
  1543. * @property {string} EITHER - Flat interpolation using either vertex.
  1544. */
  1545. function arrayNeedsUint32( array ) {
  1546. // assumes larger values usually on last
  1547. for ( let i = array.length - 1; i >= 0; -- i ) {
  1548. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1549. }
  1550. return false;
  1551. }
  1552. const TYPED_ARRAYS = {
  1553. Int8Array: Int8Array,
  1554. Uint8Array: Uint8Array,
  1555. Uint8ClampedArray: Uint8ClampedArray,
  1556. Int16Array: Int16Array,
  1557. Uint16Array: Uint16Array,
  1558. Int32Array: Int32Array,
  1559. Uint32Array: Uint32Array,
  1560. Float32Array: Float32Array,
  1561. Float64Array: Float64Array
  1562. };
  1563. function getTypedArray( type, buffer ) {
  1564. return new TYPED_ARRAYS[ type ]( buffer );
  1565. }
  1566. /**
  1567. * Returns `true` if the given object is a typed array.
  1568. *
  1569. * @param {any} array - The object to check.
  1570. * @return {boolean} Whether the given object is a typed array.
  1571. */
  1572. function isTypedArray( array ) {
  1573. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1574. }
  1575. function createElementNS( name ) {
  1576. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1577. }
  1578. function createCanvasElement() {
  1579. const canvas = createElementNS( 'canvas' );
  1580. canvas.style.display = 'block';
  1581. return canvas;
  1582. }
  1583. const _cache = {};
  1584. let _setConsoleFunction = null;
  1585. function setConsoleFunction( fn ) {
  1586. _setConsoleFunction = fn;
  1587. }
  1588. function getConsoleFunction() {
  1589. return _setConsoleFunction;
  1590. }
  1591. function log( ...params ) {
  1592. const message = 'THREE.' + params.shift();
  1593. if ( _setConsoleFunction ) {
  1594. _setConsoleFunction( 'log', message, ...params );
  1595. } else {
  1596. console.log( message, ...params );
  1597. }
  1598. }
  1599. function warn( ...params ) {
  1600. const message = 'THREE.' + params.shift();
  1601. if ( _setConsoleFunction ) {
  1602. _setConsoleFunction( 'warn', message, ...params );
  1603. } else {
  1604. console.warn( message, ...params );
  1605. }
  1606. }
  1607. function error( ...params ) {
  1608. const message = 'THREE.' + params.shift();
  1609. if ( _setConsoleFunction ) {
  1610. _setConsoleFunction( 'error', message, ...params );
  1611. } else {
  1612. console.error( message, ...params );
  1613. }
  1614. }
  1615. function warnOnce( ...params ) {
  1616. const message = params.join( ' ' );
  1617. if ( message in _cache ) return;
  1618. _cache[ message ] = true;
  1619. warn( ...params );
  1620. }
  1621. function probeAsync( gl, sync, interval ) {
  1622. return new Promise( function ( resolve, reject ) {
  1623. function probe() {
  1624. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1625. case gl.WAIT_FAILED:
  1626. reject();
  1627. break;
  1628. case gl.TIMEOUT_EXPIRED:
  1629. setTimeout( probe, interval );
  1630. break;
  1631. default:
  1632. resolve();
  1633. }
  1634. }
  1635. setTimeout( probe, interval );
  1636. } );
  1637. }
  1638. /**
  1639. * This modules allows to dispatch event objects on custom JavaScript objects.
  1640. *
  1641. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1642. *
  1643. * Code Example:
  1644. * ```js
  1645. * class Car extends EventDispatcher {
  1646. * start() {
  1647. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1648. * }
  1649. *};
  1650. *
  1651. * // Using events with the custom object
  1652. * const car = new Car();
  1653. * car.addEventListener( 'start', function ( event ) {
  1654. * alert( event.message );
  1655. * } );
  1656. *
  1657. * car.start();
  1658. * ```
  1659. */
  1660. class EventDispatcher {
  1661. /**
  1662. * Adds the given event listener to the given event type.
  1663. *
  1664. * @param {string} type - The type of event to listen to.
  1665. * @param {Function} listener - The function that gets called when the event is fired.
  1666. */
  1667. addEventListener( type, listener ) {
  1668. if ( this._listeners === undefined ) this._listeners = {};
  1669. const listeners = this._listeners;
  1670. if ( listeners[ type ] === undefined ) {
  1671. listeners[ type ] = [];
  1672. }
  1673. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1674. listeners[ type ].push( listener );
  1675. }
  1676. }
  1677. /**
  1678. * Returns `true` if the given event listener has been added to the given event type.
  1679. *
  1680. * @param {string} type - The type of event.
  1681. * @param {Function} listener - The listener to check.
  1682. * @return {boolean} Whether the given event listener has been added to the given event type.
  1683. */
  1684. hasEventListener( type, listener ) {
  1685. const listeners = this._listeners;
  1686. if ( listeners === undefined ) return false;
  1687. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1688. }
  1689. /**
  1690. * Removes the given event listener from the given event type.
  1691. *
  1692. * @param {string} type - The type of event.
  1693. * @param {Function} listener - The listener to remove.
  1694. */
  1695. removeEventListener( type, listener ) {
  1696. const listeners = this._listeners;
  1697. if ( listeners === undefined ) return;
  1698. const listenerArray = listeners[ type ];
  1699. if ( listenerArray !== undefined ) {
  1700. const index = listenerArray.indexOf( listener );
  1701. if ( index !== -1 ) {
  1702. listenerArray.splice( index, 1 );
  1703. }
  1704. }
  1705. }
  1706. /**
  1707. * Dispatches an event object.
  1708. *
  1709. * @param {Object} event - The event that gets fired.
  1710. */
  1711. dispatchEvent( event ) {
  1712. const listeners = this._listeners;
  1713. if ( listeners === undefined ) return;
  1714. const listenerArray = listeners[ event.type ];
  1715. if ( listenerArray !== undefined ) {
  1716. event.target = this;
  1717. // Make a copy, in case listeners are removed while iterating.
  1718. const array = listenerArray.slice( 0 );
  1719. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1720. array[ i ].call( this, event );
  1721. }
  1722. event.target = null;
  1723. }
  1724. }
  1725. }
  1726. 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' ];
  1727. let _seed = 1234567;
  1728. const DEG2RAD = Math.PI / 180;
  1729. const RAD2DEG = 180 / Math.PI;
  1730. /**
  1731. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1732. * (universally unique identifier).
  1733. *
  1734. * @return {string} The UUID.
  1735. */
  1736. function generateUUID() {
  1737. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1738. const d0 = Math.random() * 0xffffffff | 0;
  1739. const d1 = Math.random() * 0xffffffff | 0;
  1740. const d2 = Math.random() * 0xffffffff | 0;
  1741. const d3 = Math.random() * 0xffffffff | 0;
  1742. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1743. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1744. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1745. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1746. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1747. return uuid.toLowerCase();
  1748. }
  1749. /**
  1750. * Clamps the given value between min and max.
  1751. *
  1752. * @param {number} value - The value to clamp.
  1753. * @param {number} min - The min value.
  1754. * @param {number} max - The max value.
  1755. * @return {number} The clamped value.
  1756. */
  1757. function clamp( value, min, max ) {
  1758. return Math.max( min, Math.min( max, value ) );
  1759. }
  1760. /**
  1761. * Computes the Euclidean modulo of the given parameters that
  1762. * is `( ( n % m ) + m ) % m`.
  1763. *
  1764. * @param {number} n - The first parameter.
  1765. * @param {number} m - The second parameter.
  1766. * @return {number} The Euclidean modulo.
  1767. */
  1768. function euclideanModulo( n, m ) {
  1769. // https://en.wikipedia.org/wiki/Modulo_operation
  1770. return ( ( n % m ) + m ) % m;
  1771. }
  1772. /**
  1773. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1774. * for the given value.
  1775. *
  1776. * @param {number} x - The value to be mapped.
  1777. * @param {number} a1 - Minimum value for range A.
  1778. * @param {number} a2 - Maximum value for range A.
  1779. * @param {number} b1 - Minimum value for range B.
  1780. * @param {number} b2 - Maximum value for range B.
  1781. * @return {number} The mapped value.
  1782. */
  1783. function mapLinear( x, a1, a2, b1, b2 ) {
  1784. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1785. }
  1786. /**
  1787. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1788. * between the start and end point.
  1789. *
  1790. * @param {number} x - The start point
  1791. * @param {number} y - The end point.
  1792. * @param {number} value - A value between start and end.
  1793. * @return {number} The interpolation factor.
  1794. */
  1795. function inverseLerp( x, y, value ) {
  1796. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1797. if ( x !== y ) {
  1798. return ( value - x ) / ( y - x );
  1799. } else {
  1800. return 0;
  1801. }
  1802. }
  1803. /**
  1804. * Returns a value linearly interpolated from two known points based on the given interval -
  1805. * `t = 0` will return `x` and `t = 1` will return `y`.
  1806. *
  1807. * @param {number} x - The start point
  1808. * @param {number} y - The end point.
  1809. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1810. * @return {number} The interpolated value.
  1811. */
  1812. function lerp( x, y, t ) {
  1813. return ( 1 - t ) * x + t * y;
  1814. }
  1815. /**
  1816. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1817. * time to maintain frame rate independent movement. For details, see
  1818. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1819. *
  1820. * @param {number} x - The current point.
  1821. * @param {number} y - The target point.
  1822. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1823. * and a lower value will make the movement more gradual.
  1824. * @param {number} dt - Delta time in seconds.
  1825. * @return {number} The interpolated value.
  1826. */
  1827. function damp( x, y, lambda, dt ) {
  1828. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1829. }
  1830. /**
  1831. * Returns a value that alternates between `0` and the given `length` parameter.
  1832. *
  1833. * @param {number} x - The value to pingpong.
  1834. * @param {number} [length=1] - The positive value the function will pingpong to.
  1835. * @return {number} The alternated value.
  1836. */
  1837. function pingpong( x, length = 1 ) {
  1838. // https://www.desmos.com/calculator/vcsjnyz7x4
  1839. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1840. }
  1841. /**
  1842. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1843. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1844. * the `min` and `max`.
  1845. *
  1846. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1847. *
  1848. * @param {number} x - The value to evaluate based on its position between min and max.
  1849. * @param {number} min - The min value. Any x value below min will be `0`.
  1850. * @param {number} max - The max value. Any x value above max will be `1`.
  1851. * @return {number} The alternated value.
  1852. */
  1853. function smoothstep( x, min, max ) {
  1854. if ( x <= min ) return 0;
  1855. if ( x >= max ) return 1;
  1856. x = ( x - min ) / ( max - min );
  1857. return x * x * ( 3 - 2 * x );
  1858. }
  1859. /**
  1860. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1861. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1862. *
  1863. * @param {number} x - The value to evaluate based on its position between min and max.
  1864. * @param {number} min - The min value. Any x value below min will be `0`.
  1865. * @param {number} max - The max value. Any x value above max will be `1`.
  1866. * @return {number} The alternated value.
  1867. */
  1868. function smootherstep( x, min, max ) {
  1869. if ( x <= min ) return 0;
  1870. if ( x >= max ) return 1;
  1871. x = ( x - min ) / ( max - min );
  1872. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1873. }
  1874. /**
  1875. * Returns a random integer from `<low, high>` interval.
  1876. *
  1877. * @param {number} low - The lower value boundary.
  1878. * @param {number} high - The upper value boundary
  1879. * @return {number} A random integer.
  1880. */
  1881. function randInt( low, high ) {
  1882. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1883. }
  1884. /**
  1885. * Returns a random float from `<low, high>` interval.
  1886. *
  1887. * @param {number} low - The lower value boundary.
  1888. * @param {number} high - The upper value boundary
  1889. * @return {number} A random float.
  1890. */
  1891. function randFloat( low, high ) {
  1892. return low + Math.random() * ( high - low );
  1893. }
  1894. /**
  1895. * Returns a random integer from `<-range/2, range/2>` interval.
  1896. *
  1897. * @param {number} range - Defines the value range.
  1898. * @return {number} A random float.
  1899. */
  1900. function randFloatSpread( range ) {
  1901. return range * ( 0.5 - Math.random() );
  1902. }
  1903. /**
  1904. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1905. *
  1906. * @param {number} [s] - The integer seed.
  1907. * @return {number} A random float.
  1908. */
  1909. function seededRandom( s ) {
  1910. if ( s !== undefined ) _seed = s;
  1911. // Mulberry32 generator
  1912. let t = _seed += 0x6D2B79F5;
  1913. t = Math.imul( t ^ t >>> 15, t | 1 );
  1914. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1915. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1916. }
  1917. /**
  1918. * Converts degrees to radians.
  1919. *
  1920. * @param {number} degrees - A value in degrees.
  1921. * @return {number} The converted value in radians.
  1922. */
  1923. function degToRad( degrees ) {
  1924. return degrees * DEG2RAD;
  1925. }
  1926. /**
  1927. * Converts radians to degrees.
  1928. *
  1929. * @param {number} radians - A value in radians.
  1930. * @return {number} The converted value in degrees.
  1931. */
  1932. function radToDeg( radians ) {
  1933. return radians * RAD2DEG;
  1934. }
  1935. /**
  1936. * Returns `true` if the given number is a power of two.
  1937. *
  1938. * @param {number} value - The value to check.
  1939. * @return {boolean} Whether the given number is a power of two or not.
  1940. */
  1941. function isPowerOfTwo( value ) {
  1942. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1943. }
  1944. /**
  1945. * Returns the smallest power of two that is greater than or equal to the given number.
  1946. *
  1947. * @param {number} value - The value to find a POT for.
  1948. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1949. */
  1950. function ceilPowerOfTwo( value ) {
  1951. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1952. }
  1953. /**
  1954. * Returns the largest power of two that is less than or equal to the given number.
  1955. *
  1956. * @param {number} value - The value to find a POT for.
  1957. * @return {number} The largest power of two that is less than or equal to the given number.
  1958. */
  1959. function floorPowerOfTwo( value ) {
  1960. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1961. }
  1962. /**
  1963. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  1964. * defined by the given angles and order.
  1965. *
  1966. * Rotations are applied to the axes in the order specified by order:
  1967. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1968. *
  1969. * @param {Quaternion} q - The quaternion to set.
  1970. * @param {number} a - The rotation applied to the first axis, in radians.
  1971. * @param {number} b - The rotation applied to the second axis, in radians.
  1972. * @param {number} c - The rotation applied to the third axis, in radians.
  1973. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1974. */
  1975. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1976. const cos = Math.cos;
  1977. const sin = Math.sin;
  1978. const c2 = cos( b / 2 );
  1979. const s2 = sin( b / 2 );
  1980. const c13 = cos( ( a + c ) / 2 );
  1981. const s13 = sin( ( a + c ) / 2 );
  1982. const c1_3 = cos( ( a - c ) / 2 );
  1983. const s1_3 = sin( ( a - c ) / 2 );
  1984. const c3_1 = cos( ( c - a ) / 2 );
  1985. const s3_1 = sin( ( c - a ) / 2 );
  1986. switch ( order ) {
  1987. case 'XYX':
  1988. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1989. break;
  1990. case 'YZY':
  1991. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1992. break;
  1993. case 'ZXZ':
  1994. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1995. break;
  1996. case 'XZX':
  1997. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1998. break;
  1999. case 'YXY':
  2000. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2001. break;
  2002. case 'ZYZ':
  2003. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2004. break;
  2005. default:
  2006. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2007. }
  2008. }
  2009. /**
  2010. * Denormalizes the given value according to the given typed array.
  2011. *
  2012. * @param {number} value - The value to denormalize.
  2013. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2014. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2015. */
  2016. function denormalize( value, array ) {
  2017. switch ( array.constructor ) {
  2018. case Float32Array:
  2019. return value;
  2020. case Uint32Array:
  2021. return value / 4294967295.0;
  2022. case Uint16Array:
  2023. return value / 65535.0;
  2024. case Uint8Array:
  2025. return value / 255.0;
  2026. case Int32Array:
  2027. return Math.max( value / 2147483647.0, -1 );
  2028. case Int16Array:
  2029. return Math.max( value / 32767.0, -1 );
  2030. case Int8Array:
  2031. return Math.max( value / 127.0, -1 );
  2032. default:
  2033. throw new Error( 'Invalid component type.' );
  2034. }
  2035. }
  2036. /**
  2037. * Normalizes the given value according to the given typed array.
  2038. *
  2039. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2040. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2041. * @return {number} The normalize value.
  2042. */
  2043. function normalize( value, array ) {
  2044. switch ( array.constructor ) {
  2045. case Float32Array:
  2046. return value;
  2047. case Uint32Array:
  2048. return Math.round( value * 4294967295.0 );
  2049. case Uint16Array:
  2050. return Math.round( value * 65535.0 );
  2051. case Uint8Array:
  2052. return Math.round( value * 255.0 );
  2053. case Int32Array:
  2054. return Math.round( value * 2147483647.0 );
  2055. case Int16Array:
  2056. return Math.round( value * 32767.0 );
  2057. case Int8Array:
  2058. return Math.round( value * 127.0 );
  2059. default:
  2060. throw new Error( 'Invalid component type.' );
  2061. }
  2062. }
  2063. /**
  2064. * @class
  2065. * @classdesc A collection of math utility functions.
  2066. * @hideconstructor
  2067. */
  2068. const MathUtils = {
  2069. DEG2RAD: DEG2RAD,
  2070. RAD2DEG: RAD2DEG,
  2071. /**
  2072. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2073. * (universally unique identifier).
  2074. *
  2075. * @static
  2076. * @method
  2077. * @return {string} The UUID.
  2078. */
  2079. generateUUID: generateUUID,
  2080. /**
  2081. * Clamps the given value between min and max.
  2082. *
  2083. * @static
  2084. * @method
  2085. * @param {number} value - The value to clamp.
  2086. * @param {number} min - The min value.
  2087. * @param {number} max - The max value.
  2088. * @return {number} The clamped value.
  2089. */
  2090. clamp: clamp,
  2091. /**
  2092. * Computes the Euclidean modulo of the given parameters that
  2093. * is `( ( n % m ) + m ) % m`.
  2094. *
  2095. * @static
  2096. * @method
  2097. * @param {number} n - The first parameter.
  2098. * @param {number} m - The second parameter.
  2099. * @return {number} The Euclidean modulo.
  2100. */
  2101. euclideanModulo: euclideanModulo,
  2102. /**
  2103. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2104. * for the given value.
  2105. *
  2106. * @static
  2107. * @method
  2108. * @param {number} x - The value to be mapped.
  2109. * @param {number} a1 - Minimum value for range A.
  2110. * @param {number} a2 - Maximum value for range A.
  2111. * @param {number} b1 - Minimum value for range B.
  2112. * @param {number} b2 - Maximum value for range B.
  2113. * @return {number} The mapped value.
  2114. */
  2115. mapLinear: mapLinear,
  2116. /**
  2117. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2118. * between the start and end point.
  2119. *
  2120. * @static
  2121. * @method
  2122. * @param {number} x - The start point
  2123. * @param {number} y - The end point.
  2124. * @param {number} value - A value between start and end.
  2125. * @return {number} The interpolation factor.
  2126. */
  2127. inverseLerp: inverseLerp,
  2128. /**
  2129. * Returns a value linearly interpolated from two known points based on the given interval -
  2130. * `t = 0` will return `x` and `t = 1` will return `y`.
  2131. *
  2132. * @static
  2133. * @method
  2134. * @param {number} x - The start point
  2135. * @param {number} y - The end point.
  2136. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2137. * @return {number} The interpolated value.
  2138. */
  2139. lerp: lerp,
  2140. /**
  2141. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2142. * time to maintain frame rate independent movement. For details, see
  2143. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2144. *
  2145. * @static
  2146. * @method
  2147. * @param {number} x - The current point.
  2148. * @param {number} y - The target point.
  2149. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2150. * and a lower value will make the movement more gradual.
  2151. * @param {number} dt - Delta time in seconds.
  2152. * @return {number} The interpolated value.
  2153. */
  2154. damp: damp,
  2155. /**
  2156. * Returns a value that alternates between `0` and the given `length` parameter.
  2157. *
  2158. * @static
  2159. * @method
  2160. * @param {number} x - The value to pingpong.
  2161. * @param {number} [length=1] - The positive value the function will pingpong to.
  2162. * @return {number} The alternated value.
  2163. */
  2164. pingpong: pingpong,
  2165. /**
  2166. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2167. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2168. * the `min` and `max`.
  2169. *
  2170. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2171. *
  2172. * @static
  2173. * @method
  2174. * @param {number} x - The value to evaluate based on its position between min and max.
  2175. * @param {number} min - The min value. Any x value below min will be `0`.
  2176. * @param {number} max - The max value. Any x value above max will be `1`.
  2177. * @return {number} The alternated value.
  2178. */
  2179. smoothstep: smoothstep,
  2180. /**
  2181. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2182. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2183. *
  2184. * @static
  2185. * @method
  2186. * @param {number} x - The value to evaluate based on its position between min and max.
  2187. * @param {number} min - The min value. Any x value below min will be `0`.
  2188. * @param {number} max - The max value. Any x value above max will be `1`.
  2189. * @return {number} The alternated value.
  2190. */
  2191. smootherstep: smootherstep,
  2192. /**
  2193. * Returns a random integer from `<low, high>` interval.
  2194. *
  2195. * @static
  2196. * @method
  2197. * @param {number} low - The lower value boundary.
  2198. * @param {number} high - The upper value boundary
  2199. * @return {number} A random integer.
  2200. */
  2201. randInt: randInt,
  2202. /**
  2203. * Returns a random float from `<low, high>` interval.
  2204. *
  2205. * @static
  2206. * @method
  2207. * @param {number} low - The lower value boundary.
  2208. * @param {number} high - The upper value boundary
  2209. * @return {number} A random float.
  2210. */
  2211. randFloat: randFloat,
  2212. /**
  2213. * Returns a random integer from `<-range/2, range/2>` interval.
  2214. *
  2215. * @static
  2216. * @method
  2217. * @param {number} range - Defines the value range.
  2218. * @return {number} A random float.
  2219. */
  2220. randFloatSpread: randFloatSpread,
  2221. /**
  2222. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2223. *
  2224. * @static
  2225. * @method
  2226. * @param {number} [s] - The integer seed.
  2227. * @return {number} A random float.
  2228. */
  2229. seededRandom: seededRandom,
  2230. /**
  2231. * Converts degrees to radians.
  2232. *
  2233. * @static
  2234. * @method
  2235. * @param {number} degrees - A value in degrees.
  2236. * @return {number} The converted value in radians.
  2237. */
  2238. degToRad: degToRad,
  2239. /**
  2240. * Converts radians to degrees.
  2241. *
  2242. * @static
  2243. * @method
  2244. * @param {number} radians - A value in radians.
  2245. * @return {number} The converted value in degrees.
  2246. */
  2247. radToDeg: radToDeg,
  2248. /**
  2249. * Returns `true` if the given number is a power of two.
  2250. *
  2251. * @static
  2252. * @method
  2253. * @param {number} value - The value to check.
  2254. * @return {boolean} Whether the given number is a power of two or not.
  2255. */
  2256. isPowerOfTwo: isPowerOfTwo,
  2257. /**
  2258. * Returns the smallest power of two that is greater than or equal to the given number.
  2259. *
  2260. * @static
  2261. * @method
  2262. * @param {number} value - The value to find a POT for.
  2263. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2264. */
  2265. ceilPowerOfTwo: ceilPowerOfTwo,
  2266. /**
  2267. * Returns the largest power of two that is less than or equal to the given number.
  2268. *
  2269. * @static
  2270. * @method
  2271. * @param {number} value - The value to find a POT for.
  2272. * @return {number} The largest power of two that is less than or equal to the given number.
  2273. */
  2274. floorPowerOfTwo: floorPowerOfTwo,
  2275. /**
  2276. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2277. * defined by the given angles and order.
  2278. *
  2279. * Rotations are applied to the axes in the order specified by order:
  2280. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2281. *
  2282. * @static
  2283. * @method
  2284. * @param {Quaternion} q - The quaternion to set.
  2285. * @param {number} a - The rotation applied to the first axis, in radians.
  2286. * @param {number} b - The rotation applied to the second axis, in radians.
  2287. * @param {number} c - The rotation applied to the third axis, in radians.
  2288. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2289. */
  2290. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2291. /**
  2292. * Normalizes the given value according to the given typed array.
  2293. *
  2294. * @static
  2295. * @method
  2296. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2297. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2298. * @return {number} The normalize value.
  2299. */
  2300. normalize: normalize,
  2301. /**
  2302. * Denormalizes the given value according to the given typed array.
  2303. *
  2304. * @static
  2305. * @method
  2306. * @param {number} value - The value to denormalize.
  2307. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2308. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2309. */
  2310. denormalize: denormalize
  2311. };
  2312. /**
  2313. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2314. * (labeled x and y), which can be used to represent a number of things, such as:
  2315. *
  2316. * - A point in 2D space (i.e. a position on a plane).
  2317. * - A direction and length across a plane. In three.js the length will
  2318. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2319. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2320. * - Any arbitrary ordered pair of numbers.
  2321. *
  2322. * There are other things a 2D vector can be used to represent, such as
  2323. * momentum vectors, complex numbers and so on, however these are the most
  2324. * common uses in three.js.
  2325. *
  2326. * Iterating through a vector instance will yield its components `(x, y)` in
  2327. * the corresponding order.
  2328. * ```js
  2329. * const a = new THREE.Vector2( 0, 1 );
  2330. *
  2331. * //no arguments; will be initialised to (0, 0)
  2332. * const b = new THREE.Vector2( );
  2333. *
  2334. * const d = a.distanceTo( b );
  2335. * ```
  2336. */
  2337. class Vector2 {
  2338. /**
  2339. * Constructs a new 2D vector.
  2340. *
  2341. * @param {number} [x=0] - The x value of this vector.
  2342. * @param {number} [y=0] - The y value of this vector.
  2343. */
  2344. constructor( x = 0, y = 0 ) {
  2345. /**
  2346. * This flag can be used for type testing.
  2347. *
  2348. * @type {boolean}
  2349. * @readonly
  2350. * @default true
  2351. */
  2352. Vector2.prototype.isVector2 = true;
  2353. /**
  2354. * The x value of this vector.
  2355. *
  2356. * @type {number}
  2357. */
  2358. this.x = x;
  2359. /**
  2360. * The y value of this vector.
  2361. *
  2362. * @type {number}
  2363. */
  2364. this.y = y;
  2365. }
  2366. /**
  2367. * Alias for {@link Vector2#x}.
  2368. *
  2369. * @type {number}
  2370. */
  2371. get width() {
  2372. return this.x;
  2373. }
  2374. set width( value ) {
  2375. this.x = value;
  2376. }
  2377. /**
  2378. * Alias for {@link Vector2#y}.
  2379. *
  2380. * @type {number}
  2381. */
  2382. get height() {
  2383. return this.y;
  2384. }
  2385. set height( value ) {
  2386. this.y = value;
  2387. }
  2388. /**
  2389. * Sets the vector components.
  2390. *
  2391. * @param {number} x - The value of the x component.
  2392. * @param {number} y - The value of the y component.
  2393. * @return {Vector2} A reference to this vector.
  2394. */
  2395. set( x, y ) {
  2396. this.x = x;
  2397. this.y = y;
  2398. return this;
  2399. }
  2400. /**
  2401. * Sets the vector components to the same value.
  2402. *
  2403. * @param {number} scalar - The value to set for all vector components.
  2404. * @return {Vector2} A reference to this vector.
  2405. */
  2406. setScalar( scalar ) {
  2407. this.x = scalar;
  2408. this.y = scalar;
  2409. return this;
  2410. }
  2411. /**
  2412. * Sets the vector's x component to the given value
  2413. *
  2414. * @param {number} x - The value to set.
  2415. * @return {Vector2} A reference to this vector.
  2416. */
  2417. setX( x ) {
  2418. this.x = x;
  2419. return this;
  2420. }
  2421. /**
  2422. * Sets the vector's y component to the given value
  2423. *
  2424. * @param {number} y - The value to set.
  2425. * @return {Vector2} A reference to this vector.
  2426. */
  2427. setY( y ) {
  2428. this.y = y;
  2429. return this;
  2430. }
  2431. /**
  2432. * Allows to set a vector component with an index.
  2433. *
  2434. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2435. * @param {number} value - The value to set.
  2436. * @return {Vector2} A reference to this vector.
  2437. */
  2438. setComponent( index, value ) {
  2439. switch ( index ) {
  2440. case 0: this.x = value; break;
  2441. case 1: this.y = value; break;
  2442. default: throw new Error( 'index is out of range: ' + index );
  2443. }
  2444. return this;
  2445. }
  2446. /**
  2447. * Returns the value of the vector component which matches the given index.
  2448. *
  2449. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2450. * @return {number} A vector component value.
  2451. */
  2452. getComponent( index ) {
  2453. switch ( index ) {
  2454. case 0: return this.x;
  2455. case 1: return this.y;
  2456. default: throw new Error( 'index is out of range: ' + index );
  2457. }
  2458. }
  2459. /**
  2460. * Returns a new vector with copied values from this instance.
  2461. *
  2462. * @return {Vector2} A clone of this instance.
  2463. */
  2464. clone() {
  2465. return new this.constructor( this.x, this.y );
  2466. }
  2467. /**
  2468. * Copies the values of the given vector to this instance.
  2469. *
  2470. * @param {Vector2} v - The vector to copy.
  2471. * @return {Vector2} A reference to this vector.
  2472. */
  2473. copy( v ) {
  2474. this.x = v.x;
  2475. this.y = v.y;
  2476. return this;
  2477. }
  2478. /**
  2479. * Adds the given vector to this instance.
  2480. *
  2481. * @param {Vector2} v - The vector to add.
  2482. * @return {Vector2} A reference to this vector.
  2483. */
  2484. add( v ) {
  2485. this.x += v.x;
  2486. this.y += v.y;
  2487. return this;
  2488. }
  2489. /**
  2490. * Adds the given scalar value to all components of this instance.
  2491. *
  2492. * @param {number} s - The scalar to add.
  2493. * @return {Vector2} A reference to this vector.
  2494. */
  2495. addScalar( s ) {
  2496. this.x += s;
  2497. this.y += s;
  2498. return this;
  2499. }
  2500. /**
  2501. * Adds the given vectors and stores the result in this instance.
  2502. *
  2503. * @param {Vector2} a - The first vector.
  2504. * @param {Vector2} b - The second vector.
  2505. * @return {Vector2} A reference to this vector.
  2506. */
  2507. addVectors( a, b ) {
  2508. this.x = a.x + b.x;
  2509. this.y = a.y + b.y;
  2510. return this;
  2511. }
  2512. /**
  2513. * Adds the given vector scaled by the given factor to this instance.
  2514. *
  2515. * @param {Vector2} v - The vector.
  2516. * @param {number} s - The factor that scales `v`.
  2517. * @return {Vector2} A reference to this vector.
  2518. */
  2519. addScaledVector( v, s ) {
  2520. this.x += v.x * s;
  2521. this.y += v.y * s;
  2522. return this;
  2523. }
  2524. /**
  2525. * Subtracts the given vector from this instance.
  2526. *
  2527. * @param {Vector2} v - The vector to subtract.
  2528. * @return {Vector2} A reference to this vector.
  2529. */
  2530. sub( v ) {
  2531. this.x -= v.x;
  2532. this.y -= v.y;
  2533. return this;
  2534. }
  2535. /**
  2536. * Subtracts the given scalar value from all components of this instance.
  2537. *
  2538. * @param {number} s - The scalar to subtract.
  2539. * @return {Vector2} A reference to this vector.
  2540. */
  2541. subScalar( s ) {
  2542. this.x -= s;
  2543. this.y -= s;
  2544. return this;
  2545. }
  2546. /**
  2547. * Subtracts the given vectors and stores the result in this instance.
  2548. *
  2549. * @param {Vector2} a - The first vector.
  2550. * @param {Vector2} b - The second vector.
  2551. * @return {Vector2} A reference to this vector.
  2552. */
  2553. subVectors( a, b ) {
  2554. this.x = a.x - b.x;
  2555. this.y = a.y - b.y;
  2556. return this;
  2557. }
  2558. /**
  2559. * Multiplies the given vector with this instance.
  2560. *
  2561. * @param {Vector2} v - The vector to multiply.
  2562. * @return {Vector2} A reference to this vector.
  2563. */
  2564. multiply( v ) {
  2565. this.x *= v.x;
  2566. this.y *= v.y;
  2567. return this;
  2568. }
  2569. /**
  2570. * Multiplies the given scalar value with all components of this instance.
  2571. *
  2572. * @param {number} scalar - The scalar to multiply.
  2573. * @return {Vector2} A reference to this vector.
  2574. */
  2575. multiplyScalar( scalar ) {
  2576. this.x *= scalar;
  2577. this.y *= scalar;
  2578. return this;
  2579. }
  2580. /**
  2581. * Divides this instance by the given vector.
  2582. *
  2583. * @param {Vector2} v - The vector to divide.
  2584. * @return {Vector2} A reference to this vector.
  2585. */
  2586. divide( v ) {
  2587. this.x /= v.x;
  2588. this.y /= v.y;
  2589. return this;
  2590. }
  2591. /**
  2592. * Divides this vector by the given scalar.
  2593. *
  2594. * @param {number} scalar - The scalar to divide.
  2595. * @return {Vector2} A reference to this vector.
  2596. */
  2597. divideScalar( scalar ) {
  2598. return this.multiplyScalar( 1 / scalar );
  2599. }
  2600. /**
  2601. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2602. * the given 3x3 matrix.
  2603. *
  2604. * @param {Matrix3} m - The matrix to apply.
  2605. * @return {Vector2} A reference to this vector.
  2606. */
  2607. applyMatrix3( m ) {
  2608. const x = this.x, y = this.y;
  2609. const e = m.elements;
  2610. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2611. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2612. return this;
  2613. }
  2614. /**
  2615. * If this vector's x or y value is greater than the given vector's x or y
  2616. * value, replace that value with the corresponding min value.
  2617. *
  2618. * @param {Vector2} v - The vector.
  2619. * @return {Vector2} A reference to this vector.
  2620. */
  2621. min( v ) {
  2622. this.x = Math.min( this.x, v.x );
  2623. this.y = Math.min( this.y, v.y );
  2624. return this;
  2625. }
  2626. /**
  2627. * If this vector's x or y value is less than the given vector's x or y
  2628. * value, replace that value with the corresponding max value.
  2629. *
  2630. * @param {Vector2} v - The vector.
  2631. * @return {Vector2} A reference to this vector.
  2632. */
  2633. max( v ) {
  2634. this.x = Math.max( this.x, v.x );
  2635. this.y = Math.max( this.y, v.y );
  2636. return this;
  2637. }
  2638. /**
  2639. * If this vector's x or y value is greater than the max vector's x or y
  2640. * value, it is replaced by the corresponding value.
  2641. * If this vector's x or y value is less than the min vector's x or y value,
  2642. * it is replaced by the corresponding value.
  2643. *
  2644. * @param {Vector2} min - The minimum x and y values.
  2645. * @param {Vector2} max - The maximum x and y values in the desired range.
  2646. * @return {Vector2} A reference to this vector.
  2647. */
  2648. clamp( min, max ) {
  2649. // assumes min < max, componentwise
  2650. this.x = clamp( this.x, min.x, max.x );
  2651. this.y = clamp( this.y, min.y, max.y );
  2652. return this;
  2653. }
  2654. /**
  2655. * If this vector's x or y values are greater than the max value, they are
  2656. * replaced by the max value.
  2657. * If this vector's x or y values are less than the min value, they are
  2658. * replaced by the min value.
  2659. *
  2660. * @param {number} minVal - The minimum value the components will be clamped to.
  2661. * @param {number} maxVal - The maximum value the components will be clamped to.
  2662. * @return {Vector2} A reference to this vector.
  2663. */
  2664. clampScalar( minVal, maxVal ) {
  2665. this.x = clamp( this.x, minVal, maxVal );
  2666. this.y = clamp( this.y, minVal, maxVal );
  2667. return this;
  2668. }
  2669. /**
  2670. * If this vector's length is greater than the max value, it is replaced by
  2671. * the max value.
  2672. * If this vector's length is less than the min value, it is replaced by the
  2673. * min value.
  2674. *
  2675. * @param {number} min - The minimum value the vector length will be clamped to.
  2676. * @param {number} max - The maximum value the vector length will be clamped to.
  2677. * @return {Vector2} A reference to this vector.
  2678. */
  2679. clampLength( min, max ) {
  2680. const length = this.length();
  2681. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2682. }
  2683. /**
  2684. * The components of this vector are rounded down to the nearest integer value.
  2685. *
  2686. * @return {Vector2} A reference to this vector.
  2687. */
  2688. floor() {
  2689. this.x = Math.floor( this.x );
  2690. this.y = Math.floor( this.y );
  2691. return this;
  2692. }
  2693. /**
  2694. * The components of this vector are rounded up to the nearest integer value.
  2695. *
  2696. * @return {Vector2} A reference to this vector.
  2697. */
  2698. ceil() {
  2699. this.x = Math.ceil( this.x );
  2700. this.y = Math.ceil( this.y );
  2701. return this;
  2702. }
  2703. /**
  2704. * The components of this vector are rounded to the nearest integer value
  2705. *
  2706. * @return {Vector2} A reference to this vector.
  2707. */
  2708. round() {
  2709. this.x = Math.round( this.x );
  2710. this.y = Math.round( this.y );
  2711. return this;
  2712. }
  2713. /**
  2714. * The components of this vector are rounded towards zero (up if negative,
  2715. * down if positive) to an integer value.
  2716. *
  2717. * @return {Vector2} A reference to this vector.
  2718. */
  2719. roundToZero() {
  2720. this.x = Math.trunc( this.x );
  2721. this.y = Math.trunc( this.y );
  2722. return this;
  2723. }
  2724. /**
  2725. * Inverts this vector - i.e. sets x = -x and y = -y.
  2726. *
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. negate() {
  2730. this.x = - this.x;
  2731. this.y = - this.y;
  2732. return this;
  2733. }
  2734. /**
  2735. * Calculates the dot product of the given vector with this instance.
  2736. *
  2737. * @param {Vector2} v - The vector to compute the dot product with.
  2738. * @return {number} The result of the dot product.
  2739. */
  2740. dot( v ) {
  2741. return this.x * v.x + this.y * v.y;
  2742. }
  2743. /**
  2744. * Calculates the cross product of the given vector with this instance.
  2745. *
  2746. * @param {Vector2} v - The vector to compute the cross product with.
  2747. * @return {number} The result of the cross product.
  2748. */
  2749. cross( v ) {
  2750. return this.x * v.y - this.y * v.x;
  2751. }
  2752. /**
  2753. * Computes the square of the Euclidean length (straight-line length) from
  2754. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2755. * compare the length squared instead as it is slightly more efficient to calculate.
  2756. *
  2757. * @return {number} The square length of this vector.
  2758. */
  2759. lengthSq() {
  2760. return this.x * this.x + this.y * this.y;
  2761. }
  2762. /**
  2763. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2764. *
  2765. * @return {number} The length of this vector.
  2766. */
  2767. length() {
  2768. return Math.sqrt( this.x * this.x + this.y * this.y );
  2769. }
  2770. /**
  2771. * Computes the Manhattan length of this vector.
  2772. *
  2773. * @return {number} The length of this vector.
  2774. */
  2775. manhattanLength() {
  2776. return Math.abs( this.x ) + Math.abs( this.y );
  2777. }
  2778. /**
  2779. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2780. * with the same direction as this one, but with a vector length of `1`.
  2781. *
  2782. * @return {Vector2} A reference to this vector.
  2783. */
  2784. normalize() {
  2785. return this.divideScalar( this.length() || 1 );
  2786. }
  2787. /**
  2788. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2789. *
  2790. * @return {number} The angle in radians.
  2791. */
  2792. angle() {
  2793. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2794. return angle;
  2795. }
  2796. /**
  2797. * Returns the angle between the given vector and this instance in radians.
  2798. *
  2799. * @param {Vector2} v - The vector to compute the angle with.
  2800. * @return {number} The angle in radians.
  2801. */
  2802. angleTo( v ) {
  2803. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2804. if ( denominator === 0 ) return Math.PI / 2;
  2805. const theta = this.dot( v ) / denominator;
  2806. // clamp, to handle numerical problems
  2807. return Math.acos( clamp( theta, -1, 1 ) );
  2808. }
  2809. /**
  2810. * Computes the distance from the given vector to this instance.
  2811. *
  2812. * @param {Vector2} v - The vector to compute the distance to.
  2813. * @return {number} The distance.
  2814. */
  2815. distanceTo( v ) {
  2816. return Math.sqrt( this.distanceToSquared( v ) );
  2817. }
  2818. /**
  2819. * Computes the squared distance from the given vector to this instance.
  2820. * If you are just comparing the distance with another distance, you should compare
  2821. * the distance squared instead as it is slightly more efficient to calculate.
  2822. *
  2823. * @param {Vector2} v - The vector to compute the squared distance to.
  2824. * @return {number} The squared distance.
  2825. */
  2826. distanceToSquared( v ) {
  2827. const dx = this.x - v.x, dy = this.y - v.y;
  2828. return dx * dx + dy * dy;
  2829. }
  2830. /**
  2831. * Computes the Manhattan distance from the given vector to this instance.
  2832. *
  2833. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2834. * @return {number} The Manhattan distance.
  2835. */
  2836. manhattanDistanceTo( v ) {
  2837. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2838. }
  2839. /**
  2840. * Sets this vector to a vector with the same direction as this one, but
  2841. * with the specified length.
  2842. *
  2843. * @param {number} length - The new length of this vector.
  2844. * @return {Vector2} A reference to this vector.
  2845. */
  2846. setLength( length ) {
  2847. return this.normalize().multiplyScalar( length );
  2848. }
  2849. /**
  2850. * Linearly interpolates between the given vector and this instance, where
  2851. * alpha is the percent distance along the line - alpha = 0 will be this
  2852. * vector, and alpha = 1 will be the given one.
  2853. *
  2854. * @param {Vector2} v - The vector to interpolate towards.
  2855. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2856. * @return {Vector2} A reference to this vector.
  2857. */
  2858. lerp( v, alpha ) {
  2859. this.x += ( v.x - this.x ) * alpha;
  2860. this.y += ( v.y - this.y ) * alpha;
  2861. return this;
  2862. }
  2863. /**
  2864. * Linearly interpolates between the given vectors, where alpha is the percent
  2865. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2866. * be the second one. The result is stored in this instance.
  2867. *
  2868. * @param {Vector2} v1 - The first vector.
  2869. * @param {Vector2} v2 - The second vector.
  2870. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2871. * @return {Vector2} A reference to this vector.
  2872. */
  2873. lerpVectors( v1, v2, alpha ) {
  2874. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2875. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2876. return this;
  2877. }
  2878. /**
  2879. * Returns `true` if this vector is equal with the given one.
  2880. *
  2881. * @param {Vector2} v - The vector to test for equality.
  2882. * @return {boolean} Whether this vector is equal with the given one.
  2883. */
  2884. equals( v ) {
  2885. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2886. }
  2887. /**
  2888. * Sets this vector's x value to be `array[ offset ]` and y
  2889. * value to be `array[ offset + 1 ]`.
  2890. *
  2891. * @param {Array<number>} array - An array holding the vector component values.
  2892. * @param {number} [offset=0] - The offset into the array.
  2893. * @return {Vector2} A reference to this vector.
  2894. */
  2895. fromArray( array, offset = 0 ) {
  2896. this.x = array[ offset ];
  2897. this.y = array[ offset + 1 ];
  2898. return this;
  2899. }
  2900. /**
  2901. * Writes the components of this vector to the given array. If no array is provided,
  2902. * the method returns a new instance.
  2903. *
  2904. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2905. * @param {number} [offset=0] - Index of the first element in the array.
  2906. * @return {Array<number>} The vector components.
  2907. */
  2908. toArray( array = [], offset = 0 ) {
  2909. array[ offset ] = this.x;
  2910. array[ offset + 1 ] = this.y;
  2911. return array;
  2912. }
  2913. /**
  2914. * Sets the components of this vector from the given buffer attribute.
  2915. *
  2916. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2917. * @param {number} index - The index into the attribute.
  2918. * @return {Vector2} A reference to this vector.
  2919. */
  2920. fromBufferAttribute( attribute, index ) {
  2921. this.x = attribute.getX( index );
  2922. this.y = attribute.getY( index );
  2923. return this;
  2924. }
  2925. /**
  2926. * Rotates this vector around the given center by the given angle.
  2927. *
  2928. * @param {Vector2} center - The point around which to rotate.
  2929. * @param {number} angle - The angle to rotate, in radians.
  2930. * @return {Vector2} A reference to this vector.
  2931. */
  2932. rotateAround( center, angle ) {
  2933. const c = Math.cos( angle ), s = Math.sin( angle );
  2934. const x = this.x - center.x;
  2935. const y = this.y - center.y;
  2936. this.x = x * c - y * s + center.x;
  2937. this.y = x * s + y * c + center.y;
  2938. return this;
  2939. }
  2940. /**
  2941. * Sets each component of this vector to a pseudo-random value between `0` and
  2942. * `1`, excluding `1`.
  2943. *
  2944. * @return {Vector2} A reference to this vector.
  2945. */
  2946. random() {
  2947. this.x = Math.random();
  2948. this.y = Math.random();
  2949. return this;
  2950. }
  2951. *[ Symbol.iterator ]() {
  2952. yield this.x;
  2953. yield this.y;
  2954. }
  2955. }
  2956. /**
  2957. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2958. *
  2959. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2960. * the corresponding order.
  2961. *
  2962. * Note that three.js expects Quaternions to be normalized.
  2963. * ```js
  2964. * const quaternion = new THREE.Quaternion();
  2965. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2966. *
  2967. * const vector = new THREE.Vector3( 1, 0, 0 );
  2968. * vector.applyQuaternion( quaternion );
  2969. * ```
  2970. */
  2971. class Quaternion {
  2972. /**
  2973. * Constructs a new quaternion.
  2974. *
  2975. * @param {number} [x=0] - The x value of this quaternion.
  2976. * @param {number} [y=0] - The y value of this quaternion.
  2977. * @param {number} [z=0] - The z value of this quaternion.
  2978. * @param {number} [w=1] - The w value of this quaternion.
  2979. */
  2980. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2981. /**
  2982. * This flag can be used for type testing.
  2983. *
  2984. * @type {boolean}
  2985. * @readonly
  2986. * @default true
  2987. */
  2988. this.isQuaternion = true;
  2989. this._x = x;
  2990. this._y = y;
  2991. this._z = z;
  2992. this._w = w;
  2993. }
  2994. /**
  2995. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2996. * quaternion data are managed in flat arrays.
  2997. *
  2998. * @param {Array<number>} dst - The destination array.
  2999. * @param {number} dstOffset - An offset into the destination array.
  3000. * @param {Array<number>} src0 - The source array of the first quaternion.
  3001. * @param {number} srcOffset0 - An offset into the first source array.
  3002. * @param {Array<number>} src1 - The source array of the second quaternion.
  3003. * @param {number} srcOffset1 - An offset into the second source array.
  3004. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3005. * @see {@link Quaternion#slerp}
  3006. */
  3007. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3008. let x0 = src0[ srcOffset0 + 0 ],
  3009. y0 = src0[ srcOffset0 + 1 ],
  3010. z0 = src0[ srcOffset0 + 2 ],
  3011. w0 = src0[ srcOffset0 + 3 ];
  3012. let x1 = src1[ srcOffset1 + 0 ],
  3013. y1 = src1[ srcOffset1 + 1 ],
  3014. z1 = src1[ srcOffset1 + 2 ],
  3015. w1 = src1[ srcOffset1 + 3 ];
  3016. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3017. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3018. if ( dot < 0 ) {
  3019. x1 = - x1;
  3020. y1 = - y1;
  3021. z1 = - z1;
  3022. w1 = - w1;
  3023. dot = - dot;
  3024. }
  3025. let s = 1 - t;
  3026. if ( dot < 0.9995 ) {
  3027. // slerp
  3028. const theta = Math.acos( dot );
  3029. const sin = Math.sin( theta );
  3030. s = Math.sin( s * theta ) / sin;
  3031. t = Math.sin( t * theta ) / sin;
  3032. x0 = x0 * s + x1 * t;
  3033. y0 = y0 * s + y1 * t;
  3034. z0 = z0 * s + z1 * t;
  3035. w0 = w0 * s + w1 * t;
  3036. } else {
  3037. // for small angles, lerp then normalize
  3038. x0 = x0 * s + x1 * t;
  3039. y0 = y0 * s + y1 * t;
  3040. z0 = z0 * s + z1 * t;
  3041. w0 = w0 * s + w1 * t;
  3042. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3043. x0 *= f;
  3044. y0 *= f;
  3045. z0 *= f;
  3046. w0 *= f;
  3047. }
  3048. }
  3049. dst[ dstOffset ] = x0;
  3050. dst[ dstOffset + 1 ] = y0;
  3051. dst[ dstOffset + 2 ] = z0;
  3052. dst[ dstOffset + 3 ] = w0;
  3053. }
  3054. /**
  3055. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3056. * in flat arrays.
  3057. *
  3058. * @param {Array<number>} dst - The destination array.
  3059. * @param {number} dstOffset - An offset into the destination array.
  3060. * @param {Array<number>} src0 - The source array of the first quaternion.
  3061. * @param {number} srcOffset0 - An offset into the first source array.
  3062. * @param {Array<number>} src1 - The source array of the second quaternion.
  3063. * @param {number} srcOffset1 - An offset into the second source array.
  3064. * @return {Array<number>} The destination array.
  3065. * @see {@link Quaternion#multiplyQuaternions}.
  3066. */
  3067. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3068. const x0 = src0[ srcOffset0 ];
  3069. const y0 = src0[ srcOffset0 + 1 ];
  3070. const z0 = src0[ srcOffset0 + 2 ];
  3071. const w0 = src0[ srcOffset0 + 3 ];
  3072. const x1 = src1[ srcOffset1 ];
  3073. const y1 = src1[ srcOffset1 + 1 ];
  3074. const z1 = src1[ srcOffset1 + 2 ];
  3075. const w1 = src1[ srcOffset1 + 3 ];
  3076. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3077. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3078. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3079. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3080. return dst;
  3081. }
  3082. /**
  3083. * The x value of this quaternion.
  3084. *
  3085. * @type {number}
  3086. * @default 0
  3087. */
  3088. get x() {
  3089. return this._x;
  3090. }
  3091. set x( value ) {
  3092. this._x = value;
  3093. this._onChangeCallback();
  3094. }
  3095. /**
  3096. * The y value of this quaternion.
  3097. *
  3098. * @type {number}
  3099. * @default 0
  3100. */
  3101. get y() {
  3102. return this._y;
  3103. }
  3104. set y( value ) {
  3105. this._y = value;
  3106. this._onChangeCallback();
  3107. }
  3108. /**
  3109. * The z value of this quaternion.
  3110. *
  3111. * @type {number}
  3112. * @default 0
  3113. */
  3114. get z() {
  3115. return this._z;
  3116. }
  3117. set z( value ) {
  3118. this._z = value;
  3119. this._onChangeCallback();
  3120. }
  3121. /**
  3122. * The w value of this quaternion.
  3123. *
  3124. * @type {number}
  3125. * @default 1
  3126. */
  3127. get w() {
  3128. return this._w;
  3129. }
  3130. set w( value ) {
  3131. this._w = value;
  3132. this._onChangeCallback();
  3133. }
  3134. /**
  3135. * Sets the quaternion components.
  3136. *
  3137. * @param {number} x - The x value of this quaternion.
  3138. * @param {number} y - The y value of this quaternion.
  3139. * @param {number} z - The z value of this quaternion.
  3140. * @param {number} w - The w value of this quaternion.
  3141. * @return {Quaternion} A reference to this quaternion.
  3142. */
  3143. set( x, y, z, w ) {
  3144. this._x = x;
  3145. this._y = y;
  3146. this._z = z;
  3147. this._w = w;
  3148. this._onChangeCallback();
  3149. return this;
  3150. }
  3151. /**
  3152. * Returns a new quaternion with copied values from this instance.
  3153. *
  3154. * @return {Quaternion} A clone of this instance.
  3155. */
  3156. clone() {
  3157. return new this.constructor( this._x, this._y, this._z, this._w );
  3158. }
  3159. /**
  3160. * Copies the values of the given quaternion to this instance.
  3161. *
  3162. * @param {Quaternion} quaternion - The quaternion to copy.
  3163. * @return {Quaternion} A reference to this quaternion.
  3164. */
  3165. copy( quaternion ) {
  3166. this._x = quaternion.x;
  3167. this._y = quaternion.y;
  3168. this._z = quaternion.z;
  3169. this._w = quaternion.w;
  3170. this._onChangeCallback();
  3171. return this;
  3172. }
  3173. /**
  3174. * Sets this quaternion from the rotation specified by the given
  3175. * Euler angles.
  3176. *
  3177. * @param {Euler} euler - The Euler angles.
  3178. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3179. * @return {Quaternion} A reference to this quaternion.
  3180. */
  3181. setFromEuler( euler, update = true ) {
  3182. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3183. // http://www.mathworks.com/matlabcentral/fileexchange/
  3184. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3185. // content/SpinCalc.m
  3186. const cos = Math.cos;
  3187. const sin = Math.sin;
  3188. const c1 = cos( x / 2 );
  3189. const c2 = cos( y / 2 );
  3190. const c3 = cos( z / 2 );
  3191. const s1 = sin( x / 2 );
  3192. const s2 = sin( y / 2 );
  3193. const s3 = sin( z / 2 );
  3194. switch ( order ) {
  3195. case 'XYZ':
  3196. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3197. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3198. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3199. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3200. break;
  3201. case 'YXZ':
  3202. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3203. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3204. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3205. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3206. break;
  3207. case 'ZXY':
  3208. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3209. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3210. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3211. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3212. break;
  3213. case 'ZYX':
  3214. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3215. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3216. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3217. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3218. break;
  3219. case 'YZX':
  3220. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3221. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3222. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3223. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3224. break;
  3225. case 'XZY':
  3226. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3227. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3228. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3229. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3230. break;
  3231. default:
  3232. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3233. }
  3234. if ( update === true ) this._onChangeCallback();
  3235. return this;
  3236. }
  3237. /**
  3238. * Sets this quaternion from the given axis and angle.
  3239. *
  3240. * @param {Vector3} axis - The normalized axis.
  3241. * @param {number} angle - The angle in radians.
  3242. * @return {Quaternion} A reference to this quaternion.
  3243. */
  3244. setFromAxisAngle( axis, angle ) {
  3245. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3246. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3247. this._x = axis.x * s;
  3248. this._y = axis.y * s;
  3249. this._z = axis.z * s;
  3250. this._w = Math.cos( halfAngle );
  3251. this._onChangeCallback();
  3252. return this;
  3253. }
  3254. /**
  3255. * Sets this quaternion from the given rotation matrix.
  3256. *
  3257. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3258. * @return {Quaternion} A reference to this quaternion.
  3259. */
  3260. setFromRotationMatrix( m ) {
  3261. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3262. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3263. const te = m.elements,
  3264. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3265. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3266. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3267. trace = m11 + m22 + m33;
  3268. if ( trace > 0 ) {
  3269. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3270. this._w = 0.25 / s;
  3271. this._x = ( m32 - m23 ) * s;
  3272. this._y = ( m13 - m31 ) * s;
  3273. this._z = ( m21 - m12 ) * s;
  3274. } else if ( m11 > m22 && m11 > m33 ) {
  3275. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3276. this._w = ( m32 - m23 ) / s;
  3277. this._x = 0.25 * s;
  3278. this._y = ( m12 + m21 ) / s;
  3279. this._z = ( m13 + m31 ) / s;
  3280. } else if ( m22 > m33 ) {
  3281. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3282. this._w = ( m13 - m31 ) / s;
  3283. this._x = ( m12 + m21 ) / s;
  3284. this._y = 0.25 * s;
  3285. this._z = ( m23 + m32 ) / s;
  3286. } else {
  3287. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3288. this._w = ( m21 - m12 ) / s;
  3289. this._x = ( m13 + m31 ) / s;
  3290. this._y = ( m23 + m32 ) / s;
  3291. this._z = 0.25 * s;
  3292. }
  3293. this._onChangeCallback();
  3294. return this;
  3295. }
  3296. /**
  3297. * Sets this quaternion to the rotation required to rotate the direction vector
  3298. * `vFrom` to the direction vector `vTo`.
  3299. *
  3300. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3301. * @param {Vector3} vTo - The second (normalized) direction vector.
  3302. * @return {Quaternion} A reference to this quaternion.
  3303. */
  3304. setFromUnitVectors( vFrom, vTo ) {
  3305. // assumes direction vectors vFrom and vTo are normalized
  3306. let r = vFrom.dot( vTo ) + 1;
  3307. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3308. // vFrom and vTo point in opposite directions
  3309. r = 0;
  3310. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3311. this._x = - vFrom.y;
  3312. this._y = vFrom.x;
  3313. this._z = 0;
  3314. this._w = r;
  3315. } else {
  3316. this._x = 0;
  3317. this._y = - vFrom.z;
  3318. this._z = vFrom.y;
  3319. this._w = r;
  3320. }
  3321. } else {
  3322. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3323. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3324. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3325. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3326. this._w = r;
  3327. }
  3328. return this.normalize();
  3329. }
  3330. /**
  3331. * Returns the angle between this quaternion and the given one in radians.
  3332. *
  3333. * @param {Quaternion} q - The quaternion to compute the angle with.
  3334. * @return {number} The angle in radians.
  3335. */
  3336. angleTo( q ) {
  3337. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3338. }
  3339. /**
  3340. * Rotates this quaternion by a given angular step to the given quaternion.
  3341. * The method ensures that the final quaternion will not overshoot `q`.
  3342. *
  3343. * @param {Quaternion} q - The target quaternion.
  3344. * @param {number} step - The angular step in radians.
  3345. * @return {Quaternion} A reference to this quaternion.
  3346. */
  3347. rotateTowards( q, step ) {
  3348. const angle = this.angleTo( q );
  3349. if ( angle === 0 ) return this;
  3350. const t = Math.min( 1, step / angle );
  3351. this.slerp( q, t );
  3352. return this;
  3353. }
  3354. /**
  3355. * Sets this quaternion to the identity quaternion; that is, to the
  3356. * quaternion that represents "no rotation".
  3357. *
  3358. * @return {Quaternion} A reference to this quaternion.
  3359. */
  3360. identity() {
  3361. return this.set( 0, 0, 0, 1 );
  3362. }
  3363. /**
  3364. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3365. * quaternion is assumed to have unit length.
  3366. *
  3367. * @return {Quaternion} A reference to this quaternion.
  3368. */
  3369. invert() {
  3370. return this.conjugate();
  3371. }
  3372. /**
  3373. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3374. * quaternion represents the same rotation in the opposite direction about
  3375. * the rotational axis.
  3376. *
  3377. * @return {Quaternion} A reference to this quaternion.
  3378. */
  3379. conjugate() {
  3380. this._x *= -1;
  3381. this._y *= -1;
  3382. this._z *= -1;
  3383. this._onChangeCallback();
  3384. return this;
  3385. }
  3386. /**
  3387. * Calculates the dot product of this quaternion and the given one.
  3388. *
  3389. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3390. * @return {number} The result of the dot product.
  3391. */
  3392. dot( v ) {
  3393. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3394. }
  3395. /**
  3396. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3397. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3398. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3399. * {@link Quaternion#length}.
  3400. *
  3401. * @return {number} The squared Euclidean length.
  3402. */
  3403. lengthSq() {
  3404. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3405. }
  3406. /**
  3407. * Computes the Euclidean length (straight-line length) of this quaternion,
  3408. * considered as a 4 dimensional vector.
  3409. *
  3410. * @return {number} The Euclidean length.
  3411. */
  3412. length() {
  3413. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3414. }
  3415. /**
  3416. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3417. * the same rotation as this one, but has a length equal to `1`.
  3418. *
  3419. * @return {Quaternion} A reference to this quaternion.
  3420. */
  3421. normalize() {
  3422. let l = this.length();
  3423. if ( l === 0 ) {
  3424. this._x = 0;
  3425. this._y = 0;
  3426. this._z = 0;
  3427. this._w = 1;
  3428. } else {
  3429. l = 1 / l;
  3430. this._x = this._x * l;
  3431. this._y = this._y * l;
  3432. this._z = this._z * l;
  3433. this._w = this._w * l;
  3434. }
  3435. this._onChangeCallback();
  3436. return this;
  3437. }
  3438. /**
  3439. * Multiplies this quaternion by the given one.
  3440. *
  3441. * @param {Quaternion} q - The quaternion.
  3442. * @return {Quaternion} A reference to this quaternion.
  3443. */
  3444. multiply( q ) {
  3445. return this.multiplyQuaternions( this, q );
  3446. }
  3447. /**
  3448. * Pre-multiplies this quaternion by the given one.
  3449. *
  3450. * @param {Quaternion} q - The quaternion.
  3451. * @return {Quaternion} A reference to this quaternion.
  3452. */
  3453. premultiply( q ) {
  3454. return this.multiplyQuaternions( q, this );
  3455. }
  3456. /**
  3457. * Multiplies the given quaternions and stores the result in this instance.
  3458. *
  3459. * @param {Quaternion} a - The first quaternion.
  3460. * @param {Quaternion} b - The second quaternion.
  3461. * @return {Quaternion} A reference to this quaternion.
  3462. */
  3463. multiplyQuaternions( a, b ) {
  3464. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3465. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3466. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3467. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3468. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3469. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3470. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3471. this._onChangeCallback();
  3472. return this;
  3473. }
  3474. /**
  3475. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3476. *
  3477. * @param {Quaternion} qb - The target quaternion.
  3478. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3479. * @return {Quaternion} A reference to this quaternion.
  3480. */
  3481. slerp( qb, t ) {
  3482. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3483. let dot = this.dot( qb );
  3484. if ( dot < 0 ) {
  3485. x = - x;
  3486. y = - y;
  3487. z = - z;
  3488. w = - w;
  3489. dot = - dot;
  3490. }
  3491. let s = 1 - t;
  3492. if ( dot < 0.9995 ) {
  3493. // slerp
  3494. const theta = Math.acos( dot );
  3495. const sin = Math.sin( theta );
  3496. s = Math.sin( s * theta ) / sin;
  3497. t = Math.sin( t * theta ) / sin;
  3498. this._x = this._x * s + x * t;
  3499. this._y = this._y * s + y * t;
  3500. this._z = this._z * s + z * t;
  3501. this._w = this._w * s + w * t;
  3502. this._onChangeCallback();
  3503. } else {
  3504. // for small angles, lerp then normalize
  3505. this._x = this._x * s + x * t;
  3506. this._y = this._y * s + y * t;
  3507. this._z = this._z * s + z * t;
  3508. this._w = this._w * s + w * t;
  3509. this.normalize(); // normalize calls _onChangeCallback()
  3510. }
  3511. return this;
  3512. }
  3513. /**
  3514. * Performs a spherical linear interpolation between the given quaternions
  3515. * and stores the result in this quaternion.
  3516. *
  3517. * @param {Quaternion} qa - The source quaternion.
  3518. * @param {Quaternion} qb - The target quaternion.
  3519. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3520. * @return {Quaternion} A reference to this quaternion.
  3521. */
  3522. slerpQuaternions( qa, qb, t ) {
  3523. return this.copy( qa ).slerp( qb, t );
  3524. }
  3525. /**
  3526. * Sets this quaternion to a uniformly random, normalized quaternion.
  3527. *
  3528. * @return {Quaternion} A reference to this quaternion.
  3529. */
  3530. random() {
  3531. // Ken Shoemake
  3532. // Uniform random rotations
  3533. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3534. const theta1 = 2 * Math.PI * Math.random();
  3535. const theta2 = 2 * Math.PI * Math.random();
  3536. const x0 = Math.random();
  3537. const r1 = Math.sqrt( 1 - x0 );
  3538. const r2 = Math.sqrt( x0 );
  3539. return this.set(
  3540. r1 * Math.sin( theta1 ),
  3541. r1 * Math.cos( theta1 ),
  3542. r2 * Math.sin( theta2 ),
  3543. r2 * Math.cos( theta2 ),
  3544. );
  3545. }
  3546. /**
  3547. * Returns `true` if this quaternion is equal with the given one.
  3548. *
  3549. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3550. * @return {boolean} Whether this quaternion is equal with the given one.
  3551. */
  3552. equals( quaternion ) {
  3553. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3554. }
  3555. /**
  3556. * Sets this quaternion's components from the given array.
  3557. *
  3558. * @param {Array<number>} array - An array holding the quaternion component values.
  3559. * @param {number} [offset=0] - The offset into the array.
  3560. * @return {Quaternion} A reference to this quaternion.
  3561. */
  3562. fromArray( array, offset = 0 ) {
  3563. this._x = array[ offset ];
  3564. this._y = array[ offset + 1 ];
  3565. this._z = array[ offset + 2 ];
  3566. this._w = array[ offset + 3 ];
  3567. this._onChangeCallback();
  3568. return this;
  3569. }
  3570. /**
  3571. * Writes the components of this quaternion to the given array. If no array is provided,
  3572. * the method returns a new instance.
  3573. *
  3574. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3575. * @param {number} [offset=0] - Index of the first element in the array.
  3576. * @return {Array<number>} The quaternion components.
  3577. */
  3578. toArray( array = [], offset = 0 ) {
  3579. array[ offset ] = this._x;
  3580. array[ offset + 1 ] = this._y;
  3581. array[ offset + 2 ] = this._z;
  3582. array[ offset + 3 ] = this._w;
  3583. return array;
  3584. }
  3585. /**
  3586. * Sets the components of this quaternion from the given buffer attribute.
  3587. *
  3588. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3589. * @param {number} index - The index into the attribute.
  3590. * @return {Quaternion} A reference to this quaternion.
  3591. */
  3592. fromBufferAttribute( attribute, index ) {
  3593. this._x = attribute.getX( index );
  3594. this._y = attribute.getY( index );
  3595. this._z = attribute.getZ( index );
  3596. this._w = attribute.getW( index );
  3597. this._onChangeCallback();
  3598. return this;
  3599. }
  3600. /**
  3601. * This methods defines the serialization result of this class. Returns the
  3602. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3603. *
  3604. * @return {Array<number>} The serialized quaternion.
  3605. */
  3606. toJSON() {
  3607. return this.toArray();
  3608. }
  3609. _onChange( callback ) {
  3610. this._onChangeCallback = callback;
  3611. return this;
  3612. }
  3613. _onChangeCallback() {}
  3614. *[ Symbol.iterator ]() {
  3615. yield this._x;
  3616. yield this._y;
  3617. yield this._z;
  3618. yield this._w;
  3619. }
  3620. }
  3621. /**
  3622. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3623. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3624. *
  3625. * - A point in 3D space.
  3626. * - A direction and length in 3D space. In three.js the length will
  3627. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3628. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3629. * - Any arbitrary ordered triplet of numbers.
  3630. *
  3631. * There are other things a 3D vector can be used to represent, such as
  3632. * momentum vectors and so on, however these are the most
  3633. * common uses in three.js.
  3634. *
  3635. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3636. * the corresponding order.
  3637. * ```js
  3638. * const a = new THREE.Vector3( 0, 1, 0 );
  3639. *
  3640. * //no arguments; will be initialised to (0, 0, 0)
  3641. * const b = new THREE.Vector3( );
  3642. *
  3643. * const d = a.distanceTo( b );
  3644. * ```
  3645. */
  3646. class Vector3 {
  3647. /**
  3648. * Constructs a new 3D vector.
  3649. *
  3650. * @param {number} [x=0] - The x value of this vector.
  3651. * @param {number} [y=0] - The y value of this vector.
  3652. * @param {number} [z=0] - The z value of this vector.
  3653. */
  3654. constructor( x = 0, y = 0, z = 0 ) {
  3655. /**
  3656. * This flag can be used for type testing.
  3657. *
  3658. * @type {boolean}
  3659. * @readonly
  3660. * @default true
  3661. */
  3662. Vector3.prototype.isVector3 = true;
  3663. /**
  3664. * The x value of this vector.
  3665. *
  3666. * @type {number}
  3667. */
  3668. this.x = x;
  3669. /**
  3670. * The y value of this vector.
  3671. *
  3672. * @type {number}
  3673. */
  3674. this.y = y;
  3675. /**
  3676. * The z value of this vector.
  3677. *
  3678. * @type {number}
  3679. */
  3680. this.z = z;
  3681. }
  3682. /**
  3683. * Sets the vector components.
  3684. *
  3685. * @param {number} x - The value of the x component.
  3686. * @param {number} y - The value of the y component.
  3687. * @param {number} z - The value of the z component.
  3688. * @return {Vector3} A reference to this vector.
  3689. */
  3690. set( x, y, z ) {
  3691. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3692. this.x = x;
  3693. this.y = y;
  3694. this.z = z;
  3695. return this;
  3696. }
  3697. /**
  3698. * Sets the vector components to the same value.
  3699. *
  3700. * @param {number} scalar - The value to set for all vector components.
  3701. * @return {Vector3} A reference to this vector.
  3702. */
  3703. setScalar( scalar ) {
  3704. this.x = scalar;
  3705. this.y = scalar;
  3706. this.z = scalar;
  3707. return this;
  3708. }
  3709. /**
  3710. * Sets the vector's x component to the given value.
  3711. *
  3712. * @param {number} x - The value to set.
  3713. * @return {Vector3} A reference to this vector.
  3714. */
  3715. setX( x ) {
  3716. this.x = x;
  3717. return this;
  3718. }
  3719. /**
  3720. * Sets the vector's y component to the given value.
  3721. *
  3722. * @param {number} y - The value to set.
  3723. * @return {Vector3} A reference to this vector.
  3724. */
  3725. setY( y ) {
  3726. this.y = y;
  3727. return this;
  3728. }
  3729. /**
  3730. * Sets the vector's z component to the given value.
  3731. *
  3732. * @param {number} z - The value to set.
  3733. * @return {Vector3} A reference to this vector.
  3734. */
  3735. setZ( z ) {
  3736. this.z = z;
  3737. return this;
  3738. }
  3739. /**
  3740. * Allows to set a vector component with an index.
  3741. *
  3742. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3743. * @param {number} value - The value to set.
  3744. * @return {Vector3} A reference to this vector.
  3745. */
  3746. setComponent( index, value ) {
  3747. switch ( index ) {
  3748. case 0: this.x = value; break;
  3749. case 1: this.y = value; break;
  3750. case 2: this.z = value; break;
  3751. default: throw new Error( 'index is out of range: ' + index );
  3752. }
  3753. return this;
  3754. }
  3755. /**
  3756. * Returns the value of the vector component which matches the given index.
  3757. *
  3758. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3759. * @return {number} A vector component value.
  3760. */
  3761. getComponent( index ) {
  3762. switch ( index ) {
  3763. case 0: return this.x;
  3764. case 1: return this.y;
  3765. case 2: return this.z;
  3766. default: throw new Error( 'index is out of range: ' + index );
  3767. }
  3768. }
  3769. /**
  3770. * Returns a new vector with copied values from this instance.
  3771. *
  3772. * @return {Vector3} A clone of this instance.
  3773. */
  3774. clone() {
  3775. return new this.constructor( this.x, this.y, this.z );
  3776. }
  3777. /**
  3778. * Copies the values of the given vector to this instance.
  3779. *
  3780. * @param {Vector3} v - The vector to copy.
  3781. * @return {Vector3} A reference to this vector.
  3782. */
  3783. copy( v ) {
  3784. this.x = v.x;
  3785. this.y = v.y;
  3786. this.z = v.z;
  3787. return this;
  3788. }
  3789. /**
  3790. * Adds the given vector to this instance.
  3791. *
  3792. * @param {Vector3} v - The vector to add.
  3793. * @return {Vector3} A reference to this vector.
  3794. */
  3795. add( v ) {
  3796. this.x += v.x;
  3797. this.y += v.y;
  3798. this.z += v.z;
  3799. return this;
  3800. }
  3801. /**
  3802. * Adds the given scalar value to all components of this instance.
  3803. *
  3804. * @param {number} s - The scalar to add.
  3805. * @return {Vector3} A reference to this vector.
  3806. */
  3807. addScalar( s ) {
  3808. this.x += s;
  3809. this.y += s;
  3810. this.z += s;
  3811. return this;
  3812. }
  3813. /**
  3814. * Adds the given vectors and stores the result in this instance.
  3815. *
  3816. * @param {Vector3} a - The first vector.
  3817. * @param {Vector3} b - The second vector.
  3818. * @return {Vector3} A reference to this vector.
  3819. */
  3820. addVectors( a, b ) {
  3821. this.x = a.x + b.x;
  3822. this.y = a.y + b.y;
  3823. this.z = a.z + b.z;
  3824. return this;
  3825. }
  3826. /**
  3827. * Adds the given vector scaled by the given factor to this instance.
  3828. *
  3829. * @param {Vector3|Vector4} v - The vector.
  3830. * @param {number} s - The factor that scales `v`.
  3831. * @return {Vector3} A reference to this vector.
  3832. */
  3833. addScaledVector( v, s ) {
  3834. this.x += v.x * s;
  3835. this.y += v.y * s;
  3836. this.z += v.z * s;
  3837. return this;
  3838. }
  3839. /**
  3840. * Subtracts the given vector from this instance.
  3841. *
  3842. * @param {Vector3} v - The vector to subtract.
  3843. * @return {Vector3} A reference to this vector.
  3844. */
  3845. sub( v ) {
  3846. this.x -= v.x;
  3847. this.y -= v.y;
  3848. this.z -= v.z;
  3849. return this;
  3850. }
  3851. /**
  3852. * Subtracts the given scalar value from all components of this instance.
  3853. *
  3854. * @param {number} s - The scalar to subtract.
  3855. * @return {Vector3} A reference to this vector.
  3856. */
  3857. subScalar( s ) {
  3858. this.x -= s;
  3859. this.y -= s;
  3860. this.z -= s;
  3861. return this;
  3862. }
  3863. /**
  3864. * Subtracts the given vectors and stores the result in this instance.
  3865. *
  3866. * @param {Vector3} a - The first vector.
  3867. * @param {Vector3} b - The second vector.
  3868. * @return {Vector3} A reference to this vector.
  3869. */
  3870. subVectors( a, b ) {
  3871. this.x = a.x - b.x;
  3872. this.y = a.y - b.y;
  3873. this.z = a.z - b.z;
  3874. return this;
  3875. }
  3876. /**
  3877. * Multiplies the given vector with this instance.
  3878. *
  3879. * @param {Vector3} v - The vector to multiply.
  3880. * @return {Vector3} A reference to this vector.
  3881. */
  3882. multiply( v ) {
  3883. this.x *= v.x;
  3884. this.y *= v.y;
  3885. this.z *= v.z;
  3886. return this;
  3887. }
  3888. /**
  3889. * Multiplies the given scalar value with all components of this instance.
  3890. *
  3891. * @param {number} scalar - The scalar to multiply.
  3892. * @return {Vector3} A reference to this vector.
  3893. */
  3894. multiplyScalar( scalar ) {
  3895. this.x *= scalar;
  3896. this.y *= scalar;
  3897. this.z *= scalar;
  3898. return this;
  3899. }
  3900. /**
  3901. * Multiplies the given vectors and stores the result in this instance.
  3902. *
  3903. * @param {Vector3} a - The first vector.
  3904. * @param {Vector3} b - The second vector.
  3905. * @return {Vector3} A reference to this vector.
  3906. */
  3907. multiplyVectors( a, b ) {
  3908. this.x = a.x * b.x;
  3909. this.y = a.y * b.y;
  3910. this.z = a.z * b.z;
  3911. return this;
  3912. }
  3913. /**
  3914. * Applies the given Euler rotation to this vector.
  3915. *
  3916. * @param {Euler} euler - The Euler angles.
  3917. * @return {Vector3} A reference to this vector.
  3918. */
  3919. applyEuler( euler ) {
  3920. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3921. }
  3922. /**
  3923. * Applies a rotation specified by an axis and an angle to this vector.
  3924. *
  3925. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3926. * @param {number} angle - The angle in radians.
  3927. * @return {Vector3} A reference to this vector.
  3928. */
  3929. applyAxisAngle( axis, angle ) {
  3930. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3931. }
  3932. /**
  3933. * Multiplies this vector with the given 3x3 matrix.
  3934. *
  3935. * @param {Matrix3} m - The 3x3 matrix.
  3936. * @return {Vector3} A reference to this vector.
  3937. */
  3938. applyMatrix3( m ) {
  3939. const x = this.x, y = this.y, z = this.z;
  3940. const e = m.elements;
  3941. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3942. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3943. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3944. return this;
  3945. }
  3946. /**
  3947. * Multiplies this vector by the given normal matrix and normalizes
  3948. * the result.
  3949. *
  3950. * @param {Matrix3} m - The normal matrix.
  3951. * @return {Vector3} A reference to this vector.
  3952. */
  3953. applyNormalMatrix( m ) {
  3954. return this.applyMatrix3( m ).normalize();
  3955. }
  3956. /**
  3957. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3958. * divides by perspective.
  3959. *
  3960. * @param {Matrix4} m - The matrix to apply.
  3961. * @return {Vector3} A reference to this vector.
  3962. */
  3963. applyMatrix4( m ) {
  3964. const x = this.x, y = this.y, z = this.z;
  3965. const e = m.elements;
  3966. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3967. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3968. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3969. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3970. return this;
  3971. }
  3972. /**
  3973. * Applies the given Quaternion to this vector.
  3974. *
  3975. * @param {Quaternion} q - The Quaternion.
  3976. * @return {Vector3} A reference to this vector.
  3977. */
  3978. applyQuaternion( q ) {
  3979. // quaternion q is assumed to have unit length
  3980. const vx = this.x, vy = this.y, vz = this.z;
  3981. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3982. // t = 2 * cross( q.xyz, v );
  3983. const tx = 2 * ( qy * vz - qz * vy );
  3984. const ty = 2 * ( qz * vx - qx * vz );
  3985. const tz = 2 * ( qx * vy - qy * vx );
  3986. // v + q.w * t + cross( q.xyz, t );
  3987. this.x = vx + qw * tx + qy * tz - qz * ty;
  3988. this.y = vy + qw * ty + qz * tx - qx * tz;
  3989. this.z = vz + qw * tz + qx * ty - qy * tx;
  3990. return this;
  3991. }
  3992. /**
  3993. * Projects this vector from world space into the camera's normalized
  3994. * device coordinate (NDC) space.
  3995. *
  3996. * @param {Camera} camera - The camera.
  3997. * @return {Vector3} A reference to this vector.
  3998. */
  3999. project( camera ) {
  4000. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4001. }
  4002. /**
  4003. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4004. * space into world space.
  4005. *
  4006. * @param {Camera} camera - The camera.
  4007. * @return {Vector3} A reference to this vector.
  4008. */
  4009. unproject( camera ) {
  4010. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4011. }
  4012. /**
  4013. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4014. * subset of the given 4x4 matrix and then normalizes the result.
  4015. *
  4016. * @param {Matrix4} m - The matrix.
  4017. * @return {Vector3} A reference to this vector.
  4018. */
  4019. transformDirection( m ) {
  4020. // input: THREE.Matrix4 affine matrix
  4021. // vector interpreted as a direction
  4022. const x = this.x, y = this.y, z = this.z;
  4023. const e = m.elements;
  4024. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4025. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4026. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4027. return this.normalize();
  4028. }
  4029. /**
  4030. * Divides this instance by the given vector.
  4031. *
  4032. * @param {Vector3} v - The vector to divide.
  4033. * @return {Vector3} A reference to this vector.
  4034. */
  4035. divide( v ) {
  4036. this.x /= v.x;
  4037. this.y /= v.y;
  4038. this.z /= v.z;
  4039. return this;
  4040. }
  4041. /**
  4042. * Divides this vector by the given scalar.
  4043. *
  4044. * @param {number} scalar - The scalar to divide.
  4045. * @return {Vector3} A reference to this vector.
  4046. */
  4047. divideScalar( scalar ) {
  4048. return this.multiplyScalar( 1 / scalar );
  4049. }
  4050. /**
  4051. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4052. * value, replace that value with the corresponding min value.
  4053. *
  4054. * @param {Vector3} v - The vector.
  4055. * @return {Vector3} A reference to this vector.
  4056. */
  4057. min( v ) {
  4058. this.x = Math.min( this.x, v.x );
  4059. this.y = Math.min( this.y, v.y );
  4060. this.z = Math.min( this.z, v.z );
  4061. return this;
  4062. }
  4063. /**
  4064. * If this vector's x, y or z value is less than the given vector's x, y or z
  4065. * value, replace that value with the corresponding max value.
  4066. *
  4067. * @param {Vector3} v - The vector.
  4068. * @return {Vector3} A reference to this vector.
  4069. */
  4070. max( v ) {
  4071. this.x = Math.max( this.x, v.x );
  4072. this.y = Math.max( this.y, v.y );
  4073. this.z = Math.max( this.z, v.z );
  4074. return this;
  4075. }
  4076. /**
  4077. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4078. * value, it is replaced by the corresponding value.
  4079. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4080. * it is replaced by the corresponding value.
  4081. *
  4082. * @param {Vector3} min - The minimum x, y and z values.
  4083. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4084. * @return {Vector3} A reference to this vector.
  4085. */
  4086. clamp( min, max ) {
  4087. // assumes min < max, componentwise
  4088. this.x = clamp( this.x, min.x, max.x );
  4089. this.y = clamp( this.y, min.y, max.y );
  4090. this.z = clamp( this.z, min.z, max.z );
  4091. return this;
  4092. }
  4093. /**
  4094. * If this vector's x, y or z values are greater than the max value, they are
  4095. * replaced by the max value.
  4096. * If this vector's x, y or z values are less than the min value, they are
  4097. * replaced by the min value.
  4098. *
  4099. * @param {number} minVal - The minimum value the components will be clamped to.
  4100. * @param {number} maxVal - The maximum value the components will be clamped to.
  4101. * @return {Vector3} A reference to this vector.
  4102. */
  4103. clampScalar( minVal, maxVal ) {
  4104. this.x = clamp( this.x, minVal, maxVal );
  4105. this.y = clamp( this.y, minVal, maxVal );
  4106. this.z = clamp( this.z, minVal, maxVal );
  4107. return this;
  4108. }
  4109. /**
  4110. * If this vector's length is greater than the max value, it is replaced by
  4111. * the max value.
  4112. * If this vector's length is less than the min value, it is replaced by the
  4113. * min value.
  4114. *
  4115. * @param {number} min - The minimum value the vector length will be clamped to.
  4116. * @param {number} max - The maximum value the vector length will be clamped to.
  4117. * @return {Vector3} A reference to this vector.
  4118. */
  4119. clampLength( min, max ) {
  4120. const length = this.length();
  4121. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4122. }
  4123. /**
  4124. * The components of this vector are rounded down to the nearest integer value.
  4125. *
  4126. * @return {Vector3} A reference to this vector.
  4127. */
  4128. floor() {
  4129. this.x = Math.floor( this.x );
  4130. this.y = Math.floor( this.y );
  4131. this.z = Math.floor( this.z );
  4132. return this;
  4133. }
  4134. /**
  4135. * The components of this vector are rounded up to the nearest integer value.
  4136. *
  4137. * @return {Vector3} A reference to this vector.
  4138. */
  4139. ceil() {
  4140. this.x = Math.ceil( this.x );
  4141. this.y = Math.ceil( this.y );
  4142. this.z = Math.ceil( this.z );
  4143. return this;
  4144. }
  4145. /**
  4146. * The components of this vector are rounded to the nearest integer value
  4147. *
  4148. * @return {Vector3} A reference to this vector.
  4149. */
  4150. round() {
  4151. this.x = Math.round( this.x );
  4152. this.y = Math.round( this.y );
  4153. this.z = Math.round( this.z );
  4154. return this;
  4155. }
  4156. /**
  4157. * The components of this vector are rounded towards zero (up if negative,
  4158. * down if positive) to an integer value.
  4159. *
  4160. * @return {Vector3} A reference to this vector.
  4161. */
  4162. roundToZero() {
  4163. this.x = Math.trunc( this.x );
  4164. this.y = Math.trunc( this.y );
  4165. this.z = Math.trunc( this.z );
  4166. return this;
  4167. }
  4168. /**
  4169. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4170. *
  4171. * @return {Vector3} A reference to this vector.
  4172. */
  4173. negate() {
  4174. this.x = - this.x;
  4175. this.y = - this.y;
  4176. this.z = - this.z;
  4177. return this;
  4178. }
  4179. /**
  4180. * Calculates the dot product of the given vector with this instance.
  4181. *
  4182. * @param {Vector3} v - The vector to compute the dot product with.
  4183. * @return {number} The result of the dot product.
  4184. */
  4185. dot( v ) {
  4186. return this.x * v.x + this.y * v.y + this.z * v.z;
  4187. }
  4188. /**
  4189. * Computes the square of the Euclidean length (straight-line length) from
  4190. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4191. * compare the length squared instead as it is slightly more efficient to calculate.
  4192. *
  4193. * @return {number} The square length of this vector.
  4194. */
  4195. lengthSq() {
  4196. return this.x * this.x + this.y * this.y + this.z * this.z;
  4197. }
  4198. /**
  4199. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4200. *
  4201. * @return {number} The length of this vector.
  4202. */
  4203. length() {
  4204. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4205. }
  4206. /**
  4207. * Computes the Manhattan length of this vector.
  4208. *
  4209. * @return {number} The length of this vector.
  4210. */
  4211. manhattanLength() {
  4212. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4213. }
  4214. /**
  4215. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4216. * with the same direction as this one, but with a vector length of `1`.
  4217. *
  4218. * @return {Vector3} A reference to this vector.
  4219. */
  4220. normalize() {
  4221. return this.divideScalar( this.length() || 1 );
  4222. }
  4223. /**
  4224. * Sets this vector to a vector with the same direction as this one, but
  4225. * with the specified length.
  4226. *
  4227. * @param {number} length - The new length of this vector.
  4228. * @return {Vector3} A reference to this vector.
  4229. */
  4230. setLength( length ) {
  4231. return this.normalize().multiplyScalar( length );
  4232. }
  4233. /**
  4234. * Linearly interpolates between the given vector and this instance, where
  4235. * alpha is the percent distance along the line - alpha = 0 will be this
  4236. * vector, and alpha = 1 will be the given one.
  4237. *
  4238. * @param {Vector3} v - The vector to interpolate towards.
  4239. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4240. * @return {Vector3} A reference to this vector.
  4241. */
  4242. lerp( v, alpha ) {
  4243. this.x += ( v.x - this.x ) * alpha;
  4244. this.y += ( v.y - this.y ) * alpha;
  4245. this.z += ( v.z - this.z ) * alpha;
  4246. return this;
  4247. }
  4248. /**
  4249. * Linearly interpolates between the given vectors, where alpha is the percent
  4250. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4251. * be the second one. The result is stored in this instance.
  4252. *
  4253. * @param {Vector3} v1 - The first vector.
  4254. * @param {Vector3} v2 - The second vector.
  4255. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4256. * @return {Vector3} A reference to this vector.
  4257. */
  4258. lerpVectors( v1, v2, alpha ) {
  4259. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4260. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4261. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4262. return this;
  4263. }
  4264. /**
  4265. * Calculates the cross product of the given vector with this instance.
  4266. *
  4267. * @param {Vector3} v - The vector to compute the cross product with.
  4268. * @return {Vector3} The result of the cross product.
  4269. */
  4270. cross( v ) {
  4271. return this.crossVectors( this, v );
  4272. }
  4273. /**
  4274. * Calculates the cross product of the given vectors and stores the result
  4275. * in this instance.
  4276. *
  4277. * @param {Vector3} a - The first vector.
  4278. * @param {Vector3} b - The second vector.
  4279. * @return {Vector3} A reference to this vector.
  4280. */
  4281. crossVectors( a, b ) {
  4282. const ax = a.x, ay = a.y, az = a.z;
  4283. const bx = b.x, by = b.y, bz = b.z;
  4284. this.x = ay * bz - az * by;
  4285. this.y = az * bx - ax * bz;
  4286. this.z = ax * by - ay * bx;
  4287. return this;
  4288. }
  4289. /**
  4290. * Projects this vector onto the given one.
  4291. *
  4292. * @param {Vector3} v - The vector to project to.
  4293. * @return {Vector3} A reference to this vector.
  4294. */
  4295. projectOnVector( v ) {
  4296. const denominator = v.lengthSq();
  4297. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4298. const scalar = v.dot( this ) / denominator;
  4299. return this.copy( v ).multiplyScalar( scalar );
  4300. }
  4301. /**
  4302. * Projects this vector onto a plane by subtracting this
  4303. * vector projected onto the plane's normal from this vector.
  4304. *
  4305. * @param {Vector3} planeNormal - The plane normal.
  4306. * @return {Vector3} A reference to this vector.
  4307. */
  4308. projectOnPlane( planeNormal ) {
  4309. _vector$c.copy( this ).projectOnVector( planeNormal );
  4310. return this.sub( _vector$c );
  4311. }
  4312. /**
  4313. * Reflects this vector off a plane orthogonal to the given normal vector.
  4314. *
  4315. * @param {Vector3} normal - The (normalized) normal vector.
  4316. * @return {Vector3} A reference to this vector.
  4317. */
  4318. reflect( normal ) {
  4319. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4320. }
  4321. /**
  4322. * Returns the angle between the given vector and this instance in radians.
  4323. *
  4324. * @param {Vector3} v - The vector to compute the angle with.
  4325. * @return {number} The angle in radians.
  4326. */
  4327. angleTo( v ) {
  4328. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4329. if ( denominator === 0 ) return Math.PI / 2;
  4330. const theta = this.dot( v ) / denominator;
  4331. // clamp, to handle numerical problems
  4332. return Math.acos( clamp( theta, -1, 1 ) );
  4333. }
  4334. /**
  4335. * Computes the distance from the given vector to this instance.
  4336. *
  4337. * @param {Vector3} v - The vector to compute the distance to.
  4338. * @return {number} The distance.
  4339. */
  4340. distanceTo( v ) {
  4341. return Math.sqrt( this.distanceToSquared( v ) );
  4342. }
  4343. /**
  4344. * Computes the squared distance from the given vector to this instance.
  4345. * If you are just comparing the distance with another distance, you should compare
  4346. * the distance squared instead as it is slightly more efficient to calculate.
  4347. *
  4348. * @param {Vector3} v - The vector to compute the squared distance to.
  4349. * @return {number} The squared distance.
  4350. */
  4351. distanceToSquared( v ) {
  4352. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4353. return dx * dx + dy * dy + dz * dz;
  4354. }
  4355. /**
  4356. * Computes the Manhattan distance from the given vector to this instance.
  4357. *
  4358. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4359. * @return {number} The Manhattan distance.
  4360. */
  4361. manhattanDistanceTo( v ) {
  4362. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4363. }
  4364. /**
  4365. * Sets the vector components from the given spherical coordinates.
  4366. *
  4367. * @param {Spherical} s - The spherical coordinates.
  4368. * @return {Vector3} A reference to this vector.
  4369. */
  4370. setFromSpherical( s ) {
  4371. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4372. }
  4373. /**
  4374. * Sets the vector components from the given spherical coordinates.
  4375. *
  4376. * @param {number} radius - The radius.
  4377. * @param {number} phi - The phi angle in radians.
  4378. * @param {number} theta - The theta angle in radians.
  4379. * @return {Vector3} A reference to this vector.
  4380. */
  4381. setFromSphericalCoords( radius, phi, theta ) {
  4382. const sinPhiRadius = Math.sin( phi ) * radius;
  4383. this.x = sinPhiRadius * Math.sin( theta );
  4384. this.y = Math.cos( phi ) * radius;
  4385. this.z = sinPhiRadius * Math.cos( theta );
  4386. return this;
  4387. }
  4388. /**
  4389. * Sets the vector components from the given cylindrical coordinates.
  4390. *
  4391. * @param {Cylindrical} c - The cylindrical coordinates.
  4392. * @return {Vector3} A reference to this vector.
  4393. */
  4394. setFromCylindrical( c ) {
  4395. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4396. }
  4397. /**
  4398. * Sets the vector components from the given cylindrical coordinates.
  4399. *
  4400. * @param {number} radius - The radius.
  4401. * @param {number} theta - The theta angle in radians.
  4402. * @param {number} y - The y value.
  4403. * @return {Vector3} A reference to this vector.
  4404. */
  4405. setFromCylindricalCoords( radius, theta, y ) {
  4406. this.x = radius * Math.sin( theta );
  4407. this.y = y;
  4408. this.z = radius * Math.cos( theta );
  4409. return this;
  4410. }
  4411. /**
  4412. * Sets the vector components to the position elements of the
  4413. * given transformation matrix.
  4414. *
  4415. * @param {Matrix4} m - The 4x4 matrix.
  4416. * @return {Vector3} A reference to this vector.
  4417. */
  4418. setFromMatrixPosition( m ) {
  4419. const e = m.elements;
  4420. this.x = e[ 12 ];
  4421. this.y = e[ 13 ];
  4422. this.z = e[ 14 ];
  4423. return this;
  4424. }
  4425. /**
  4426. * Sets the vector components to the scale elements of the
  4427. * given transformation matrix.
  4428. *
  4429. * @param {Matrix4} m - The 4x4 matrix.
  4430. * @return {Vector3} A reference to this vector.
  4431. */
  4432. setFromMatrixScale( m ) {
  4433. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4434. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4435. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4436. this.x = sx;
  4437. this.y = sy;
  4438. this.z = sz;
  4439. return this;
  4440. }
  4441. /**
  4442. * Sets the vector components from the specified matrix column.
  4443. *
  4444. * @param {Matrix4} m - The 4x4 matrix.
  4445. * @param {number} index - The column index.
  4446. * @return {Vector3} A reference to this vector.
  4447. */
  4448. setFromMatrixColumn( m, index ) {
  4449. return this.fromArray( m.elements, index * 4 );
  4450. }
  4451. /**
  4452. * Sets the vector components from the specified matrix column.
  4453. *
  4454. * @param {Matrix3} m - The 3x3 matrix.
  4455. * @param {number} index - The column index.
  4456. * @return {Vector3} A reference to this vector.
  4457. */
  4458. setFromMatrix3Column( m, index ) {
  4459. return this.fromArray( m.elements, index * 3 );
  4460. }
  4461. /**
  4462. * Sets the vector components from the given Euler angles.
  4463. *
  4464. * @param {Euler} e - The Euler angles to set.
  4465. * @return {Vector3} A reference to this vector.
  4466. */
  4467. setFromEuler( e ) {
  4468. this.x = e._x;
  4469. this.y = e._y;
  4470. this.z = e._z;
  4471. return this;
  4472. }
  4473. /**
  4474. * Sets the vector components from the RGB components of the
  4475. * given color.
  4476. *
  4477. * @param {Color} c - The color to set.
  4478. * @return {Vector3} A reference to this vector.
  4479. */
  4480. setFromColor( c ) {
  4481. this.x = c.r;
  4482. this.y = c.g;
  4483. this.z = c.b;
  4484. return this;
  4485. }
  4486. /**
  4487. * Returns `true` if this vector is equal with the given one.
  4488. *
  4489. * @param {Vector3} v - The vector to test for equality.
  4490. * @return {boolean} Whether this vector is equal with the given one.
  4491. */
  4492. equals( v ) {
  4493. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4494. }
  4495. /**
  4496. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4497. * and z value to be `array[ offset + 2 ]`.
  4498. *
  4499. * @param {Array<number>} array - An array holding the vector component values.
  4500. * @param {number} [offset=0] - The offset into the array.
  4501. * @return {Vector3} A reference to this vector.
  4502. */
  4503. fromArray( array, offset = 0 ) {
  4504. this.x = array[ offset ];
  4505. this.y = array[ offset + 1 ];
  4506. this.z = array[ offset + 2 ];
  4507. return this;
  4508. }
  4509. /**
  4510. * Writes the components of this vector to the given array. If no array is provided,
  4511. * the method returns a new instance.
  4512. *
  4513. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4514. * @param {number} [offset=0] - Index of the first element in the array.
  4515. * @return {Array<number>} The vector components.
  4516. */
  4517. toArray( array = [], offset = 0 ) {
  4518. array[ offset ] = this.x;
  4519. array[ offset + 1 ] = this.y;
  4520. array[ offset + 2 ] = this.z;
  4521. return array;
  4522. }
  4523. /**
  4524. * Sets the components of this vector from the given buffer attribute.
  4525. *
  4526. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4527. * @param {number} index - The index into the attribute.
  4528. * @return {Vector3} A reference to this vector.
  4529. */
  4530. fromBufferAttribute( attribute, index ) {
  4531. this.x = attribute.getX( index );
  4532. this.y = attribute.getY( index );
  4533. this.z = attribute.getZ( index );
  4534. return this;
  4535. }
  4536. /**
  4537. * Sets each component of this vector to a pseudo-random value between `0` and
  4538. * `1`, excluding `1`.
  4539. *
  4540. * @return {Vector3} A reference to this vector.
  4541. */
  4542. random() {
  4543. this.x = Math.random();
  4544. this.y = Math.random();
  4545. this.z = Math.random();
  4546. return this;
  4547. }
  4548. /**
  4549. * Sets this vector to a uniformly random point on a unit sphere.
  4550. *
  4551. * @return {Vector3} A reference to this vector.
  4552. */
  4553. randomDirection() {
  4554. // https://mathworld.wolfram.com/SpherePointPicking.html
  4555. const theta = Math.random() * Math.PI * 2;
  4556. const u = Math.random() * 2 - 1;
  4557. const c = Math.sqrt( 1 - u * u );
  4558. this.x = c * Math.cos( theta );
  4559. this.y = u;
  4560. this.z = c * Math.sin( theta );
  4561. return this;
  4562. }
  4563. *[ Symbol.iterator ]() {
  4564. yield this.x;
  4565. yield this.y;
  4566. yield this.z;
  4567. }
  4568. }
  4569. const _vector$c = /*@__PURE__*/ new Vector3();
  4570. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4571. /**
  4572. * Represents a 3x3 matrix.
  4573. *
  4574. * A Note on Row-Major and Column-Major Ordering:
  4575. *
  4576. * The constructor and {@link Matrix3#set} method take arguments in
  4577. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4578. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4579. * This means that calling:
  4580. * ```js
  4581. * const m = new THREE.Matrix();
  4582. * m.set( 11, 12, 13,
  4583. * 21, 22, 23,
  4584. * 31, 32, 33 );
  4585. * ```
  4586. * will result in the elements array containing:
  4587. * ```js
  4588. * m.elements = [ 11, 21, 31,
  4589. * 12, 22, 32,
  4590. * 13, 23, 33 ];
  4591. * ```
  4592. * and internally all calculations are performed using column-major ordering.
  4593. * However, as the actual ordering makes no difference mathematically and
  4594. * most people are used to thinking about matrices in row-major order, the
  4595. * three.js documentation shows matrices in row-major order. Just bear in
  4596. * mind that if you are reading the source code, you'll have to take the
  4597. * transpose of any matrices outlined here to make sense of the calculations.
  4598. */
  4599. class Matrix3 {
  4600. /**
  4601. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4602. * in row-major order. If no arguments are provided, the constructor
  4603. * initializes the matrix as an identity matrix.
  4604. *
  4605. * @param {number} [n11] - 1-1 matrix element.
  4606. * @param {number} [n12] - 1-2 matrix element.
  4607. * @param {number} [n13] - 1-3 matrix element.
  4608. * @param {number} [n21] - 2-1 matrix element.
  4609. * @param {number} [n22] - 2-2 matrix element.
  4610. * @param {number} [n23] - 2-3 matrix element.
  4611. * @param {number} [n31] - 3-1 matrix element.
  4612. * @param {number} [n32] - 3-2 matrix element.
  4613. * @param {number} [n33] - 3-3 matrix element.
  4614. */
  4615. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4616. /**
  4617. * This flag can be used for type testing.
  4618. *
  4619. * @type {boolean}
  4620. * @readonly
  4621. * @default true
  4622. */
  4623. Matrix3.prototype.isMatrix3 = true;
  4624. /**
  4625. * A column-major list of matrix values.
  4626. *
  4627. * @type {Array<number>}
  4628. */
  4629. this.elements = [
  4630. 1, 0, 0,
  4631. 0, 1, 0,
  4632. 0, 0, 1
  4633. ];
  4634. if ( n11 !== undefined ) {
  4635. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4636. }
  4637. }
  4638. /**
  4639. * Sets the elements of the matrix.The arguments are supposed to be
  4640. * in row-major order.
  4641. *
  4642. * @param {number} [n11] - 1-1 matrix element.
  4643. * @param {number} [n12] - 1-2 matrix element.
  4644. * @param {number} [n13] - 1-3 matrix element.
  4645. * @param {number} [n21] - 2-1 matrix element.
  4646. * @param {number} [n22] - 2-2 matrix element.
  4647. * @param {number} [n23] - 2-3 matrix element.
  4648. * @param {number} [n31] - 3-1 matrix element.
  4649. * @param {number} [n32] - 3-2 matrix element.
  4650. * @param {number} [n33] - 3-3 matrix element.
  4651. * @return {Matrix3} A reference to this matrix.
  4652. */
  4653. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4654. const te = this.elements;
  4655. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4656. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4657. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4658. return this;
  4659. }
  4660. /**
  4661. * Sets this matrix to the 3x3 identity matrix.
  4662. *
  4663. * @return {Matrix3} A reference to this matrix.
  4664. */
  4665. identity() {
  4666. this.set(
  4667. 1, 0, 0,
  4668. 0, 1, 0,
  4669. 0, 0, 1
  4670. );
  4671. return this;
  4672. }
  4673. /**
  4674. * Copies the values of the given matrix to this instance.
  4675. *
  4676. * @param {Matrix3} m - The matrix to copy.
  4677. * @return {Matrix3} A reference to this matrix.
  4678. */
  4679. copy( m ) {
  4680. const te = this.elements;
  4681. const me = m.elements;
  4682. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4683. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4684. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4685. return this;
  4686. }
  4687. /**
  4688. * Extracts the basis of this matrix into the three axis vectors provided.
  4689. *
  4690. * @param {Vector3} xAxis - The basis's x axis.
  4691. * @param {Vector3} yAxis - The basis's y axis.
  4692. * @param {Vector3} zAxis - The basis's z axis.
  4693. * @return {Matrix3} A reference to this matrix.
  4694. */
  4695. extractBasis( xAxis, yAxis, zAxis ) {
  4696. xAxis.setFromMatrix3Column( this, 0 );
  4697. yAxis.setFromMatrix3Column( this, 1 );
  4698. zAxis.setFromMatrix3Column( this, 2 );
  4699. return this;
  4700. }
  4701. /**
  4702. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4703. *
  4704. * @param {Matrix4} m - The 4x4 matrix.
  4705. * @return {Matrix3} A reference to this matrix.
  4706. */
  4707. setFromMatrix4( m ) {
  4708. const me = m.elements;
  4709. this.set(
  4710. me[ 0 ], me[ 4 ], me[ 8 ],
  4711. me[ 1 ], me[ 5 ], me[ 9 ],
  4712. me[ 2 ], me[ 6 ], me[ 10 ]
  4713. );
  4714. return this;
  4715. }
  4716. /**
  4717. * Post-multiplies this matrix by the given 3x3 matrix.
  4718. *
  4719. * @param {Matrix3} m - The matrix to multiply with.
  4720. * @return {Matrix3} A reference to this matrix.
  4721. */
  4722. multiply( m ) {
  4723. return this.multiplyMatrices( this, m );
  4724. }
  4725. /**
  4726. * Pre-multiplies this matrix by the given 3x3 matrix.
  4727. *
  4728. * @param {Matrix3} m - The matrix to multiply with.
  4729. * @return {Matrix3} A reference to this matrix.
  4730. */
  4731. premultiply( m ) {
  4732. return this.multiplyMatrices( m, this );
  4733. }
  4734. /**
  4735. * Multiples the given 3x3 matrices and stores the result
  4736. * in this matrix.
  4737. *
  4738. * @param {Matrix3} a - The first matrix.
  4739. * @param {Matrix3} b - The second matrix.
  4740. * @return {Matrix3} A reference to this matrix.
  4741. */
  4742. multiplyMatrices( a, b ) {
  4743. const ae = a.elements;
  4744. const be = b.elements;
  4745. const te = this.elements;
  4746. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4747. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4748. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4749. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4750. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4751. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4752. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4753. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4754. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4755. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4756. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4757. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4758. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4759. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4760. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4761. return this;
  4762. }
  4763. /**
  4764. * Multiplies every component of the matrix by the given scalar.
  4765. *
  4766. * @param {number} s - The scalar.
  4767. * @return {Matrix3} A reference to this matrix.
  4768. */
  4769. multiplyScalar( s ) {
  4770. const te = this.elements;
  4771. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4772. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4773. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4774. return this;
  4775. }
  4776. /**
  4777. * Computes and returns the determinant of this matrix.
  4778. *
  4779. * @return {number} The determinant.
  4780. */
  4781. determinant() {
  4782. const te = this.elements;
  4783. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4784. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4785. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4786. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4787. }
  4788. /**
  4789. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4790. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4791. * a zero matrix instead.
  4792. *
  4793. * @return {Matrix3} A reference to this matrix.
  4794. */
  4795. invert() {
  4796. const te = this.elements,
  4797. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4798. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4799. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4800. t11 = n33 * n22 - n32 * n23,
  4801. t12 = n32 * n13 - n33 * n12,
  4802. t13 = n23 * n12 - n22 * n13,
  4803. det = n11 * t11 + n21 * t12 + n31 * t13;
  4804. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4805. const detInv = 1 / det;
  4806. te[ 0 ] = t11 * detInv;
  4807. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4808. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4809. te[ 3 ] = t12 * detInv;
  4810. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4811. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4812. te[ 6 ] = t13 * detInv;
  4813. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4814. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4815. return this;
  4816. }
  4817. /**
  4818. * Transposes this matrix in place.
  4819. *
  4820. * @return {Matrix3} A reference to this matrix.
  4821. */
  4822. transpose() {
  4823. let tmp;
  4824. const m = this.elements;
  4825. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4826. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4827. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4828. return this;
  4829. }
  4830. /**
  4831. * Computes the normal matrix which is the inverse transpose of the upper
  4832. * left 3x3 portion of the given 4x4 matrix.
  4833. *
  4834. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4835. * @return {Matrix3} A reference to this matrix.
  4836. */
  4837. getNormalMatrix( matrix4 ) {
  4838. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4839. }
  4840. /**
  4841. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4842. *
  4843. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4844. * @return {Matrix3} A reference to this matrix.
  4845. */
  4846. transposeIntoArray( r ) {
  4847. const m = this.elements;
  4848. r[ 0 ] = m[ 0 ];
  4849. r[ 1 ] = m[ 3 ];
  4850. r[ 2 ] = m[ 6 ];
  4851. r[ 3 ] = m[ 1 ];
  4852. r[ 4 ] = m[ 4 ];
  4853. r[ 5 ] = m[ 7 ];
  4854. r[ 6 ] = m[ 2 ];
  4855. r[ 7 ] = m[ 5 ];
  4856. r[ 8 ] = m[ 8 ];
  4857. return this;
  4858. }
  4859. /**
  4860. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4861. *
  4862. * @param {number} tx - Offset x.
  4863. * @param {number} ty - Offset y.
  4864. * @param {number} sx - Repeat x.
  4865. * @param {number} sy - Repeat y.
  4866. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4867. * @param {number} cx - Center x of rotation.
  4868. * @param {number} cy - Center y of rotation
  4869. * @return {Matrix3} A reference to this matrix.
  4870. */
  4871. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4872. const c = Math.cos( rotation );
  4873. const s = Math.sin( rotation );
  4874. this.set(
  4875. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4876. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4877. 0, 0, 1
  4878. );
  4879. return this;
  4880. }
  4881. /**
  4882. * Scales this matrix with the given scalar values.
  4883. *
  4884. * @param {number} sx - The amount to scale in the X axis.
  4885. * @param {number} sy - The amount to scale in the Y axis.
  4886. * @return {Matrix3} A reference to this matrix.
  4887. */
  4888. scale( sx, sy ) {
  4889. this.premultiply( _m3.makeScale( sx, sy ) );
  4890. return this;
  4891. }
  4892. /**
  4893. * Rotates this matrix by the given angle.
  4894. *
  4895. * @param {number} theta - The rotation in radians.
  4896. * @return {Matrix3} A reference to this matrix.
  4897. */
  4898. rotate( theta ) {
  4899. this.premultiply( _m3.makeRotation( - theta ) );
  4900. return this;
  4901. }
  4902. /**
  4903. * Translates this matrix by the given scalar values.
  4904. *
  4905. * @param {number} tx - The amount to translate in the X axis.
  4906. * @param {number} ty - The amount to translate in the Y axis.
  4907. * @return {Matrix3} A reference to this matrix.
  4908. */
  4909. translate( tx, ty ) {
  4910. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4911. return this;
  4912. }
  4913. // for 2D Transforms
  4914. /**
  4915. * Sets this matrix as a 2D translation transform.
  4916. *
  4917. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4918. * @param {number} y - The amount to translate in the Y axis.
  4919. * @return {Matrix3} A reference to this matrix.
  4920. */
  4921. makeTranslation( x, y ) {
  4922. if ( x.isVector2 ) {
  4923. this.set(
  4924. 1, 0, x.x,
  4925. 0, 1, x.y,
  4926. 0, 0, 1
  4927. );
  4928. } else {
  4929. this.set(
  4930. 1, 0, x,
  4931. 0, 1, y,
  4932. 0, 0, 1
  4933. );
  4934. }
  4935. return this;
  4936. }
  4937. /**
  4938. * Sets this matrix as a 2D rotational transformation.
  4939. *
  4940. * @param {number} theta - The rotation in radians.
  4941. * @return {Matrix3} A reference to this matrix.
  4942. */
  4943. makeRotation( theta ) {
  4944. // counterclockwise
  4945. const c = Math.cos( theta );
  4946. const s = Math.sin( theta );
  4947. this.set(
  4948. c, - s, 0,
  4949. s, c, 0,
  4950. 0, 0, 1
  4951. );
  4952. return this;
  4953. }
  4954. /**
  4955. * Sets this matrix as a 2D scale transform.
  4956. *
  4957. * @param {number} x - The amount to scale in the X axis.
  4958. * @param {number} y - The amount to scale in the Y axis.
  4959. * @return {Matrix3} A reference to this matrix.
  4960. */
  4961. makeScale( x, y ) {
  4962. this.set(
  4963. x, 0, 0,
  4964. 0, y, 0,
  4965. 0, 0, 1
  4966. );
  4967. return this;
  4968. }
  4969. /**
  4970. * Returns `true` if this matrix is equal with the given one.
  4971. *
  4972. * @param {Matrix3} matrix - The matrix to test for equality.
  4973. * @return {boolean} Whether this matrix is equal with the given one.
  4974. */
  4975. equals( matrix ) {
  4976. const te = this.elements;
  4977. const me = matrix.elements;
  4978. for ( let i = 0; i < 9; i ++ ) {
  4979. if ( te[ i ] !== me[ i ] ) return false;
  4980. }
  4981. return true;
  4982. }
  4983. /**
  4984. * Sets the elements of the matrix from the given array.
  4985. *
  4986. * @param {Array<number>} array - The matrix elements in column-major order.
  4987. * @param {number} [offset=0] - Index of the first element in the array.
  4988. * @return {Matrix3} A reference to this matrix.
  4989. */
  4990. fromArray( array, offset = 0 ) {
  4991. for ( let i = 0; i < 9; i ++ ) {
  4992. this.elements[ i ] = array[ i + offset ];
  4993. }
  4994. return this;
  4995. }
  4996. /**
  4997. * Writes the elements of this matrix to the given array. If no array is provided,
  4998. * the method returns a new instance.
  4999. *
  5000. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5001. * @param {number} [offset=0] - Index of the first element in the array.
  5002. * @return {Array<number>} The matrix elements in column-major order.
  5003. */
  5004. toArray( array = [], offset = 0 ) {
  5005. const te = this.elements;
  5006. array[ offset ] = te[ 0 ];
  5007. array[ offset + 1 ] = te[ 1 ];
  5008. array[ offset + 2 ] = te[ 2 ];
  5009. array[ offset + 3 ] = te[ 3 ];
  5010. array[ offset + 4 ] = te[ 4 ];
  5011. array[ offset + 5 ] = te[ 5 ];
  5012. array[ offset + 6 ] = te[ 6 ];
  5013. array[ offset + 7 ] = te[ 7 ];
  5014. array[ offset + 8 ] = te[ 8 ];
  5015. return array;
  5016. }
  5017. /**
  5018. * Returns a matrix with copied values from this instance.
  5019. *
  5020. * @return {Matrix3} A clone of this instance.
  5021. */
  5022. clone() {
  5023. return new this.constructor().fromArray( this.elements );
  5024. }
  5025. }
  5026. const _m3 = /*@__PURE__*/ new Matrix3();
  5027. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5028. 0.4123908, 0.3575843, 0.1804808,
  5029. 0.2126390, 0.7151687, 0.0721923,
  5030. 0.0193308, 0.1191948, 0.9505322
  5031. );
  5032. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5033. 3.2409699, -1.5373832, -0.4986108,
  5034. -0.9692436, 1.8759675, 0.0415551,
  5035. 0.0556301, -0.203977, 1.0569715
  5036. );
  5037. function createColorManagement() {
  5038. const ColorManagement = {
  5039. enabled: true,
  5040. workingColorSpace: LinearSRGBColorSpace,
  5041. /**
  5042. * Implementations of supported color spaces.
  5043. *
  5044. * Required:
  5045. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5046. * - whitePoint: reference white [ x y ]
  5047. * - transfer: transfer function (pre-defined)
  5048. * - toXYZ: Matrix3 RGB to XYZ transform
  5049. * - fromXYZ: Matrix3 XYZ to RGB transform
  5050. * - luminanceCoefficients: RGB luminance coefficients
  5051. *
  5052. * Optional:
  5053. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5054. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5055. *
  5056. * Reference:
  5057. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5058. */
  5059. spaces: {},
  5060. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5061. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5062. return color;
  5063. }
  5064. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5065. color.r = SRGBToLinear( color.r );
  5066. color.g = SRGBToLinear( color.g );
  5067. color.b = SRGBToLinear( color.b );
  5068. }
  5069. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5070. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5071. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5072. }
  5073. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5074. color.r = LinearToSRGB( color.r );
  5075. color.g = LinearToSRGB( color.g );
  5076. color.b = LinearToSRGB( color.b );
  5077. }
  5078. return color;
  5079. },
  5080. workingToColorSpace: function ( color, targetColorSpace ) {
  5081. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5082. },
  5083. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5084. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5085. },
  5086. getPrimaries: function ( colorSpace ) {
  5087. return this.spaces[ colorSpace ].primaries;
  5088. },
  5089. getTransfer: function ( colorSpace ) {
  5090. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5091. return this.spaces[ colorSpace ].transfer;
  5092. },
  5093. getToneMappingMode: function ( colorSpace ) {
  5094. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5095. },
  5096. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5097. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5098. },
  5099. define: function ( colorSpaces ) {
  5100. Object.assign( this.spaces, colorSpaces );
  5101. },
  5102. // Internal APIs
  5103. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5104. return targetMatrix
  5105. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5106. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5107. },
  5108. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5109. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5110. },
  5111. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5112. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5113. },
  5114. // Deprecated
  5115. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5116. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5117. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5118. },
  5119. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5120. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5121. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5122. },
  5123. };
  5124. /******************************************************************************
  5125. * sRGB definitions
  5126. */
  5127. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5128. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5129. const D65 = [ 0.3127, 0.3290 ];
  5130. ColorManagement.define( {
  5131. [ LinearSRGBColorSpace ]: {
  5132. primaries: REC709_PRIMARIES,
  5133. whitePoint: D65,
  5134. transfer: LinearTransfer,
  5135. toXYZ: LINEAR_REC709_TO_XYZ,
  5136. fromXYZ: XYZ_TO_LINEAR_REC709,
  5137. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5138. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5139. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5140. },
  5141. [ SRGBColorSpace ]: {
  5142. primaries: REC709_PRIMARIES,
  5143. whitePoint: D65,
  5144. transfer: SRGBTransfer,
  5145. toXYZ: LINEAR_REC709_TO_XYZ,
  5146. fromXYZ: XYZ_TO_LINEAR_REC709,
  5147. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5148. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5149. },
  5150. } );
  5151. return ColorManagement;
  5152. }
  5153. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5154. function SRGBToLinear( c ) {
  5155. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5156. }
  5157. function LinearToSRGB( c ) {
  5158. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5159. }
  5160. let _canvas;
  5161. /**
  5162. * A class containing utility functions for images.
  5163. *
  5164. * @hideconstructor
  5165. */
  5166. class ImageUtils {
  5167. /**
  5168. * Returns a data URI containing a representation of the given image.
  5169. *
  5170. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5171. * @param {string} [type='image/png'] - Indicates the image format.
  5172. * @return {string} The data URI.
  5173. */
  5174. static getDataURL( image, type = 'image/png' ) {
  5175. if ( /^data:/i.test( image.src ) ) {
  5176. return image.src;
  5177. }
  5178. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5179. return image.src;
  5180. }
  5181. let canvas;
  5182. if ( image instanceof HTMLCanvasElement ) {
  5183. canvas = image;
  5184. } else {
  5185. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5186. _canvas.width = image.width;
  5187. _canvas.height = image.height;
  5188. const context = _canvas.getContext( '2d' );
  5189. if ( image instanceof ImageData ) {
  5190. context.putImageData( image, 0, 0 );
  5191. } else {
  5192. context.drawImage( image, 0, 0, image.width, image.height );
  5193. }
  5194. canvas = _canvas;
  5195. }
  5196. return canvas.toDataURL( type );
  5197. }
  5198. /**
  5199. * Converts the given sRGB image data to linear color space.
  5200. *
  5201. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5202. * @return {HTMLCanvasElement|Object} The converted image.
  5203. */
  5204. static sRGBToLinear( image ) {
  5205. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5206. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5207. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5208. const canvas = createElementNS( 'canvas' );
  5209. canvas.width = image.width;
  5210. canvas.height = image.height;
  5211. const context = canvas.getContext( '2d' );
  5212. context.drawImage( image, 0, 0, image.width, image.height );
  5213. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5214. const data = imageData.data;
  5215. for ( let i = 0; i < data.length; i ++ ) {
  5216. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5217. }
  5218. context.putImageData( imageData, 0, 0 );
  5219. return canvas;
  5220. } else if ( image.data ) {
  5221. const data = image.data.slice( 0 );
  5222. for ( let i = 0; i < data.length; i ++ ) {
  5223. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5224. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5225. } else {
  5226. // assuming float
  5227. data[ i ] = SRGBToLinear( data[ i ] );
  5228. }
  5229. }
  5230. return {
  5231. data: data,
  5232. width: image.width,
  5233. height: image.height
  5234. };
  5235. } else {
  5236. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5237. return image;
  5238. }
  5239. }
  5240. }
  5241. let _sourceId = 0;
  5242. /**
  5243. * Represents the data source of a texture.
  5244. *
  5245. * The main purpose of this class is to decouple the data definition from the texture
  5246. * definition so the same data can be used with multiple texture instances.
  5247. */
  5248. class Source {
  5249. /**
  5250. * Constructs a new video texture.
  5251. *
  5252. * @param {any} [data=null] - The data definition of a texture.
  5253. */
  5254. constructor( data = null ) {
  5255. /**
  5256. * This flag can be used for type testing.
  5257. *
  5258. * @type {boolean}
  5259. * @readonly
  5260. * @default true
  5261. */
  5262. this.isSource = true;
  5263. /**
  5264. * The ID of the source.
  5265. *
  5266. * @name Source#id
  5267. * @type {number}
  5268. * @readonly
  5269. */
  5270. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5271. /**
  5272. * The UUID of the source.
  5273. *
  5274. * @type {string}
  5275. * @readonly
  5276. */
  5277. this.uuid = generateUUID();
  5278. /**
  5279. * The data definition of a texture.
  5280. *
  5281. * @type {any}
  5282. */
  5283. this.data = data;
  5284. /**
  5285. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5286. * provides more control on how texture data should be processed. When `dataReady` is set
  5287. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5288. * the data into the GPU memory.
  5289. *
  5290. * @type {boolean}
  5291. * @default true
  5292. */
  5293. this.dataReady = true;
  5294. /**
  5295. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5296. *
  5297. * @type {number}
  5298. * @readonly
  5299. * @default 0
  5300. */
  5301. this.version = 0;
  5302. }
  5303. /**
  5304. * Returns the dimensions of the source into the given target vector.
  5305. *
  5306. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5307. * @return {(Vector2|Vector3)} The dimensions of the source.
  5308. */
  5309. getSize( target ) {
  5310. const data = this.data;
  5311. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5312. target.set( data.videoWidth, data.videoHeight, 0 );
  5313. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5314. target.set( data.displayHeight, data.displayWidth, 0 );
  5315. } else if ( data !== null ) {
  5316. target.set( data.width, data.height, data.depth || 0 );
  5317. } else {
  5318. target.set( 0, 0, 0 );
  5319. }
  5320. return target;
  5321. }
  5322. /**
  5323. * When the property is set to `true`, the engine allocates the memory
  5324. * for the texture (if necessary) and triggers the actual texture upload
  5325. * to the GPU next time the source is used.
  5326. *
  5327. * @type {boolean}
  5328. * @default false
  5329. * @param {boolean} value
  5330. */
  5331. set needsUpdate( value ) {
  5332. if ( value === true ) this.version ++;
  5333. }
  5334. /**
  5335. * Serializes the source into JSON.
  5336. *
  5337. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5338. * @return {Object} A JSON object representing the serialized source.
  5339. * @see {@link ObjectLoader#parse}
  5340. */
  5341. toJSON( meta ) {
  5342. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5343. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5344. return meta.images[ this.uuid ];
  5345. }
  5346. const output = {
  5347. uuid: this.uuid,
  5348. url: ''
  5349. };
  5350. const data = this.data;
  5351. if ( data !== null ) {
  5352. let url;
  5353. if ( Array.isArray( data ) ) {
  5354. // cube texture
  5355. url = [];
  5356. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5357. if ( data[ i ].isDataTexture ) {
  5358. url.push( serializeImage( data[ i ].image ) );
  5359. } else {
  5360. url.push( serializeImage( data[ i ] ) );
  5361. }
  5362. }
  5363. } else {
  5364. // texture
  5365. url = serializeImage( data );
  5366. }
  5367. output.url = url;
  5368. }
  5369. if ( ! isRootObject ) {
  5370. meta.images[ this.uuid ] = output;
  5371. }
  5372. return output;
  5373. }
  5374. }
  5375. function serializeImage( image ) {
  5376. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5377. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5378. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5379. // default images
  5380. return ImageUtils.getDataURL( image );
  5381. } else {
  5382. if ( image.data ) {
  5383. // images of DataTexture
  5384. return {
  5385. data: Array.from( image.data ),
  5386. width: image.width,
  5387. height: image.height,
  5388. type: image.data.constructor.name
  5389. };
  5390. } else {
  5391. warn( 'Texture: Unable to serialize Texture.' );
  5392. return {};
  5393. }
  5394. }
  5395. }
  5396. let _textureId = 0;
  5397. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5398. /**
  5399. * Base class for all textures.
  5400. *
  5401. * Note: After the initial use of a texture, its dimensions, format, and type
  5402. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5403. *
  5404. * @augments EventDispatcher
  5405. */
  5406. class Texture extends EventDispatcher {
  5407. /**
  5408. * Constructs a new texture.
  5409. *
  5410. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5411. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5412. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5413. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5414. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5415. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5416. * @param {number} [format=RGBAFormat] - The texture format.
  5417. * @param {number} [type=UnsignedByteType] - The texture type.
  5418. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5419. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5420. */
  5421. 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 ) {
  5422. super();
  5423. /**
  5424. * This flag can be used for type testing.
  5425. *
  5426. * @type {boolean}
  5427. * @readonly
  5428. * @default true
  5429. */
  5430. this.isTexture = true;
  5431. /**
  5432. * The ID of the texture.
  5433. *
  5434. * @name Texture#id
  5435. * @type {number}
  5436. * @readonly
  5437. */
  5438. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5439. /**
  5440. * The UUID of the texture.
  5441. *
  5442. * @type {string}
  5443. * @readonly
  5444. */
  5445. this.uuid = generateUUID();
  5446. /**
  5447. * The name of the texture.
  5448. *
  5449. * @type {string}
  5450. */
  5451. this.name = '';
  5452. /**
  5453. * The data definition of a texture. A reference to the data source can be
  5454. * shared across textures. This is often useful in context of spritesheets
  5455. * where multiple textures render the same data but with different texture
  5456. * transformations.
  5457. *
  5458. * @type {Source}
  5459. */
  5460. this.source = new Source( image );
  5461. /**
  5462. * An array holding user-defined mipmaps.
  5463. *
  5464. * @type {Array<Object>}
  5465. */
  5466. this.mipmaps = [];
  5467. /**
  5468. * How the texture is applied to the object. The value `UVMapping`
  5469. * is the default, where texture or uv coordinates are used to apply the map.
  5470. *
  5471. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5472. * @default UVMapping
  5473. */
  5474. this.mapping = mapping;
  5475. /**
  5476. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5477. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5478. *
  5479. * @type {number}
  5480. * @default 0
  5481. */
  5482. this.channel = 0;
  5483. /**
  5484. * This defines how the texture is wrapped horizontally and corresponds to
  5485. * *U* in UV mapping.
  5486. *
  5487. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5488. * @default ClampToEdgeWrapping
  5489. */
  5490. this.wrapS = wrapS;
  5491. /**
  5492. * This defines how the texture is wrapped horizontally and corresponds to
  5493. * *V* in UV mapping.
  5494. *
  5495. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5496. * @default ClampToEdgeWrapping
  5497. */
  5498. this.wrapT = wrapT;
  5499. /**
  5500. * How the texture is sampled when a texel covers more than one pixel.
  5501. *
  5502. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5503. * @default LinearFilter
  5504. */
  5505. this.magFilter = magFilter;
  5506. /**
  5507. * How the texture is sampled when a texel covers less than one pixel.
  5508. *
  5509. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5510. * @default LinearMipmapLinearFilter
  5511. */
  5512. this.minFilter = minFilter;
  5513. /**
  5514. * The number of samples taken along the axis through the pixel that has the
  5515. * highest density of texels. By default, this value is `1`. A higher value
  5516. * gives a less blurry result than a basic mipmap, at the cost of more
  5517. * texture samples being used.
  5518. *
  5519. * @type {number}
  5520. * @default Texture.DEFAULT_ANISOTROPY
  5521. */
  5522. this.anisotropy = anisotropy;
  5523. /**
  5524. * The format of the texture.
  5525. *
  5526. * @type {number}
  5527. * @default RGBAFormat
  5528. */
  5529. this.format = format;
  5530. /**
  5531. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5532. * defines how the texture data is going to be stored on the GPU.
  5533. *
  5534. * This property allows to overwrite the default format.
  5535. *
  5536. * @type {?string}
  5537. * @default null
  5538. */
  5539. this.internalFormat = null;
  5540. /**
  5541. * The data type of the texture.
  5542. *
  5543. * @type {number}
  5544. * @default UnsignedByteType
  5545. */
  5546. this.type = type;
  5547. /**
  5548. * How much a single repetition of the texture is offset from the beginning,
  5549. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5550. *
  5551. * @type {Vector2}
  5552. * @default (0,0)
  5553. */
  5554. this.offset = new Vector2( 0, 0 );
  5555. /**
  5556. * How many times the texture is repeated across the surface, in each
  5557. * direction U and V. If repeat is set greater than `1` in either direction,
  5558. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5559. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5560. *
  5561. * @type {Vector2}
  5562. * @default (1,1)
  5563. */
  5564. this.repeat = new Vector2( 1, 1 );
  5565. /**
  5566. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5567. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5568. *
  5569. * @type {Vector2}
  5570. * @default (0,0)
  5571. */
  5572. this.center = new Vector2( 0, 0 );
  5573. /**
  5574. * How much the texture is rotated around the center point, in radians.
  5575. * Positive values are counter-clockwise.
  5576. *
  5577. * @type {number}
  5578. * @default 0
  5579. */
  5580. this.rotation = 0;
  5581. /**
  5582. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5583. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5584. * {@link Texture#rotation}, and {@link Texture#center}.
  5585. *
  5586. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5587. *
  5588. * @type {boolean}
  5589. * @default true
  5590. */
  5591. this.matrixAutoUpdate = true;
  5592. /**
  5593. * The uv-transformation matrix of the texture.
  5594. *
  5595. * @type {Matrix3}
  5596. */
  5597. this.matrix = new Matrix3();
  5598. /**
  5599. * Whether to generate mipmaps (if possible) for a texture.
  5600. *
  5601. * Set this to `false` if you are creating mipmaps manually.
  5602. *
  5603. * @type {boolean}
  5604. * @default true
  5605. */
  5606. this.generateMipmaps = true;
  5607. /**
  5608. * If set to `true`, the alpha channel, if present, is multiplied into the
  5609. * color channels when the texture is uploaded to the GPU.
  5610. *
  5611. * Note that this property has no effect when using `ImageBitmap`. You need to
  5612. * configure premultiply alpha on bitmap creation instead.
  5613. *
  5614. * @type {boolean}
  5615. * @default false
  5616. */
  5617. this.premultiplyAlpha = false;
  5618. /**
  5619. * If set to `true`, the texture is flipped along the vertical axis when
  5620. * uploaded to the GPU.
  5621. *
  5622. * Note that this property has no effect when using `ImageBitmap`. You need to
  5623. * configure the flip on bitmap creation instead.
  5624. *
  5625. * @type {boolean}
  5626. * @default true
  5627. */
  5628. this.flipY = true;
  5629. /**
  5630. * Specifies the alignment requirements for the start of each pixel row in memory.
  5631. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5632. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5633. *
  5634. * @type {number}
  5635. * @default 4
  5636. */
  5637. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5638. /**
  5639. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5640. *
  5641. * @type {string}
  5642. * @default NoColorSpace
  5643. */
  5644. this.colorSpace = colorSpace;
  5645. /**
  5646. * An object that can be used to store custom data about the texture. It
  5647. * should not hold references to functions as these will not be cloned.
  5648. *
  5649. * @type {Object}
  5650. */
  5651. this.userData = {};
  5652. /**
  5653. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5654. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5655. *
  5656. * @type {Array<Object>}
  5657. */
  5658. this.updateRanges = [];
  5659. /**
  5660. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5661. *
  5662. * @type {number}
  5663. * @readonly
  5664. * @default 0
  5665. */
  5666. this.version = 0;
  5667. /**
  5668. * A callback function, called when the texture is updated (e.g., when
  5669. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5670. *
  5671. * @type {?Function}
  5672. * @default null
  5673. */
  5674. this.onUpdate = null;
  5675. /**
  5676. * An optional back reference to the textures render target.
  5677. *
  5678. * @type {?(RenderTarget|WebGLRenderTarget)}
  5679. * @default null
  5680. */
  5681. this.renderTarget = null;
  5682. /**
  5683. * Indicates whether a texture belongs to a render target or not.
  5684. *
  5685. * @type {boolean}
  5686. * @readonly
  5687. * @default false
  5688. */
  5689. this.isRenderTargetTexture = false;
  5690. /**
  5691. * Indicates if a texture should be handled like a texture array.
  5692. *
  5693. * @type {boolean}
  5694. * @readonly
  5695. * @default false
  5696. */
  5697. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5698. /**
  5699. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5700. * (only relevant for render target textures).
  5701. *
  5702. * @type {number}
  5703. * @readonly
  5704. * @default 0
  5705. */
  5706. this.pmremVersion = 0;
  5707. }
  5708. /**
  5709. * The width of the texture in pixels.
  5710. */
  5711. get width() {
  5712. return this.source.getSize( _tempVec3 ).x;
  5713. }
  5714. /**
  5715. * The height of the texture in pixels.
  5716. */
  5717. get height() {
  5718. return this.source.getSize( _tempVec3 ).y;
  5719. }
  5720. /**
  5721. * The depth of the texture in pixels.
  5722. */
  5723. get depth() {
  5724. return this.source.getSize( _tempVec3 ).z;
  5725. }
  5726. /**
  5727. * The image object holding the texture data.
  5728. *
  5729. * @type {?Object}
  5730. */
  5731. get image() {
  5732. return this.source.data;
  5733. }
  5734. set image( value = null ) {
  5735. this.source.data = value;
  5736. }
  5737. /**
  5738. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5739. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5740. */
  5741. updateMatrix() {
  5742. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5743. }
  5744. /**
  5745. * Adds a range of data in the data texture to be updated on the GPU.
  5746. *
  5747. * @param {number} start - Position at which to start update.
  5748. * @param {number} count - The number of components to update.
  5749. */
  5750. addUpdateRange( start, count ) {
  5751. this.updateRanges.push( { start, count } );
  5752. }
  5753. /**
  5754. * Clears the update ranges.
  5755. */
  5756. clearUpdateRanges() {
  5757. this.updateRanges.length = 0;
  5758. }
  5759. /**
  5760. * Returns a new texture with copied values from this instance.
  5761. *
  5762. * @return {Texture} A clone of this instance.
  5763. */
  5764. clone() {
  5765. return new this.constructor().copy( this );
  5766. }
  5767. /**
  5768. * Copies the values of the given texture to this instance.
  5769. *
  5770. * @param {Texture} source - The texture to copy.
  5771. * @return {Texture} A reference to this instance.
  5772. */
  5773. copy( source ) {
  5774. this.name = source.name;
  5775. this.source = source.source;
  5776. this.mipmaps = source.mipmaps.slice( 0 );
  5777. this.mapping = source.mapping;
  5778. this.channel = source.channel;
  5779. this.wrapS = source.wrapS;
  5780. this.wrapT = source.wrapT;
  5781. this.magFilter = source.magFilter;
  5782. this.minFilter = source.minFilter;
  5783. this.anisotropy = source.anisotropy;
  5784. this.format = source.format;
  5785. this.internalFormat = source.internalFormat;
  5786. this.type = source.type;
  5787. this.offset.copy( source.offset );
  5788. this.repeat.copy( source.repeat );
  5789. this.center.copy( source.center );
  5790. this.rotation = source.rotation;
  5791. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5792. this.matrix.copy( source.matrix );
  5793. this.generateMipmaps = source.generateMipmaps;
  5794. this.premultiplyAlpha = source.premultiplyAlpha;
  5795. this.flipY = source.flipY;
  5796. this.unpackAlignment = source.unpackAlignment;
  5797. this.colorSpace = source.colorSpace;
  5798. this.renderTarget = source.renderTarget;
  5799. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5800. this.isArrayTexture = source.isArrayTexture;
  5801. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5802. this.needsUpdate = true;
  5803. return this;
  5804. }
  5805. /**
  5806. * Sets this texture's properties based on `values`.
  5807. * @param {Object} values - A container with texture parameters.
  5808. */
  5809. setValues( values ) {
  5810. for ( const key in values ) {
  5811. const newValue = values[ key ];
  5812. if ( newValue === undefined ) {
  5813. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5814. continue;
  5815. }
  5816. const currentValue = this[ key ];
  5817. if ( currentValue === undefined ) {
  5818. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5819. continue;
  5820. }
  5821. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5822. currentValue.copy( newValue );
  5823. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5824. currentValue.copy( newValue );
  5825. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5826. currentValue.copy( newValue );
  5827. } else {
  5828. this[ key ] = newValue;
  5829. }
  5830. }
  5831. }
  5832. /**
  5833. * Serializes the texture into JSON.
  5834. *
  5835. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5836. * @return {Object} A JSON object representing the serialized texture.
  5837. * @see {@link ObjectLoader#parse}
  5838. */
  5839. toJSON( meta ) {
  5840. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5841. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5842. return meta.textures[ this.uuid ];
  5843. }
  5844. const output = {
  5845. metadata: {
  5846. version: 4.7,
  5847. type: 'Texture',
  5848. generator: 'Texture.toJSON'
  5849. },
  5850. uuid: this.uuid,
  5851. name: this.name,
  5852. image: this.source.toJSON( meta ).uuid,
  5853. mapping: this.mapping,
  5854. channel: this.channel,
  5855. repeat: [ this.repeat.x, this.repeat.y ],
  5856. offset: [ this.offset.x, this.offset.y ],
  5857. center: [ this.center.x, this.center.y ],
  5858. rotation: this.rotation,
  5859. wrap: [ this.wrapS, this.wrapT ],
  5860. format: this.format,
  5861. internalFormat: this.internalFormat,
  5862. type: this.type,
  5863. colorSpace: this.colorSpace,
  5864. minFilter: this.minFilter,
  5865. magFilter: this.magFilter,
  5866. anisotropy: this.anisotropy,
  5867. flipY: this.flipY,
  5868. generateMipmaps: this.generateMipmaps,
  5869. premultiplyAlpha: this.premultiplyAlpha,
  5870. unpackAlignment: this.unpackAlignment
  5871. };
  5872. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5873. if ( ! isRootObject ) {
  5874. meta.textures[ this.uuid ] = output;
  5875. }
  5876. return output;
  5877. }
  5878. /**
  5879. * Frees the GPU-related resources allocated by this instance. Call this
  5880. * method whenever this instance is no longer used in your app.
  5881. *
  5882. * @fires Texture#dispose
  5883. */
  5884. dispose() {
  5885. /**
  5886. * Fires when the texture has been disposed of.
  5887. *
  5888. * @event Texture#dispose
  5889. * @type {Object}
  5890. */
  5891. this.dispatchEvent( { type: 'dispose' } );
  5892. }
  5893. /**
  5894. * Transforms the given uv vector with the textures uv transformation matrix.
  5895. *
  5896. * @param {Vector2} uv - The uv vector.
  5897. * @return {Vector2} The transformed uv vector.
  5898. */
  5899. transformUv( uv ) {
  5900. if ( this.mapping !== UVMapping ) return uv;
  5901. uv.applyMatrix3( this.matrix );
  5902. if ( uv.x < 0 || uv.x > 1 ) {
  5903. switch ( this.wrapS ) {
  5904. case RepeatWrapping:
  5905. uv.x = uv.x - Math.floor( uv.x );
  5906. break;
  5907. case ClampToEdgeWrapping:
  5908. uv.x = uv.x < 0 ? 0 : 1;
  5909. break;
  5910. case MirroredRepeatWrapping:
  5911. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5912. uv.x = Math.ceil( uv.x ) - uv.x;
  5913. } else {
  5914. uv.x = uv.x - Math.floor( uv.x );
  5915. }
  5916. break;
  5917. }
  5918. }
  5919. if ( uv.y < 0 || uv.y > 1 ) {
  5920. switch ( this.wrapT ) {
  5921. case RepeatWrapping:
  5922. uv.y = uv.y - Math.floor( uv.y );
  5923. break;
  5924. case ClampToEdgeWrapping:
  5925. uv.y = uv.y < 0 ? 0 : 1;
  5926. break;
  5927. case MirroredRepeatWrapping:
  5928. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5929. uv.y = Math.ceil( uv.y ) - uv.y;
  5930. } else {
  5931. uv.y = uv.y - Math.floor( uv.y );
  5932. }
  5933. break;
  5934. }
  5935. }
  5936. if ( this.flipY ) {
  5937. uv.y = 1 - uv.y;
  5938. }
  5939. return uv;
  5940. }
  5941. /**
  5942. * Setting this property to `true` indicates the engine the texture
  5943. * must be updated in the next render. This triggers a texture upload
  5944. * to the GPU and ensures correct texture parameter configuration.
  5945. *
  5946. * @type {boolean}
  5947. * @default false
  5948. * @param {boolean} value
  5949. */
  5950. set needsUpdate( value ) {
  5951. if ( value === true ) {
  5952. this.version ++;
  5953. this.source.needsUpdate = true;
  5954. }
  5955. }
  5956. /**
  5957. * Setting this property to `true` indicates the engine the PMREM
  5958. * must be regenerated.
  5959. *
  5960. * @type {boolean}
  5961. * @default false
  5962. * @param {boolean} value
  5963. */
  5964. set needsPMREMUpdate( value ) {
  5965. if ( value === true ) {
  5966. this.pmremVersion ++;
  5967. }
  5968. }
  5969. }
  5970. /**
  5971. * The default image for all textures.
  5972. *
  5973. * @static
  5974. * @type {?Image}
  5975. * @default null
  5976. */
  5977. Texture.DEFAULT_IMAGE = null;
  5978. /**
  5979. * The default mapping for all textures.
  5980. *
  5981. * @static
  5982. * @type {number}
  5983. * @default UVMapping
  5984. */
  5985. Texture.DEFAULT_MAPPING = UVMapping;
  5986. /**
  5987. * The default anisotropy value for all textures.
  5988. *
  5989. * @static
  5990. * @type {number}
  5991. * @default 1
  5992. */
  5993. Texture.DEFAULT_ANISOTROPY = 1;
  5994. /**
  5995. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5996. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5997. *
  5998. * - A point in 4D space.
  5999. * - A direction and length in 4D space. In three.js the length will
  6000. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6001. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6002. * - Any arbitrary ordered quadruplet of numbers.
  6003. *
  6004. * There are other things a 4D vector can be used to represent, however these
  6005. * are the most common uses in *three.js*.
  6006. *
  6007. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6008. * the corresponding order.
  6009. * ```js
  6010. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6011. *
  6012. * //no arguments; will be initialised to (0, 0, 0, 1)
  6013. * const b = new THREE.Vector4( );
  6014. *
  6015. * const d = a.dot( b );
  6016. * ```
  6017. */
  6018. class Vector4 {
  6019. /**
  6020. * Constructs a new 4D vector.
  6021. *
  6022. * @param {number} [x=0] - The x value of this vector.
  6023. * @param {number} [y=0] - The y value of this vector.
  6024. * @param {number} [z=0] - The z value of this vector.
  6025. * @param {number} [w=1] - The w value of this vector.
  6026. */
  6027. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6028. /**
  6029. * This flag can be used for type testing.
  6030. *
  6031. * @type {boolean}
  6032. * @readonly
  6033. * @default true
  6034. */
  6035. Vector4.prototype.isVector4 = true;
  6036. /**
  6037. * The x value of this vector.
  6038. *
  6039. * @type {number}
  6040. */
  6041. this.x = x;
  6042. /**
  6043. * The y value of this vector.
  6044. *
  6045. * @type {number}
  6046. */
  6047. this.y = y;
  6048. /**
  6049. * The z value of this vector.
  6050. *
  6051. * @type {number}
  6052. */
  6053. this.z = z;
  6054. /**
  6055. * The w value of this vector.
  6056. *
  6057. * @type {number}
  6058. */
  6059. this.w = w;
  6060. }
  6061. /**
  6062. * Alias for {@link Vector4#z}.
  6063. *
  6064. * @type {number}
  6065. */
  6066. get width() {
  6067. return this.z;
  6068. }
  6069. set width( value ) {
  6070. this.z = value;
  6071. }
  6072. /**
  6073. * Alias for {@link Vector4#w}.
  6074. *
  6075. * @type {number}
  6076. */
  6077. get height() {
  6078. return this.w;
  6079. }
  6080. set height( value ) {
  6081. this.w = value;
  6082. }
  6083. /**
  6084. * Sets the vector components.
  6085. *
  6086. * @param {number} x - The value of the x component.
  6087. * @param {number} y - The value of the y component.
  6088. * @param {number} z - The value of the z component.
  6089. * @param {number} w - The value of the w component.
  6090. * @return {Vector4} A reference to this vector.
  6091. */
  6092. set( x, y, z, w ) {
  6093. this.x = x;
  6094. this.y = y;
  6095. this.z = z;
  6096. this.w = w;
  6097. return this;
  6098. }
  6099. /**
  6100. * Sets the vector components to the same value.
  6101. *
  6102. * @param {number} scalar - The value to set for all vector components.
  6103. * @return {Vector4} A reference to this vector.
  6104. */
  6105. setScalar( scalar ) {
  6106. this.x = scalar;
  6107. this.y = scalar;
  6108. this.z = scalar;
  6109. this.w = scalar;
  6110. return this;
  6111. }
  6112. /**
  6113. * Sets the vector's x component to the given value
  6114. *
  6115. * @param {number} x - The value to set.
  6116. * @return {Vector4} A reference to this vector.
  6117. */
  6118. setX( x ) {
  6119. this.x = x;
  6120. return this;
  6121. }
  6122. /**
  6123. * Sets the vector's y component to the given value
  6124. *
  6125. * @param {number} y - The value to set.
  6126. * @return {Vector4} A reference to this vector.
  6127. */
  6128. setY( y ) {
  6129. this.y = y;
  6130. return this;
  6131. }
  6132. /**
  6133. * Sets the vector's z component to the given value
  6134. *
  6135. * @param {number} z - The value to set.
  6136. * @return {Vector4} A reference to this vector.
  6137. */
  6138. setZ( z ) {
  6139. this.z = z;
  6140. return this;
  6141. }
  6142. /**
  6143. * Sets the vector's w component to the given value
  6144. *
  6145. * @param {number} w - The value to set.
  6146. * @return {Vector4} A reference to this vector.
  6147. */
  6148. setW( w ) {
  6149. this.w = w;
  6150. return this;
  6151. }
  6152. /**
  6153. * Allows to set a vector component with an index.
  6154. *
  6155. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6156. * `2` equals to z, `3` equals to w.
  6157. * @param {number} value - The value to set.
  6158. * @return {Vector4} A reference to this vector.
  6159. */
  6160. setComponent( index, value ) {
  6161. switch ( index ) {
  6162. case 0: this.x = value; break;
  6163. case 1: this.y = value; break;
  6164. case 2: this.z = value; break;
  6165. case 3: this.w = value; break;
  6166. default: throw new Error( 'index is out of range: ' + index );
  6167. }
  6168. return this;
  6169. }
  6170. /**
  6171. * Returns the value of the vector component which matches the given index.
  6172. *
  6173. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6174. * `2` equals to z, `3` equals to w.
  6175. * @return {number} A vector component value.
  6176. */
  6177. getComponent( index ) {
  6178. switch ( index ) {
  6179. case 0: return this.x;
  6180. case 1: return this.y;
  6181. case 2: return this.z;
  6182. case 3: return this.w;
  6183. default: throw new Error( 'index is out of range: ' + index );
  6184. }
  6185. }
  6186. /**
  6187. * Returns a new vector with copied values from this instance.
  6188. *
  6189. * @return {Vector4} A clone of this instance.
  6190. */
  6191. clone() {
  6192. return new this.constructor( this.x, this.y, this.z, this.w );
  6193. }
  6194. /**
  6195. * Copies the values of the given vector to this instance.
  6196. *
  6197. * @param {Vector3|Vector4} v - The vector to copy.
  6198. * @return {Vector4} A reference to this vector.
  6199. */
  6200. copy( v ) {
  6201. this.x = v.x;
  6202. this.y = v.y;
  6203. this.z = v.z;
  6204. this.w = ( v.w !== undefined ) ? v.w : 1;
  6205. return this;
  6206. }
  6207. /**
  6208. * Adds the given vector to this instance.
  6209. *
  6210. * @param {Vector4} v - The vector to add.
  6211. * @return {Vector4} A reference to this vector.
  6212. */
  6213. add( v ) {
  6214. this.x += v.x;
  6215. this.y += v.y;
  6216. this.z += v.z;
  6217. this.w += v.w;
  6218. return this;
  6219. }
  6220. /**
  6221. * Adds the given scalar value to all components of this instance.
  6222. *
  6223. * @param {number} s - The scalar to add.
  6224. * @return {Vector4} A reference to this vector.
  6225. */
  6226. addScalar( s ) {
  6227. this.x += s;
  6228. this.y += s;
  6229. this.z += s;
  6230. this.w += s;
  6231. return this;
  6232. }
  6233. /**
  6234. * Adds the given vectors and stores the result in this instance.
  6235. *
  6236. * @param {Vector4} a - The first vector.
  6237. * @param {Vector4} b - The second vector.
  6238. * @return {Vector4} A reference to this vector.
  6239. */
  6240. addVectors( a, b ) {
  6241. this.x = a.x + b.x;
  6242. this.y = a.y + b.y;
  6243. this.z = a.z + b.z;
  6244. this.w = a.w + b.w;
  6245. return this;
  6246. }
  6247. /**
  6248. * Adds the given vector scaled by the given factor to this instance.
  6249. *
  6250. * @param {Vector4} v - The vector.
  6251. * @param {number} s - The factor that scales `v`.
  6252. * @return {Vector4} A reference to this vector.
  6253. */
  6254. addScaledVector( v, s ) {
  6255. this.x += v.x * s;
  6256. this.y += v.y * s;
  6257. this.z += v.z * s;
  6258. this.w += v.w * s;
  6259. return this;
  6260. }
  6261. /**
  6262. * Subtracts the given vector from this instance.
  6263. *
  6264. * @param {Vector4} v - The vector to subtract.
  6265. * @return {Vector4} A reference to this vector.
  6266. */
  6267. sub( v ) {
  6268. this.x -= v.x;
  6269. this.y -= v.y;
  6270. this.z -= v.z;
  6271. this.w -= v.w;
  6272. return this;
  6273. }
  6274. /**
  6275. * Subtracts the given scalar value from all components of this instance.
  6276. *
  6277. * @param {number} s - The scalar to subtract.
  6278. * @return {Vector4} A reference to this vector.
  6279. */
  6280. subScalar( s ) {
  6281. this.x -= s;
  6282. this.y -= s;
  6283. this.z -= s;
  6284. this.w -= s;
  6285. return this;
  6286. }
  6287. /**
  6288. * Subtracts the given vectors and stores the result in this instance.
  6289. *
  6290. * @param {Vector4} a - The first vector.
  6291. * @param {Vector4} b - The second vector.
  6292. * @return {Vector4} A reference to this vector.
  6293. */
  6294. subVectors( a, b ) {
  6295. this.x = a.x - b.x;
  6296. this.y = a.y - b.y;
  6297. this.z = a.z - b.z;
  6298. this.w = a.w - b.w;
  6299. return this;
  6300. }
  6301. /**
  6302. * Multiplies the given vector with this instance.
  6303. *
  6304. * @param {Vector4} v - The vector to multiply.
  6305. * @return {Vector4} A reference to this vector.
  6306. */
  6307. multiply( v ) {
  6308. this.x *= v.x;
  6309. this.y *= v.y;
  6310. this.z *= v.z;
  6311. this.w *= v.w;
  6312. return this;
  6313. }
  6314. /**
  6315. * Multiplies the given scalar value with all components of this instance.
  6316. *
  6317. * @param {number} scalar - The scalar to multiply.
  6318. * @return {Vector4} A reference to this vector.
  6319. */
  6320. multiplyScalar( scalar ) {
  6321. this.x *= scalar;
  6322. this.y *= scalar;
  6323. this.z *= scalar;
  6324. this.w *= scalar;
  6325. return this;
  6326. }
  6327. /**
  6328. * Multiplies this vector with the given 4x4 matrix.
  6329. *
  6330. * @param {Matrix4} m - The 4x4 matrix.
  6331. * @return {Vector4} A reference to this vector.
  6332. */
  6333. applyMatrix4( m ) {
  6334. const x = this.x, y = this.y, z = this.z, w = this.w;
  6335. const e = m.elements;
  6336. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6337. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6338. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6339. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6340. return this;
  6341. }
  6342. /**
  6343. * Divides this instance by the given vector.
  6344. *
  6345. * @param {Vector4} v - The vector to divide.
  6346. * @return {Vector4} A reference to this vector.
  6347. */
  6348. divide( v ) {
  6349. this.x /= v.x;
  6350. this.y /= v.y;
  6351. this.z /= v.z;
  6352. this.w /= v.w;
  6353. return this;
  6354. }
  6355. /**
  6356. * Divides this vector by the given scalar.
  6357. *
  6358. * @param {number} scalar - The scalar to divide.
  6359. * @return {Vector4} A reference to this vector.
  6360. */
  6361. divideScalar( scalar ) {
  6362. return this.multiplyScalar( 1 / scalar );
  6363. }
  6364. /**
  6365. * Sets the x, y and z components of this
  6366. * vector to the quaternion's axis and w to the angle.
  6367. *
  6368. * @param {Quaternion} q - The Quaternion to set.
  6369. * @return {Vector4} A reference to this vector.
  6370. */
  6371. setAxisAngleFromQuaternion( q ) {
  6372. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6373. // q is assumed to be normalized
  6374. this.w = 2 * Math.acos( q.w );
  6375. const s = Math.sqrt( 1 - q.w * q.w );
  6376. if ( s < 0.0001 ) {
  6377. this.x = 1;
  6378. this.y = 0;
  6379. this.z = 0;
  6380. } else {
  6381. this.x = q.x / s;
  6382. this.y = q.y / s;
  6383. this.z = q.z / s;
  6384. }
  6385. return this;
  6386. }
  6387. /**
  6388. * Sets the x, y and z components of this
  6389. * vector to the axis of rotation and w to the angle.
  6390. *
  6391. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6392. * @return {Vector4} A reference to this vector.
  6393. */
  6394. setAxisAngleFromRotationMatrix( m ) {
  6395. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6396. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6397. let angle, x, y, z; // variables for result
  6398. const epsilon = 0.01, // margin to allow for rounding errors
  6399. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6400. te = m.elements,
  6401. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6402. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6403. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6404. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6405. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6406. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6407. // singularity found
  6408. // first check for identity matrix which must have +1 for all terms
  6409. // in leading diagonal and zero in other terms
  6410. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6411. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6412. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6413. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6414. // this singularity is identity matrix so angle = 0
  6415. this.set( 1, 0, 0, 0 );
  6416. return this; // zero angle, arbitrary axis
  6417. }
  6418. // otherwise this singularity is angle = 180
  6419. angle = Math.PI;
  6420. const xx = ( m11 + 1 ) / 2;
  6421. const yy = ( m22 + 1 ) / 2;
  6422. const zz = ( m33 + 1 ) / 2;
  6423. const xy = ( m12 + m21 ) / 4;
  6424. const xz = ( m13 + m31 ) / 4;
  6425. const yz = ( m23 + m32 ) / 4;
  6426. if ( ( xx > yy ) && ( xx > zz ) ) {
  6427. // m11 is the largest diagonal term
  6428. if ( xx < epsilon ) {
  6429. x = 0;
  6430. y = 0.707106781;
  6431. z = 0.707106781;
  6432. } else {
  6433. x = Math.sqrt( xx );
  6434. y = xy / x;
  6435. z = xz / x;
  6436. }
  6437. } else if ( yy > zz ) {
  6438. // m22 is the largest diagonal term
  6439. if ( yy < epsilon ) {
  6440. x = 0.707106781;
  6441. y = 0;
  6442. z = 0.707106781;
  6443. } else {
  6444. y = Math.sqrt( yy );
  6445. x = xy / y;
  6446. z = yz / y;
  6447. }
  6448. } else {
  6449. // m33 is the largest diagonal term so base result on this
  6450. if ( zz < epsilon ) {
  6451. x = 0.707106781;
  6452. y = 0.707106781;
  6453. z = 0;
  6454. } else {
  6455. z = Math.sqrt( zz );
  6456. x = xz / z;
  6457. y = yz / z;
  6458. }
  6459. }
  6460. this.set( x, y, z, angle );
  6461. return this; // return 180 deg rotation
  6462. }
  6463. // as we have reached here there are no singularities so we can handle normally
  6464. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6465. ( m13 - m31 ) * ( m13 - m31 ) +
  6466. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6467. if ( Math.abs( s ) < 0.001 ) s = 1;
  6468. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6469. // caught by singularity test above, but I've left it in just in case
  6470. this.x = ( m32 - m23 ) / s;
  6471. this.y = ( m13 - m31 ) / s;
  6472. this.z = ( m21 - m12 ) / s;
  6473. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6474. return this;
  6475. }
  6476. /**
  6477. * Sets the vector components to the position elements of the
  6478. * given transformation matrix.
  6479. *
  6480. * @param {Matrix4} m - The 4x4 matrix.
  6481. * @return {Vector4} A reference to this vector.
  6482. */
  6483. setFromMatrixPosition( m ) {
  6484. const e = m.elements;
  6485. this.x = e[ 12 ];
  6486. this.y = e[ 13 ];
  6487. this.z = e[ 14 ];
  6488. this.w = e[ 15 ];
  6489. return this;
  6490. }
  6491. /**
  6492. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6493. * value, replace that value with the corresponding min value.
  6494. *
  6495. * @param {Vector4} v - The vector.
  6496. * @return {Vector4} A reference to this vector.
  6497. */
  6498. min( v ) {
  6499. this.x = Math.min( this.x, v.x );
  6500. this.y = Math.min( this.y, v.y );
  6501. this.z = Math.min( this.z, v.z );
  6502. this.w = Math.min( this.w, v.w );
  6503. return this;
  6504. }
  6505. /**
  6506. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6507. * value, replace that value with the corresponding max value.
  6508. *
  6509. * @param {Vector4} v - The vector.
  6510. * @return {Vector4} A reference to this vector.
  6511. */
  6512. max( v ) {
  6513. this.x = Math.max( this.x, v.x );
  6514. this.y = Math.max( this.y, v.y );
  6515. this.z = Math.max( this.z, v.z );
  6516. this.w = Math.max( this.w, v.w );
  6517. return this;
  6518. }
  6519. /**
  6520. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6521. * value, it is replaced by the corresponding value.
  6522. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6523. * it is replaced by the corresponding value.
  6524. *
  6525. * @param {Vector4} min - The minimum x, y and z values.
  6526. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6527. * @return {Vector4} A reference to this vector.
  6528. */
  6529. clamp( min, max ) {
  6530. // assumes min < max, componentwise
  6531. this.x = clamp( this.x, min.x, max.x );
  6532. this.y = clamp( this.y, min.y, max.y );
  6533. this.z = clamp( this.z, min.z, max.z );
  6534. this.w = clamp( this.w, min.w, max.w );
  6535. return this;
  6536. }
  6537. /**
  6538. * If this vector's x, y, z or w values are greater than the max value, they are
  6539. * replaced by the max value.
  6540. * If this vector's x, y, z or w values are less than the min value, they are
  6541. * replaced by the min value.
  6542. *
  6543. * @param {number} minVal - The minimum value the components will be clamped to.
  6544. * @param {number} maxVal - The maximum value the components will be clamped to.
  6545. * @return {Vector4} A reference to this vector.
  6546. */
  6547. clampScalar( minVal, maxVal ) {
  6548. this.x = clamp( this.x, minVal, maxVal );
  6549. this.y = clamp( this.y, minVal, maxVal );
  6550. this.z = clamp( this.z, minVal, maxVal );
  6551. this.w = clamp( this.w, minVal, maxVal );
  6552. return this;
  6553. }
  6554. /**
  6555. * If this vector's length is greater than the max value, it is replaced by
  6556. * the max value.
  6557. * If this vector's length is less than the min value, it is replaced by the
  6558. * min value.
  6559. *
  6560. * @param {number} min - The minimum value the vector length will be clamped to.
  6561. * @param {number} max - The maximum value the vector length will be clamped to.
  6562. * @return {Vector4} A reference to this vector.
  6563. */
  6564. clampLength( min, max ) {
  6565. const length = this.length();
  6566. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6567. }
  6568. /**
  6569. * The components of this vector are rounded down to the nearest integer value.
  6570. *
  6571. * @return {Vector4} A reference to this vector.
  6572. */
  6573. floor() {
  6574. this.x = Math.floor( this.x );
  6575. this.y = Math.floor( this.y );
  6576. this.z = Math.floor( this.z );
  6577. this.w = Math.floor( this.w );
  6578. return this;
  6579. }
  6580. /**
  6581. * The components of this vector are rounded up to the nearest integer value.
  6582. *
  6583. * @return {Vector4} A reference to this vector.
  6584. */
  6585. ceil() {
  6586. this.x = Math.ceil( this.x );
  6587. this.y = Math.ceil( this.y );
  6588. this.z = Math.ceil( this.z );
  6589. this.w = Math.ceil( this.w );
  6590. return this;
  6591. }
  6592. /**
  6593. * The components of this vector are rounded to the nearest integer value
  6594. *
  6595. * @return {Vector4} A reference to this vector.
  6596. */
  6597. round() {
  6598. this.x = Math.round( this.x );
  6599. this.y = Math.round( this.y );
  6600. this.z = Math.round( this.z );
  6601. this.w = Math.round( this.w );
  6602. return this;
  6603. }
  6604. /**
  6605. * The components of this vector are rounded towards zero (up if negative,
  6606. * down if positive) to an integer value.
  6607. *
  6608. * @return {Vector4} A reference to this vector.
  6609. */
  6610. roundToZero() {
  6611. this.x = Math.trunc( this.x );
  6612. this.y = Math.trunc( this.y );
  6613. this.z = Math.trunc( this.z );
  6614. this.w = Math.trunc( this.w );
  6615. return this;
  6616. }
  6617. /**
  6618. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6619. *
  6620. * @return {Vector4} A reference to this vector.
  6621. */
  6622. negate() {
  6623. this.x = - this.x;
  6624. this.y = - this.y;
  6625. this.z = - this.z;
  6626. this.w = - this.w;
  6627. return this;
  6628. }
  6629. /**
  6630. * Calculates the dot product of the given vector with this instance.
  6631. *
  6632. * @param {Vector4} v - The vector to compute the dot product with.
  6633. * @return {number} The result of the dot product.
  6634. */
  6635. dot( v ) {
  6636. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6637. }
  6638. /**
  6639. * Computes the square of the Euclidean length (straight-line length) from
  6640. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6641. * compare the length squared instead as it is slightly more efficient to calculate.
  6642. *
  6643. * @return {number} The square length of this vector.
  6644. */
  6645. lengthSq() {
  6646. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6647. }
  6648. /**
  6649. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6650. *
  6651. * @return {number} The length of this vector.
  6652. */
  6653. length() {
  6654. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6655. }
  6656. /**
  6657. * Computes the Manhattan length of this vector.
  6658. *
  6659. * @return {number} The length of this vector.
  6660. */
  6661. manhattanLength() {
  6662. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6663. }
  6664. /**
  6665. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6666. * with the same direction as this one, but with a vector length of `1`.
  6667. *
  6668. * @return {Vector4} A reference to this vector.
  6669. */
  6670. normalize() {
  6671. return this.divideScalar( this.length() || 1 );
  6672. }
  6673. /**
  6674. * Sets this vector to a vector with the same direction as this one, but
  6675. * with the specified length.
  6676. *
  6677. * @param {number} length - The new length of this vector.
  6678. * @return {Vector4} A reference to this vector.
  6679. */
  6680. setLength( length ) {
  6681. return this.normalize().multiplyScalar( length );
  6682. }
  6683. /**
  6684. * Linearly interpolates between the given vector and this instance, where
  6685. * alpha is the percent distance along the line - alpha = 0 will be this
  6686. * vector, and alpha = 1 will be the given one.
  6687. *
  6688. * @param {Vector4} v - The vector to interpolate towards.
  6689. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6690. * @return {Vector4} A reference to this vector.
  6691. */
  6692. lerp( v, alpha ) {
  6693. this.x += ( v.x - this.x ) * alpha;
  6694. this.y += ( v.y - this.y ) * alpha;
  6695. this.z += ( v.z - this.z ) * alpha;
  6696. this.w += ( v.w - this.w ) * alpha;
  6697. return this;
  6698. }
  6699. /**
  6700. * Linearly interpolates between the given vectors, where alpha is the percent
  6701. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6702. * be the second one. The result is stored in this instance.
  6703. *
  6704. * @param {Vector4} v1 - The first vector.
  6705. * @param {Vector4} v2 - The second vector.
  6706. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6707. * @return {Vector4} A reference to this vector.
  6708. */
  6709. lerpVectors( v1, v2, alpha ) {
  6710. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6711. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6712. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6713. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6714. return this;
  6715. }
  6716. /**
  6717. * Returns `true` if this vector is equal with the given one.
  6718. *
  6719. * @param {Vector4} v - The vector to test for equality.
  6720. * @return {boolean} Whether this vector is equal with the given one.
  6721. */
  6722. equals( v ) {
  6723. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6724. }
  6725. /**
  6726. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6727. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6728. *
  6729. * @param {Array<number>} array - An array holding the vector component values.
  6730. * @param {number} [offset=0] - The offset into the array.
  6731. * @return {Vector4} A reference to this vector.
  6732. */
  6733. fromArray( array, offset = 0 ) {
  6734. this.x = array[ offset ];
  6735. this.y = array[ offset + 1 ];
  6736. this.z = array[ offset + 2 ];
  6737. this.w = array[ offset + 3 ];
  6738. return this;
  6739. }
  6740. /**
  6741. * Writes the components of this vector to the given array. If no array is provided,
  6742. * the method returns a new instance.
  6743. *
  6744. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6745. * @param {number} [offset=0] - Index of the first element in the array.
  6746. * @return {Array<number>} The vector components.
  6747. */
  6748. toArray( array = [], offset = 0 ) {
  6749. array[ offset ] = this.x;
  6750. array[ offset + 1 ] = this.y;
  6751. array[ offset + 2 ] = this.z;
  6752. array[ offset + 3 ] = this.w;
  6753. return array;
  6754. }
  6755. /**
  6756. * Sets the components of this vector from the given buffer attribute.
  6757. *
  6758. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6759. * @param {number} index - The index into the attribute.
  6760. * @return {Vector4} A reference to this vector.
  6761. */
  6762. fromBufferAttribute( attribute, index ) {
  6763. this.x = attribute.getX( index );
  6764. this.y = attribute.getY( index );
  6765. this.z = attribute.getZ( index );
  6766. this.w = attribute.getW( index );
  6767. return this;
  6768. }
  6769. /**
  6770. * Sets each component of this vector to a pseudo-random value between `0` and
  6771. * `1`, excluding `1`.
  6772. *
  6773. * @return {Vector4} A reference to this vector.
  6774. */
  6775. random() {
  6776. this.x = Math.random();
  6777. this.y = Math.random();
  6778. this.z = Math.random();
  6779. this.w = Math.random();
  6780. return this;
  6781. }
  6782. *[ Symbol.iterator ]() {
  6783. yield this.x;
  6784. yield this.y;
  6785. yield this.z;
  6786. yield this.w;
  6787. }
  6788. }
  6789. /**
  6790. * A render target is a buffer where the video card draws pixels for a scene
  6791. * that is being rendered in the background. It is used in different effects,
  6792. * such as applying postprocessing to a rendered image before displaying it
  6793. * on the screen.
  6794. *
  6795. * @augments EventDispatcher
  6796. */
  6797. class RenderTarget extends EventDispatcher {
  6798. /**
  6799. * Render target options.
  6800. *
  6801. * @typedef {Object} RenderTarget~Options
  6802. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6803. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6804. * @property {number} [minFilter=LinearFilter] - The min filter.
  6805. * @property {number} [format=RGBAFormat] - The texture format.
  6806. * @property {number} [type=UnsignedByteType] - The texture type.
  6807. * @property {?string} [internalFormat=null] - The texture's internal format.
  6808. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6809. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6810. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6811. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6812. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6813. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6814. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6815. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6816. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6817. * @property {number} [samples=0] - The MSAA samples count.
  6818. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6819. * @property {number} [depth=1] - The texture depth.
  6820. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6821. */
  6822. /**
  6823. * Constructs a new render target.
  6824. *
  6825. * @param {number} [width=1] - The width of the render target.
  6826. * @param {number} [height=1] - The height of the render target.
  6827. * @param {RenderTarget~Options} [options] - The configuration object.
  6828. */
  6829. constructor( width = 1, height = 1, options = {} ) {
  6830. super();
  6831. options = Object.assign( {
  6832. generateMipmaps: false,
  6833. internalFormat: null,
  6834. minFilter: LinearFilter,
  6835. depthBuffer: true,
  6836. stencilBuffer: false,
  6837. resolveDepthBuffer: true,
  6838. resolveStencilBuffer: true,
  6839. depthTexture: null,
  6840. samples: 0,
  6841. count: 1,
  6842. depth: 1,
  6843. multiview: false
  6844. }, options );
  6845. /**
  6846. * This flag can be used for type testing.
  6847. *
  6848. * @type {boolean}
  6849. * @readonly
  6850. * @default true
  6851. */
  6852. this.isRenderTarget = true;
  6853. /**
  6854. * The width of the render target.
  6855. *
  6856. * @type {number}
  6857. * @default 1
  6858. */
  6859. this.width = width;
  6860. /**
  6861. * The height of the render target.
  6862. *
  6863. * @type {number}
  6864. * @default 1
  6865. */
  6866. this.height = height;
  6867. /**
  6868. * The depth of the render target.
  6869. *
  6870. * @type {number}
  6871. * @default 1
  6872. */
  6873. this.depth = options.depth;
  6874. /**
  6875. * A rectangular area inside the render target's viewport. Fragments that are
  6876. * outside the area will be discarded.
  6877. *
  6878. * @type {Vector4}
  6879. * @default (0,0,width,height)
  6880. */
  6881. this.scissor = new Vector4( 0, 0, width, height );
  6882. /**
  6883. * Indicates whether the scissor test should be enabled when rendering into
  6884. * this render target or not.
  6885. *
  6886. * @type {boolean}
  6887. * @default false
  6888. */
  6889. this.scissorTest = false;
  6890. /**
  6891. * A rectangular area representing the render target's viewport.
  6892. *
  6893. * @type {Vector4}
  6894. * @default (0,0,width,height)
  6895. */
  6896. this.viewport = new Vector4( 0, 0, width, height );
  6897. const image = { width: width, height: height, depth: options.depth };
  6898. const texture = new Texture( image );
  6899. /**
  6900. * An array of textures. Each color attachment is represented as a separate texture.
  6901. * Has at least a single entry for the default color attachment.
  6902. *
  6903. * @type {Array<Texture>}
  6904. */
  6905. this.textures = [];
  6906. const count = options.count;
  6907. for ( let i = 0; i < count; i ++ ) {
  6908. this.textures[ i ] = texture.clone();
  6909. this.textures[ i ].isRenderTargetTexture = true;
  6910. this.textures[ i ].renderTarget = this;
  6911. }
  6912. this._setTextureOptions( options );
  6913. /**
  6914. * Whether to allocate a depth buffer or not.
  6915. *
  6916. * @type {boolean}
  6917. * @default true
  6918. */
  6919. this.depthBuffer = options.depthBuffer;
  6920. /**
  6921. * Whether to allocate a stencil buffer or not.
  6922. *
  6923. * @type {boolean}
  6924. * @default false
  6925. */
  6926. this.stencilBuffer = options.stencilBuffer;
  6927. /**
  6928. * Whether to resolve the depth buffer or not.
  6929. *
  6930. * @type {boolean}
  6931. * @default true
  6932. */
  6933. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6934. /**
  6935. * Whether to resolve the stencil buffer or not.
  6936. *
  6937. * @type {boolean}
  6938. * @default true
  6939. */
  6940. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6941. this._depthTexture = null;
  6942. this.depthTexture = options.depthTexture;
  6943. /**
  6944. * The number of MSAA samples.
  6945. *
  6946. * A value of `0` disables MSAA.
  6947. *
  6948. * @type {number}
  6949. * @default 0
  6950. */
  6951. this.samples = options.samples;
  6952. /**
  6953. * Whether to this target is used in multiview rendering.
  6954. *
  6955. * @type {boolean}
  6956. * @default false
  6957. */
  6958. this.multiview = options.multiview;
  6959. }
  6960. _setTextureOptions( options = {} ) {
  6961. const values = {
  6962. minFilter: LinearFilter,
  6963. generateMipmaps: false,
  6964. flipY: false,
  6965. internalFormat: null
  6966. };
  6967. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6968. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6969. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6970. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6971. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6972. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6973. if ( options.format !== undefined ) values.format = options.format;
  6974. if ( options.type !== undefined ) values.type = options.type;
  6975. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6976. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6977. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6978. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6979. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6980. for ( let i = 0; i < this.textures.length; i ++ ) {
  6981. const texture = this.textures[ i ];
  6982. texture.setValues( values );
  6983. }
  6984. }
  6985. /**
  6986. * The texture representing the default color attachment.
  6987. *
  6988. * @type {Texture}
  6989. */
  6990. get texture() {
  6991. return this.textures[ 0 ];
  6992. }
  6993. set texture( value ) {
  6994. this.textures[ 0 ] = value;
  6995. }
  6996. set depthTexture( current ) {
  6997. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6998. if ( current !== null ) current.renderTarget = this;
  6999. this._depthTexture = current;
  7000. }
  7001. /**
  7002. * Instead of saving the depth in a renderbuffer, a texture
  7003. * can be used instead which is useful for further processing
  7004. * e.g. in context of post-processing.
  7005. *
  7006. * @type {?DepthTexture}
  7007. * @default null
  7008. */
  7009. get depthTexture() {
  7010. return this._depthTexture;
  7011. }
  7012. /**
  7013. * Sets the size of this render target.
  7014. *
  7015. * @param {number} width - The width.
  7016. * @param {number} height - The height.
  7017. * @param {number} [depth=1] - The depth.
  7018. */
  7019. setSize( width, height, depth = 1 ) {
  7020. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7021. this.width = width;
  7022. this.height = height;
  7023. this.depth = depth;
  7024. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7025. this.textures[ i ].image.width = width;
  7026. this.textures[ i ].image.height = height;
  7027. this.textures[ i ].image.depth = depth;
  7028. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7029. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7030. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7031. // both are evaluated on each call?
  7032. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7033. }
  7034. }
  7035. this.dispose();
  7036. }
  7037. this.viewport.set( 0, 0, width, height );
  7038. this.scissor.set( 0, 0, width, height );
  7039. }
  7040. /**
  7041. * Returns a new render target with copied values from this instance.
  7042. *
  7043. * @return {RenderTarget} A clone of this instance.
  7044. */
  7045. clone() {
  7046. return new this.constructor().copy( this );
  7047. }
  7048. /**
  7049. * Copies the settings of the given render target. This is a structural copy so
  7050. * no resources are shared between render targets after the copy. That includes
  7051. * all MRT textures and the depth texture.
  7052. *
  7053. * @param {RenderTarget} source - The render target to copy.
  7054. * @return {RenderTarget} A reference to this instance.
  7055. */
  7056. copy( source ) {
  7057. this.width = source.width;
  7058. this.height = source.height;
  7059. this.depth = source.depth;
  7060. this.scissor.copy( source.scissor );
  7061. this.scissorTest = source.scissorTest;
  7062. this.viewport.copy( source.viewport );
  7063. this.textures.length = 0;
  7064. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7065. this.textures[ i ] = source.textures[ i ].clone();
  7066. this.textures[ i ].isRenderTargetTexture = true;
  7067. this.textures[ i ].renderTarget = this;
  7068. // ensure image object is not shared, see #20328
  7069. const image = Object.assign( {}, source.textures[ i ].image );
  7070. this.textures[ i ].source = new Source( image );
  7071. }
  7072. this.depthBuffer = source.depthBuffer;
  7073. this.stencilBuffer = source.stencilBuffer;
  7074. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7075. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7076. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7077. this.samples = source.samples;
  7078. return this;
  7079. }
  7080. /**
  7081. * Frees the GPU-related resources allocated by this instance. Call this
  7082. * method whenever this instance is no longer used in your app.
  7083. *
  7084. * @fires RenderTarget#dispose
  7085. */
  7086. dispose() {
  7087. this.dispatchEvent( { type: 'dispose' } );
  7088. }
  7089. }
  7090. /**
  7091. * A render target used in context of {@link WebGLRenderer}.
  7092. *
  7093. * @augments RenderTarget
  7094. */
  7095. class WebGLRenderTarget extends RenderTarget {
  7096. /**
  7097. * Constructs a new 3D render target.
  7098. *
  7099. * @param {number} [width=1] - The width of the render target.
  7100. * @param {number} [height=1] - The height of the render target.
  7101. * @param {RenderTarget~Options} [options] - The configuration object.
  7102. */
  7103. constructor( width = 1, height = 1, options = {} ) {
  7104. super( width, height, options );
  7105. /**
  7106. * This flag can be used for type testing.
  7107. *
  7108. * @type {boolean}
  7109. * @readonly
  7110. * @default true
  7111. */
  7112. this.isWebGLRenderTarget = true;
  7113. }
  7114. }
  7115. /**
  7116. * Creates an array of textures directly from raw buffer data.
  7117. *
  7118. * @augments Texture
  7119. */
  7120. class DataArrayTexture extends Texture {
  7121. /**
  7122. * Constructs a new data array texture.
  7123. *
  7124. * @param {?TypedArray} [data=null] - The buffer data.
  7125. * @param {number} [width=1] - The width of the texture.
  7126. * @param {number} [height=1] - The height of the texture.
  7127. * @param {number} [depth=1] - The depth of the texture.
  7128. */
  7129. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7130. super( null );
  7131. /**
  7132. * This flag can be used for type testing.
  7133. *
  7134. * @type {boolean}
  7135. * @readonly
  7136. * @default true
  7137. */
  7138. this.isDataArrayTexture = true;
  7139. /**
  7140. * The image definition of a data texture.
  7141. *
  7142. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7143. */
  7144. this.image = { data, width, height, depth };
  7145. /**
  7146. * How the texture is sampled when a texel covers more than one pixel.
  7147. *
  7148. * Overwritten and set to `NearestFilter` by default.
  7149. *
  7150. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7151. * @default NearestFilter
  7152. */
  7153. this.magFilter = NearestFilter;
  7154. /**
  7155. * How the texture is sampled when a texel covers less than one pixel.
  7156. *
  7157. * Overwritten and set to `NearestFilter` by default.
  7158. *
  7159. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7160. * @default NearestFilter
  7161. */
  7162. this.minFilter = NearestFilter;
  7163. /**
  7164. * This defines how the texture is wrapped in the depth and corresponds to
  7165. * *W* in UVW mapping.
  7166. *
  7167. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7168. * @default ClampToEdgeWrapping
  7169. */
  7170. this.wrapR = ClampToEdgeWrapping;
  7171. /**
  7172. * Whether to generate mipmaps (if possible) for a texture.
  7173. *
  7174. * Overwritten and set to `false` by default.
  7175. *
  7176. * @type {boolean}
  7177. * @default false
  7178. */
  7179. this.generateMipmaps = false;
  7180. /**
  7181. * If set to `true`, the texture is flipped along the vertical axis when
  7182. * uploaded to the GPU.
  7183. *
  7184. * Overwritten and set to `false` by default.
  7185. *
  7186. * @type {boolean}
  7187. * @default false
  7188. */
  7189. this.flipY = false;
  7190. /**
  7191. * Specifies the alignment requirements for the start of each pixel row in memory.
  7192. *
  7193. * Overwritten and set to `1` by default.
  7194. *
  7195. * @type {boolean}
  7196. * @default 1
  7197. */
  7198. this.unpackAlignment = 1;
  7199. /**
  7200. * A set of all layers which need to be updated in the texture.
  7201. *
  7202. * @type {Set<number>}
  7203. */
  7204. this.layerUpdates = new Set();
  7205. }
  7206. /**
  7207. * Describes that a specific layer of the texture needs to be updated.
  7208. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7209. * entire data texture array is sent to the GPU. Marking specific
  7210. * layers will only transmit subsets of all mipmaps associated with a
  7211. * specific depth in the array which is often much more performant.
  7212. *
  7213. * @param {number} layerIndex - The layer index that should be updated.
  7214. */
  7215. addLayerUpdate( layerIndex ) {
  7216. this.layerUpdates.add( layerIndex );
  7217. }
  7218. /**
  7219. * Resets the layer updates registry.
  7220. */
  7221. clearLayerUpdates() {
  7222. this.layerUpdates.clear();
  7223. }
  7224. }
  7225. /**
  7226. * An array render target used in context of {@link WebGLRenderer}.
  7227. *
  7228. * @augments WebGLRenderTarget
  7229. */
  7230. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7231. /**
  7232. * Constructs a new array render target.
  7233. *
  7234. * @param {number} [width=1] - The width of the render target.
  7235. * @param {number} [height=1] - The height of the render target.
  7236. * @param {number} [depth=1] - The height of the render target.
  7237. * @param {RenderTarget~Options} [options] - The configuration object.
  7238. */
  7239. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7240. super( width, height, options );
  7241. /**
  7242. * This flag can be used for type testing.
  7243. *
  7244. * @type {boolean}
  7245. * @readonly
  7246. * @default true
  7247. */
  7248. this.isWebGLArrayRenderTarget = true;
  7249. this.depth = depth;
  7250. /**
  7251. * Overwritten with a different texture type.
  7252. *
  7253. * @type {DataArrayTexture}
  7254. */
  7255. this.texture = new DataArrayTexture( null, width, height, depth );
  7256. this._setTextureOptions( options );
  7257. this.texture.isRenderTargetTexture = true;
  7258. }
  7259. }
  7260. /**
  7261. * Creates a three-dimensional texture from raw data, with parameters to
  7262. * divide it into width, height, and depth.
  7263. *
  7264. * @augments Texture
  7265. */
  7266. class Data3DTexture extends Texture {
  7267. /**
  7268. * Constructs a new data array texture.
  7269. *
  7270. * @param {?TypedArray} [data=null] - The buffer data.
  7271. * @param {number} [width=1] - The width of the texture.
  7272. * @param {number} [height=1] - The height of the texture.
  7273. * @param {number} [depth=1] - The depth of the texture.
  7274. */
  7275. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7276. // We're going to add .setXXX() methods for setting properties later.
  7277. // Users can still set in Data3DTexture directly.
  7278. //
  7279. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7280. // texture.anisotropy = 16;
  7281. //
  7282. // See #14839
  7283. super( null );
  7284. /**
  7285. * This flag can be used for type testing.
  7286. *
  7287. * @type {boolean}
  7288. * @readonly
  7289. * @default true
  7290. */
  7291. this.isData3DTexture = true;
  7292. /**
  7293. * The image definition of a data texture.
  7294. *
  7295. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7296. */
  7297. this.image = { data, width, height, depth };
  7298. /**
  7299. * How the texture is sampled when a texel covers more than one pixel.
  7300. *
  7301. * Overwritten and set to `NearestFilter` by default.
  7302. *
  7303. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7304. * @default NearestFilter
  7305. */
  7306. this.magFilter = NearestFilter;
  7307. /**
  7308. * How the texture is sampled when a texel covers less than one pixel.
  7309. *
  7310. * Overwritten and set to `NearestFilter` by default.
  7311. *
  7312. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7313. * @default NearestFilter
  7314. */
  7315. this.minFilter = NearestFilter;
  7316. /**
  7317. * This defines how the texture is wrapped in the depth and corresponds to
  7318. * *W* in UVW mapping.
  7319. *
  7320. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7321. * @default ClampToEdgeWrapping
  7322. */
  7323. this.wrapR = ClampToEdgeWrapping;
  7324. /**
  7325. * Whether to generate mipmaps (if possible) for a texture.
  7326. *
  7327. * Overwritten and set to `false` by default.
  7328. *
  7329. * @type {boolean}
  7330. * @default false
  7331. */
  7332. this.generateMipmaps = false;
  7333. /**
  7334. * If set to `true`, the texture is flipped along the vertical axis when
  7335. * uploaded to the GPU.
  7336. *
  7337. * Overwritten and set to `false` by default.
  7338. *
  7339. * @type {boolean}
  7340. * @default false
  7341. */
  7342. this.flipY = false;
  7343. /**
  7344. * Specifies the alignment requirements for the start of each pixel row in memory.
  7345. *
  7346. * Overwritten and set to `1` by default.
  7347. *
  7348. * @type {boolean}
  7349. * @default 1
  7350. */
  7351. this.unpackAlignment = 1;
  7352. }
  7353. }
  7354. /**
  7355. * A 3D render target used in context of {@link WebGLRenderer}.
  7356. *
  7357. * @augments WebGLRenderTarget
  7358. */
  7359. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7360. /**
  7361. * Constructs a new 3D render target.
  7362. *
  7363. * @param {number} [width=1] - The width of the render target.
  7364. * @param {number} [height=1] - The height of the render target.
  7365. * @param {number} [depth=1] - The height of the render target.
  7366. * @param {RenderTarget~Options} [options] - The configuration object.
  7367. */
  7368. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7369. super( width, height, options );
  7370. /**
  7371. * This flag can be used for type testing.
  7372. *
  7373. * @type {boolean}
  7374. * @readonly
  7375. * @default true
  7376. */
  7377. this.isWebGL3DRenderTarget = true;
  7378. this.depth = depth;
  7379. /**
  7380. * Overwritten with a different texture type.
  7381. *
  7382. * @type {Data3DTexture}
  7383. */
  7384. this.texture = new Data3DTexture( null, width, height, depth );
  7385. this._setTextureOptions( options );
  7386. this.texture.isRenderTargetTexture = true;
  7387. }
  7388. }
  7389. /**
  7390. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7391. */
  7392. class Box3 {
  7393. /**
  7394. * Constructs a new bounding box.
  7395. *
  7396. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7397. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7398. */
  7399. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7400. /**
  7401. * This flag can be used for type testing.
  7402. *
  7403. * @type {boolean}
  7404. * @readonly
  7405. * @default true
  7406. */
  7407. this.isBox3 = true;
  7408. /**
  7409. * The lower boundary of the box.
  7410. *
  7411. * @type {Vector3}
  7412. */
  7413. this.min = min;
  7414. /**
  7415. * The upper boundary of the box.
  7416. *
  7417. * @type {Vector3}
  7418. */
  7419. this.max = max;
  7420. }
  7421. /**
  7422. * Sets the lower and upper boundaries of this box.
  7423. * Please note that this method only copies the values from the given objects.
  7424. *
  7425. * @param {Vector3} min - The lower boundary of the box.
  7426. * @param {Vector3} max - The upper boundary of the box.
  7427. * @return {Box3} A reference to this bounding box.
  7428. */
  7429. set( min, max ) {
  7430. this.min.copy( min );
  7431. this.max.copy( max );
  7432. return this;
  7433. }
  7434. /**
  7435. * Sets the upper and lower bounds of this box so it encloses the position data
  7436. * in the given array.
  7437. *
  7438. * @param {Array<number>} array - An array holding 3D position data.
  7439. * @return {Box3} A reference to this bounding box.
  7440. */
  7441. setFromArray( array ) {
  7442. this.makeEmpty();
  7443. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7444. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7445. }
  7446. return this;
  7447. }
  7448. /**
  7449. * Sets the upper and lower bounds of this box so it encloses the position data
  7450. * in the given buffer attribute.
  7451. *
  7452. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7453. * @return {Box3} A reference to this bounding box.
  7454. */
  7455. setFromBufferAttribute( attribute ) {
  7456. this.makeEmpty();
  7457. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7458. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7459. }
  7460. return this;
  7461. }
  7462. /**
  7463. * Sets the upper and lower bounds of this box so it encloses the position data
  7464. * in the given array.
  7465. *
  7466. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7467. * @return {Box3} A reference to this bounding box.
  7468. */
  7469. setFromPoints( points ) {
  7470. this.makeEmpty();
  7471. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7472. this.expandByPoint( points[ i ] );
  7473. }
  7474. return this;
  7475. }
  7476. /**
  7477. * Centers this box on the given center vector and sets this box's width, height and
  7478. * depth to the given size values.
  7479. *
  7480. * @param {Vector3} center - The center of the box.
  7481. * @param {Vector3} size - The x, y and z dimensions of the box.
  7482. * @return {Box3} A reference to this bounding box.
  7483. */
  7484. setFromCenterAndSize( center, size ) {
  7485. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7486. this.min.copy( center ).sub( halfSize );
  7487. this.max.copy( center ).add( halfSize );
  7488. return this;
  7489. }
  7490. /**
  7491. * Computes the world-axis-aligned bounding box for the given 3D object
  7492. * (including its children), accounting for the object's, and children's,
  7493. * world transforms. The function may result in a larger box than strictly necessary.
  7494. *
  7495. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7496. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7497. * world-axis-aligned bounding box at the expense of more computation.
  7498. * @return {Box3} A reference to this bounding box.
  7499. */
  7500. setFromObject( object, precise = false ) {
  7501. this.makeEmpty();
  7502. return this.expandByObject( object, precise );
  7503. }
  7504. /**
  7505. * Returns a new box with copied values from this instance.
  7506. *
  7507. * @return {Box3} A clone of this instance.
  7508. */
  7509. clone() {
  7510. return new this.constructor().copy( this );
  7511. }
  7512. /**
  7513. * Copies the values of the given box to this instance.
  7514. *
  7515. * @param {Box3} box - The box to copy.
  7516. * @return {Box3} A reference to this bounding box.
  7517. */
  7518. copy( box ) {
  7519. this.min.copy( box.min );
  7520. this.max.copy( box.max );
  7521. return this;
  7522. }
  7523. /**
  7524. * Makes this box empty which means in encloses a zero space in 3D.
  7525. *
  7526. * @return {Box3} A reference to this bounding box.
  7527. */
  7528. makeEmpty() {
  7529. this.min.x = this.min.y = this.min.z = + Infinity;
  7530. this.max.x = this.max.y = this.max.z = - Infinity;
  7531. return this;
  7532. }
  7533. /**
  7534. * Returns true if this box includes zero points within its bounds.
  7535. * Note that a box with equal lower and upper bounds still includes one
  7536. * point, the one both bounds share.
  7537. *
  7538. * @return {boolean} Whether this box is empty or not.
  7539. */
  7540. isEmpty() {
  7541. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7542. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7543. }
  7544. /**
  7545. * Returns the center point of this box.
  7546. *
  7547. * @param {Vector3} target - The target vector that is used to store the method's result.
  7548. * @return {Vector3} The center point.
  7549. */
  7550. getCenter( target ) {
  7551. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7552. }
  7553. /**
  7554. * Returns the dimensions of this box.
  7555. *
  7556. * @param {Vector3} target - The target vector that is used to store the method's result.
  7557. * @return {Vector3} The size.
  7558. */
  7559. getSize( target ) {
  7560. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7561. }
  7562. /**
  7563. * Expands the boundaries of this box to include the given point.
  7564. *
  7565. * @param {Vector3} point - The point that should be included by the bounding box.
  7566. * @return {Box3} A reference to this bounding box.
  7567. */
  7568. expandByPoint( point ) {
  7569. this.min.min( point );
  7570. this.max.max( point );
  7571. return this;
  7572. }
  7573. /**
  7574. * Expands this box equilaterally by the given vector. The width of this
  7575. * box will be expanded by the x component of the vector in both
  7576. * directions. The height of this box will be expanded by the y component of
  7577. * the vector in both directions. The depth of this box will be
  7578. * expanded by the z component of the vector in both directions.
  7579. *
  7580. * @param {Vector3} vector - The vector that should expand the bounding box.
  7581. * @return {Box3} A reference to this bounding box.
  7582. */
  7583. expandByVector( vector ) {
  7584. this.min.sub( vector );
  7585. this.max.add( vector );
  7586. return this;
  7587. }
  7588. /**
  7589. * Expands each dimension of the box by the given scalar. If negative, the
  7590. * dimensions of the box will be contracted.
  7591. *
  7592. * @param {number} scalar - The scalar value that should expand the bounding box.
  7593. * @return {Box3} A reference to this bounding box.
  7594. */
  7595. expandByScalar( scalar ) {
  7596. this.min.addScalar( - scalar );
  7597. this.max.addScalar( scalar );
  7598. return this;
  7599. }
  7600. /**
  7601. * Expands the boundaries of this box to include the given 3D object and
  7602. * its children, accounting for the object's, and children's, world
  7603. * transforms. The function may result in a larger box than strictly
  7604. * necessary (unless the precise parameter is set to true).
  7605. *
  7606. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7607. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7608. * as little as necessary at the expense of more computation.
  7609. * @return {Box3} A reference to this bounding box.
  7610. */
  7611. expandByObject( object, precise = false ) {
  7612. // Computes the world-axis-aligned bounding box of an object (including its children),
  7613. // accounting for both the object's, and children's, world transforms
  7614. object.updateWorldMatrix( false, false );
  7615. const geometry = object.geometry;
  7616. if ( geometry !== undefined ) {
  7617. const positionAttribute = geometry.getAttribute( 'position' );
  7618. // precise AABB computation based on vertex data requires at least a position attribute.
  7619. // instancing isn't supported so far and uses the normal (conservative) code path.
  7620. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7621. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7622. if ( object.isMesh === true ) {
  7623. object.getVertexPosition( i, _vector$b );
  7624. } else {
  7625. _vector$b.fromBufferAttribute( positionAttribute, i );
  7626. }
  7627. _vector$b.applyMatrix4( object.matrixWorld );
  7628. this.expandByPoint( _vector$b );
  7629. }
  7630. } else {
  7631. if ( object.boundingBox !== undefined ) {
  7632. // object-level bounding box
  7633. if ( object.boundingBox === null ) {
  7634. object.computeBoundingBox();
  7635. }
  7636. _box$4.copy( object.boundingBox );
  7637. } else {
  7638. // geometry-level bounding box
  7639. if ( geometry.boundingBox === null ) {
  7640. geometry.computeBoundingBox();
  7641. }
  7642. _box$4.copy( geometry.boundingBox );
  7643. }
  7644. _box$4.applyMatrix4( object.matrixWorld );
  7645. this.union( _box$4 );
  7646. }
  7647. }
  7648. const children = object.children;
  7649. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7650. this.expandByObject( children[ i ], precise );
  7651. }
  7652. return this;
  7653. }
  7654. /**
  7655. * Returns `true` if the given point lies within or on the boundaries of this box.
  7656. *
  7657. * @param {Vector3} point - The point to test.
  7658. * @return {boolean} Whether the bounding box contains the given point or not.
  7659. */
  7660. containsPoint( point ) {
  7661. return point.x >= this.min.x && point.x <= this.max.x &&
  7662. point.y >= this.min.y && point.y <= this.max.y &&
  7663. point.z >= this.min.z && point.z <= this.max.z;
  7664. }
  7665. /**
  7666. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7667. * If this box and the given one are identical, this function also returns `true`.
  7668. *
  7669. * @param {Box3} box - The bounding box to test.
  7670. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7671. */
  7672. containsBox( box ) {
  7673. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7674. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7675. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7676. }
  7677. /**
  7678. * Returns a point as a proportion of this box's width, height and depth.
  7679. *
  7680. * @param {Vector3} point - A point in 3D space.
  7681. * @param {Vector3} target - The target vector that is used to store the method's result.
  7682. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7683. */
  7684. getParameter( point, target ) {
  7685. // This can potentially have a divide by zero if the box
  7686. // has a size dimension of 0.
  7687. return target.set(
  7688. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7689. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7690. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7691. );
  7692. }
  7693. /**
  7694. * Returns `true` if the given bounding box intersects with this bounding box.
  7695. *
  7696. * @param {Box3} box - The bounding box to test.
  7697. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7698. */
  7699. intersectsBox( box ) {
  7700. // using 6 splitting planes to rule out intersections.
  7701. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7702. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7703. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7704. }
  7705. /**
  7706. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7707. *
  7708. * @param {Sphere} sphere - The bounding sphere to test.
  7709. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7710. */
  7711. intersectsSphere( sphere ) {
  7712. // Find the point on the AABB closest to the sphere center.
  7713. this.clampPoint( sphere.center, _vector$b );
  7714. // If that point is inside the sphere, the AABB and sphere intersect.
  7715. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7716. }
  7717. /**
  7718. * Returns `true` if the given plane intersects with this bounding box.
  7719. *
  7720. * @param {Plane} plane - The plane to test.
  7721. * @return {boolean} Whether the given plane intersects with this bounding box.
  7722. */
  7723. intersectsPlane( plane ) {
  7724. // We compute the minimum and maximum dot product values. If those values
  7725. // are on the same side (back or front) of the plane, then there is no intersection.
  7726. let min, max;
  7727. if ( plane.normal.x > 0 ) {
  7728. min = plane.normal.x * this.min.x;
  7729. max = plane.normal.x * this.max.x;
  7730. } else {
  7731. min = plane.normal.x * this.max.x;
  7732. max = plane.normal.x * this.min.x;
  7733. }
  7734. if ( plane.normal.y > 0 ) {
  7735. min += plane.normal.y * this.min.y;
  7736. max += plane.normal.y * this.max.y;
  7737. } else {
  7738. min += plane.normal.y * this.max.y;
  7739. max += plane.normal.y * this.min.y;
  7740. }
  7741. if ( plane.normal.z > 0 ) {
  7742. min += plane.normal.z * this.min.z;
  7743. max += plane.normal.z * this.max.z;
  7744. } else {
  7745. min += plane.normal.z * this.max.z;
  7746. max += plane.normal.z * this.min.z;
  7747. }
  7748. return ( min <= - plane.constant && max >= - plane.constant );
  7749. }
  7750. /**
  7751. * Returns `true` if the given triangle intersects with this bounding box.
  7752. *
  7753. * @param {Triangle} triangle - The triangle to test.
  7754. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7755. */
  7756. intersectsTriangle( triangle ) {
  7757. if ( this.isEmpty() ) {
  7758. return false;
  7759. }
  7760. // compute box center and extents
  7761. this.getCenter( _center );
  7762. _extents.subVectors( this.max, _center );
  7763. // translate triangle to aabb origin
  7764. _v0$3.subVectors( triangle.a, _center );
  7765. _v1$7.subVectors( triangle.b, _center );
  7766. _v2$4.subVectors( triangle.c, _center );
  7767. // compute edge vectors for triangle
  7768. _f0.subVectors( _v1$7, _v0$3 );
  7769. _f1.subVectors( _v2$4, _v1$7 );
  7770. _f2.subVectors( _v0$3, _v2$4 );
  7771. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7772. // 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
  7773. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7774. let axes = [
  7775. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7776. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7777. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7778. ];
  7779. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7780. return false;
  7781. }
  7782. // test 3 face normals from the aabb
  7783. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7784. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7785. return false;
  7786. }
  7787. // finally testing the face normal of the triangle
  7788. // use already existing triangle edge vectors here
  7789. _triangleNormal.crossVectors( _f0, _f1 );
  7790. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7791. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7792. }
  7793. /**
  7794. * Clamps the given point within the bounds of this box.
  7795. *
  7796. * @param {Vector3} point - The point to clamp.
  7797. * @param {Vector3} target - The target vector that is used to store the method's result.
  7798. * @return {Vector3} The clamped point.
  7799. */
  7800. clampPoint( point, target ) {
  7801. return target.copy( point ).clamp( this.min, this.max );
  7802. }
  7803. /**
  7804. * Returns the euclidean distance from any edge of this box to the specified point. If
  7805. * the given point lies inside of this box, the distance will be `0`.
  7806. *
  7807. * @param {Vector3} point - The point to compute the distance to.
  7808. * @return {number} The euclidean distance.
  7809. */
  7810. distanceToPoint( point ) {
  7811. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7812. }
  7813. /**
  7814. * Returns a bounding sphere that encloses this bounding box.
  7815. *
  7816. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7817. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7818. */
  7819. getBoundingSphere( target ) {
  7820. if ( this.isEmpty() ) {
  7821. target.makeEmpty();
  7822. } else {
  7823. this.getCenter( target.center );
  7824. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7825. }
  7826. return target;
  7827. }
  7828. /**
  7829. * Computes the intersection of this bounding box and the given one, setting the upper
  7830. * bound of this box to the lesser of the two boxes' upper bounds and the
  7831. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7832. * there's no overlap, makes this box empty.
  7833. *
  7834. * @param {Box3} box - The bounding box to intersect with.
  7835. * @return {Box3} A reference to this bounding box.
  7836. */
  7837. intersect( box ) {
  7838. this.min.max( box.min );
  7839. this.max.min( box.max );
  7840. // 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.
  7841. if ( this.isEmpty() ) this.makeEmpty();
  7842. return this;
  7843. }
  7844. /**
  7845. * Computes the union of this box and another and the given one, setting the upper
  7846. * bound of this box to the greater of the two boxes' upper bounds and the
  7847. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7848. *
  7849. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7850. * @return {Box3} A reference to this bounding box.
  7851. */
  7852. union( box ) {
  7853. this.min.min( box.min );
  7854. this.max.max( box.max );
  7855. return this;
  7856. }
  7857. /**
  7858. * Transforms this bounding box by the given 4x4 transformation matrix.
  7859. *
  7860. * @param {Matrix4} matrix - The transformation matrix.
  7861. * @return {Box3} A reference to this bounding box.
  7862. */
  7863. applyMatrix4( matrix ) {
  7864. // transform of empty box is an empty box.
  7865. if ( this.isEmpty() ) return this;
  7866. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7867. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7868. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7869. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7870. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7871. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7872. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7873. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7874. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7875. this.setFromPoints( _points );
  7876. return this;
  7877. }
  7878. /**
  7879. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7880. * effectively moving it in 3D space.
  7881. *
  7882. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7883. * @return {Box3} A reference to this bounding box.
  7884. */
  7885. translate( offset ) {
  7886. this.min.add( offset );
  7887. this.max.add( offset );
  7888. return this;
  7889. }
  7890. /**
  7891. * Returns `true` if this bounding box is equal with the given one.
  7892. *
  7893. * @param {Box3} box - The box to test for equality.
  7894. * @return {boolean} Whether this bounding box is equal with the given one.
  7895. */
  7896. equals( box ) {
  7897. return box.min.equals( this.min ) && box.max.equals( this.max );
  7898. }
  7899. /**
  7900. * Returns a serialized structure of the bounding box.
  7901. *
  7902. * @return {Object} Serialized structure with fields representing the object state.
  7903. */
  7904. toJSON() {
  7905. return {
  7906. min: this.min.toArray(),
  7907. max: this.max.toArray()
  7908. };
  7909. }
  7910. /**
  7911. * Returns a serialized structure of the bounding box.
  7912. *
  7913. * @param {Object} json - The serialized json to set the box from.
  7914. * @return {Box3} A reference to this bounding box.
  7915. */
  7916. fromJSON( json ) {
  7917. this.min.fromArray( json.min );
  7918. this.max.fromArray( json.max );
  7919. return this;
  7920. }
  7921. }
  7922. const _points = [
  7923. /*@__PURE__*/ new Vector3(),
  7924. /*@__PURE__*/ new Vector3(),
  7925. /*@__PURE__*/ new Vector3(),
  7926. /*@__PURE__*/ new Vector3(),
  7927. /*@__PURE__*/ new Vector3(),
  7928. /*@__PURE__*/ new Vector3(),
  7929. /*@__PURE__*/ new Vector3(),
  7930. /*@__PURE__*/ new Vector3()
  7931. ];
  7932. const _vector$b = /*@__PURE__*/ new Vector3();
  7933. const _box$4 = /*@__PURE__*/ new Box3();
  7934. // triangle centered vertices
  7935. const _v0$3 = /*@__PURE__*/ new Vector3();
  7936. const _v1$7 = /*@__PURE__*/ new Vector3();
  7937. const _v2$4 = /*@__PURE__*/ new Vector3();
  7938. // triangle edge vectors
  7939. const _f0 = /*@__PURE__*/ new Vector3();
  7940. const _f1 = /*@__PURE__*/ new Vector3();
  7941. const _f2 = /*@__PURE__*/ new Vector3();
  7942. const _center = /*@__PURE__*/ new Vector3();
  7943. const _extents = /*@__PURE__*/ new Vector3();
  7944. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7945. const _testAxis = /*@__PURE__*/ new Vector3();
  7946. function satForAxes( axes, v0, v1, v2, extents ) {
  7947. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7948. _testAxis.fromArray( axes, i );
  7949. // project the aabb onto the separating axis
  7950. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7951. // project all 3 vertices of the triangle onto the separating axis
  7952. const p0 = v0.dot( _testAxis );
  7953. const p1 = v1.dot( _testAxis );
  7954. const p2 = v2.dot( _testAxis );
  7955. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7956. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7957. // points of the projected triangle are outside the projected half-length of the aabb
  7958. // the axis is separating and we can exit
  7959. return false;
  7960. }
  7961. }
  7962. return true;
  7963. }
  7964. const _box$3 = /*@__PURE__*/ new Box3();
  7965. const _v1$6 = /*@__PURE__*/ new Vector3();
  7966. const _v2$3 = /*@__PURE__*/ new Vector3();
  7967. /**
  7968. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7969. * used as a Bounding Sphere for 3D objects.
  7970. */
  7971. class Sphere {
  7972. /**
  7973. * Constructs a new sphere.
  7974. *
  7975. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7976. * @param {number} [radius=-1] - The radius of the sphere.
  7977. */
  7978. constructor( center = new Vector3(), radius = -1 ) {
  7979. /**
  7980. * This flag can be used for type testing.
  7981. *
  7982. * @type {boolean}
  7983. * @readonly
  7984. * @default true
  7985. */
  7986. this.isSphere = true;
  7987. /**
  7988. * The center of the sphere
  7989. *
  7990. * @type {Vector3}
  7991. */
  7992. this.center = center;
  7993. /**
  7994. * The radius of the sphere.
  7995. *
  7996. * @type {number}
  7997. */
  7998. this.radius = radius;
  7999. }
  8000. /**
  8001. * Sets the sphere's components by copying the given values.
  8002. *
  8003. * @param {Vector3} center - The center.
  8004. * @param {number} radius - The radius.
  8005. * @return {Sphere} A reference to this sphere.
  8006. */
  8007. set( center, radius ) {
  8008. this.center.copy( center );
  8009. this.radius = radius;
  8010. return this;
  8011. }
  8012. /**
  8013. * Computes the minimum bounding sphere for list of points.
  8014. * If the optional center point is given, it is used as the sphere's
  8015. * center. Otherwise, the center of the axis-aligned bounding box
  8016. * encompassing the points is calculated.
  8017. *
  8018. * @param {Array<Vector3>} points - A list of points in 3D space.
  8019. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8020. * @return {Sphere} A reference to this sphere.
  8021. */
  8022. setFromPoints( points, optionalCenter ) {
  8023. const center = this.center;
  8024. if ( optionalCenter !== undefined ) {
  8025. center.copy( optionalCenter );
  8026. } else {
  8027. _box$3.setFromPoints( points ).getCenter( center );
  8028. }
  8029. let maxRadiusSq = 0;
  8030. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8031. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8032. }
  8033. this.radius = Math.sqrt( maxRadiusSq );
  8034. return this;
  8035. }
  8036. /**
  8037. * Copies the values of the given sphere to this instance.
  8038. *
  8039. * @param {Sphere} sphere - The sphere to copy.
  8040. * @return {Sphere} A reference to this sphere.
  8041. */
  8042. copy( sphere ) {
  8043. this.center.copy( sphere.center );
  8044. this.radius = sphere.radius;
  8045. return this;
  8046. }
  8047. /**
  8048. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8049. *
  8050. * Spheres with a radius of `0` contain only their center point and are not
  8051. * considered to be empty.
  8052. *
  8053. * @return {boolean} Whether this sphere is empty or not.
  8054. */
  8055. isEmpty() {
  8056. return ( this.radius < 0 );
  8057. }
  8058. /**
  8059. * Makes this sphere empty which means in encloses a zero space in 3D.
  8060. *
  8061. * @return {Sphere} A reference to this sphere.
  8062. */
  8063. makeEmpty() {
  8064. this.center.set( 0, 0, 0 );
  8065. this.radius = -1;
  8066. return this;
  8067. }
  8068. /**
  8069. * Returns `true` if this sphere contains the given point inclusive of
  8070. * the surface of the sphere.
  8071. *
  8072. * @param {Vector3} point - The point to check.
  8073. * @return {boolean} Whether this sphere contains the given point or not.
  8074. */
  8075. containsPoint( point ) {
  8076. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8077. }
  8078. /**
  8079. * Returns the closest distance from the boundary of the sphere to the
  8080. * given point. If the sphere contains the point, the distance will
  8081. * be negative.
  8082. *
  8083. * @param {Vector3} point - The point to compute the distance to.
  8084. * @return {number} The distance to the point.
  8085. */
  8086. distanceToPoint( point ) {
  8087. return ( point.distanceTo( this.center ) - this.radius );
  8088. }
  8089. /**
  8090. * Returns `true` if this sphere intersects with the given one.
  8091. *
  8092. * @param {Sphere} sphere - The sphere to test.
  8093. * @return {boolean} Whether this sphere intersects with the given one or not.
  8094. */
  8095. intersectsSphere( sphere ) {
  8096. const radiusSum = this.radius + sphere.radius;
  8097. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8098. }
  8099. /**
  8100. * Returns `true` if this sphere intersects with the given box.
  8101. *
  8102. * @param {Box3} box - The box to test.
  8103. * @return {boolean} Whether this sphere intersects with the given box or not.
  8104. */
  8105. intersectsBox( box ) {
  8106. return box.intersectsSphere( this );
  8107. }
  8108. /**
  8109. * Returns `true` if this sphere intersects with the given plane.
  8110. *
  8111. * @param {Plane} plane - The plane to test.
  8112. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8113. */
  8114. intersectsPlane( plane ) {
  8115. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8116. }
  8117. /**
  8118. * Clamps a point within the sphere. If the point is outside the sphere, it
  8119. * will clamp it to the closest point on the edge of the sphere. Points
  8120. * already inside the sphere will not be affected.
  8121. *
  8122. * @param {Vector3} point - The plane to clamp.
  8123. * @param {Vector3} target - The target vector that is used to store the method's result.
  8124. * @return {Vector3} The clamped point.
  8125. */
  8126. clampPoint( point, target ) {
  8127. const deltaLengthSq = this.center.distanceToSquared( point );
  8128. target.copy( point );
  8129. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8130. target.sub( this.center ).normalize();
  8131. target.multiplyScalar( this.radius ).add( this.center );
  8132. }
  8133. return target;
  8134. }
  8135. /**
  8136. * Returns a bounding box that encloses this sphere.
  8137. *
  8138. * @param {Box3} target - The target box that is used to store the method's result.
  8139. * @return {Box3} The bounding box that encloses this sphere.
  8140. */
  8141. getBoundingBox( target ) {
  8142. if ( this.isEmpty() ) {
  8143. // Empty sphere produces empty bounding box
  8144. target.makeEmpty();
  8145. return target;
  8146. }
  8147. target.set( this.center, this.center );
  8148. target.expandByScalar( this.radius );
  8149. return target;
  8150. }
  8151. /**
  8152. * Transforms this sphere with the given 4x4 transformation matrix.
  8153. *
  8154. * @param {Matrix4} matrix - The transformation matrix.
  8155. * @return {Sphere} A reference to this sphere.
  8156. */
  8157. applyMatrix4( matrix ) {
  8158. this.center.applyMatrix4( matrix );
  8159. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8160. return this;
  8161. }
  8162. /**
  8163. * Translates the sphere's center by the given offset.
  8164. *
  8165. * @param {Vector3} offset - The offset.
  8166. * @return {Sphere} A reference to this sphere.
  8167. */
  8168. translate( offset ) {
  8169. this.center.add( offset );
  8170. return this;
  8171. }
  8172. /**
  8173. * Expands the boundaries of this sphere to include the given point.
  8174. *
  8175. * @param {Vector3} point - The point to include.
  8176. * @return {Sphere} A reference to this sphere.
  8177. */
  8178. expandByPoint( point ) {
  8179. if ( this.isEmpty() ) {
  8180. this.center.copy( point );
  8181. this.radius = 0;
  8182. return this;
  8183. }
  8184. _v1$6.subVectors( point, this.center );
  8185. const lengthSq = _v1$6.lengthSq();
  8186. if ( lengthSq > ( this.radius * this.radius ) ) {
  8187. // calculate the minimal sphere
  8188. const length = Math.sqrt( lengthSq );
  8189. const delta = ( length - this.radius ) * 0.5;
  8190. this.center.addScaledVector( _v1$6, delta / length );
  8191. this.radius += delta;
  8192. }
  8193. return this;
  8194. }
  8195. /**
  8196. * Expands this sphere to enclose both the original sphere and the given sphere.
  8197. *
  8198. * @param {Sphere} sphere - The sphere to include.
  8199. * @return {Sphere} A reference to this sphere.
  8200. */
  8201. union( sphere ) {
  8202. if ( sphere.isEmpty() ) {
  8203. return this;
  8204. }
  8205. if ( this.isEmpty() ) {
  8206. this.copy( sphere );
  8207. return this;
  8208. }
  8209. if ( this.center.equals( sphere.center ) === true ) {
  8210. this.radius = Math.max( this.radius, sphere.radius );
  8211. } else {
  8212. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8213. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8214. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8215. }
  8216. return this;
  8217. }
  8218. /**
  8219. * Returns `true` if this sphere is equal with the given one.
  8220. *
  8221. * @param {Sphere} sphere - The sphere to test for equality.
  8222. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8223. */
  8224. equals( sphere ) {
  8225. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8226. }
  8227. /**
  8228. * Returns a new sphere with copied values from this instance.
  8229. *
  8230. * @return {Sphere} A clone of this instance.
  8231. */
  8232. clone() {
  8233. return new this.constructor().copy( this );
  8234. }
  8235. /**
  8236. * Returns a serialized structure of the bounding sphere.
  8237. *
  8238. * @return {Object} Serialized structure with fields representing the object state.
  8239. */
  8240. toJSON() {
  8241. return {
  8242. radius: this.radius,
  8243. center: this.center.toArray()
  8244. };
  8245. }
  8246. /**
  8247. * Returns a serialized structure of the bounding sphere.
  8248. *
  8249. * @param {Object} json - The serialized json to set the sphere from.
  8250. * @return {Sphere} A reference to this bounding sphere.
  8251. */
  8252. fromJSON( json ) {
  8253. this.radius = json.radius;
  8254. this.center.fromArray( json.center );
  8255. return this;
  8256. }
  8257. }
  8258. const _vector$a = /*@__PURE__*/ new Vector3();
  8259. const _segCenter = /*@__PURE__*/ new Vector3();
  8260. const _segDir = /*@__PURE__*/ new Vector3();
  8261. const _diff = /*@__PURE__*/ new Vector3();
  8262. const _edge1 = /*@__PURE__*/ new Vector3();
  8263. const _edge2 = /*@__PURE__*/ new Vector3();
  8264. const _normal$1 = /*@__PURE__*/ new Vector3();
  8265. /**
  8266. * A ray that emits from an origin in a certain direction. The class is used by
  8267. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8268. * mouse picking (working out what objects in the 3D space the mouse is over)
  8269. * amongst other things.
  8270. */
  8271. class Ray {
  8272. /**
  8273. * Constructs a new ray.
  8274. *
  8275. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8276. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8277. */
  8278. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8279. /**
  8280. * The origin of the ray.
  8281. *
  8282. * @type {Vector3}
  8283. */
  8284. this.origin = origin;
  8285. /**
  8286. * The (normalized) direction of the ray.
  8287. *
  8288. * @type {Vector3}
  8289. */
  8290. this.direction = direction;
  8291. }
  8292. /**
  8293. * Sets the ray's components by copying the given values.
  8294. *
  8295. * @param {Vector3} origin - The origin.
  8296. * @param {Vector3} direction - The direction.
  8297. * @return {Ray} A reference to this ray.
  8298. */
  8299. set( origin, direction ) {
  8300. this.origin.copy( origin );
  8301. this.direction.copy( direction );
  8302. return this;
  8303. }
  8304. /**
  8305. * Copies the values of the given ray to this instance.
  8306. *
  8307. * @param {Ray} ray - The ray to copy.
  8308. * @return {Ray} A reference to this ray.
  8309. */
  8310. copy( ray ) {
  8311. this.origin.copy( ray.origin );
  8312. this.direction.copy( ray.direction );
  8313. return this;
  8314. }
  8315. /**
  8316. * Returns a vector that is located at a given distance along this ray.
  8317. *
  8318. * @param {number} t - The distance along the ray to retrieve a position for.
  8319. * @param {Vector3} target - The target vector that is used to store the method's result.
  8320. * @return {Vector3} A position on the ray.
  8321. */
  8322. at( t, target ) {
  8323. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8324. }
  8325. /**
  8326. * Adjusts the direction of the ray to point at the given vector in world space.
  8327. *
  8328. * @param {Vector3} v - The target position.
  8329. * @return {Ray} A reference to this ray.
  8330. */
  8331. lookAt( v ) {
  8332. this.direction.copy( v ).sub( this.origin ).normalize();
  8333. return this;
  8334. }
  8335. /**
  8336. * Shift the origin of this ray along its direction by the given distance.
  8337. *
  8338. * @param {number} t - The distance along the ray to interpolate.
  8339. * @return {Ray} A reference to this ray.
  8340. */
  8341. recast( t ) {
  8342. this.origin.copy( this.at( t, _vector$a ) );
  8343. return this;
  8344. }
  8345. /**
  8346. * Returns the point along this ray that is closest to the given point.
  8347. *
  8348. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8349. * @param {Vector3} target - The target vector that is used to store the method's result.
  8350. * @return {Vector3} The closest point on this ray.
  8351. */
  8352. closestPointToPoint( point, target ) {
  8353. target.subVectors( point, this.origin );
  8354. const directionDistance = target.dot( this.direction );
  8355. if ( directionDistance < 0 ) {
  8356. return target.copy( this.origin );
  8357. }
  8358. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8359. }
  8360. /**
  8361. * Returns the distance of the closest approach between this ray and the given point.
  8362. *
  8363. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8364. * @return {number} The distance.
  8365. */
  8366. distanceToPoint( point ) {
  8367. return Math.sqrt( this.distanceSqToPoint( point ) );
  8368. }
  8369. /**
  8370. * Returns the squared distance of the closest approach between this ray and the given point.
  8371. *
  8372. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8373. * @return {number} The squared distance.
  8374. */
  8375. distanceSqToPoint( point ) {
  8376. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8377. // point behind the ray
  8378. if ( directionDistance < 0 ) {
  8379. return this.origin.distanceToSquared( point );
  8380. }
  8381. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8382. return _vector$a.distanceToSquared( point );
  8383. }
  8384. /**
  8385. * Returns the squared distance between this ray and the given line segment.
  8386. *
  8387. * @param {Vector3} v0 - The start point of the line segment.
  8388. * @param {Vector3} v1 - The end point of the line segment.
  8389. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8390. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8391. * @return {number} The squared distance.
  8392. */
  8393. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8394. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8395. // It returns the min distance between the ray and the segment
  8396. // defined by v0 and v1
  8397. // It can also set two optional targets :
  8398. // - The closest point on the ray
  8399. // - The closest point on the segment
  8400. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8401. _segDir.copy( v1 ).sub( v0 ).normalize();
  8402. _diff.copy( this.origin ).sub( _segCenter );
  8403. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8404. const a01 = - this.direction.dot( _segDir );
  8405. const b0 = _diff.dot( this.direction );
  8406. const b1 = - _diff.dot( _segDir );
  8407. const c = _diff.lengthSq();
  8408. const det = Math.abs( 1 - a01 * a01 );
  8409. let s0, s1, sqrDist, extDet;
  8410. if ( det > 0 ) {
  8411. // The ray and segment are not parallel.
  8412. s0 = a01 * b1 - b0;
  8413. s1 = a01 * b0 - b1;
  8414. extDet = segExtent * det;
  8415. if ( s0 >= 0 ) {
  8416. if ( s1 >= - extDet ) {
  8417. if ( s1 <= extDet ) {
  8418. // region 0
  8419. // Minimum at interior points of ray and segment.
  8420. const invDet = 1 / det;
  8421. s0 *= invDet;
  8422. s1 *= invDet;
  8423. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8424. } else {
  8425. // region 1
  8426. s1 = segExtent;
  8427. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8428. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8429. }
  8430. } else {
  8431. // region 5
  8432. s1 = - segExtent;
  8433. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8434. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8435. }
  8436. } else {
  8437. if ( s1 <= - extDet ) {
  8438. // region 4
  8439. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8440. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8441. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8442. } else if ( s1 <= extDet ) {
  8443. // region 3
  8444. s0 = 0;
  8445. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8446. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8447. } else {
  8448. // region 2
  8449. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8450. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8451. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8452. }
  8453. }
  8454. } else {
  8455. // Ray and segment are parallel.
  8456. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8457. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8458. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8459. }
  8460. if ( optionalPointOnRay ) {
  8461. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8462. }
  8463. if ( optionalPointOnSegment ) {
  8464. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8465. }
  8466. return sqrDist;
  8467. }
  8468. /**
  8469. * Intersects this ray with the given sphere, returning the intersection
  8470. * point or `null` if there is no intersection.
  8471. *
  8472. * @param {Sphere} sphere - The sphere to intersect.
  8473. * @param {Vector3} target - The target vector that is used to store the method's result.
  8474. * @return {?Vector3} The intersection point.
  8475. */
  8476. intersectSphere( sphere, target ) {
  8477. _vector$a.subVectors( sphere.center, this.origin );
  8478. const tca = _vector$a.dot( this.direction );
  8479. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8480. const radius2 = sphere.radius * sphere.radius;
  8481. if ( d2 > radius2 ) return null;
  8482. const thc = Math.sqrt( radius2 - d2 );
  8483. // t0 = first intersect point - entrance on front of sphere
  8484. const t0 = tca - thc;
  8485. // t1 = second intersect point - exit point on back of sphere
  8486. const t1 = tca + thc;
  8487. // test to see if t1 is behind the ray - if so, return null
  8488. if ( t1 < 0 ) return null;
  8489. // test to see if t0 is behind the ray:
  8490. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8491. // in order to always return an intersect point that is in front of the ray.
  8492. if ( t0 < 0 ) return this.at( t1, target );
  8493. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8494. return this.at( t0, target );
  8495. }
  8496. /**
  8497. * Returns `true` if this ray intersects with the given sphere.
  8498. *
  8499. * @param {Sphere} sphere - The sphere to intersect.
  8500. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8501. */
  8502. intersectsSphere( sphere ) {
  8503. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8504. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8505. }
  8506. /**
  8507. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8508. * does not intersect with the plane.
  8509. *
  8510. * @param {Plane} plane - The plane to compute the distance to.
  8511. * @return {?number} Whether this ray intersects with the given sphere or not.
  8512. */
  8513. distanceToPlane( plane ) {
  8514. const denominator = plane.normal.dot( this.direction );
  8515. if ( denominator === 0 ) {
  8516. // line is coplanar, return origin
  8517. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8518. return 0;
  8519. }
  8520. // Null is preferable to undefined since undefined means.... it is undefined
  8521. return null;
  8522. }
  8523. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8524. // Return if the ray never intersects the plane
  8525. return t >= 0 ? t : null;
  8526. }
  8527. /**
  8528. * Intersects this ray with the given plane, returning the intersection
  8529. * point or `null` if there is no intersection.
  8530. *
  8531. * @param {Plane} plane - The plane to intersect.
  8532. * @param {Vector3} target - The target vector that is used to store the method's result.
  8533. * @return {?Vector3} The intersection point.
  8534. */
  8535. intersectPlane( plane, target ) {
  8536. const t = this.distanceToPlane( plane );
  8537. if ( t === null ) {
  8538. return null;
  8539. }
  8540. return this.at( t, target );
  8541. }
  8542. /**
  8543. * Returns `true` if this ray intersects with the given plane.
  8544. *
  8545. * @param {Plane} plane - The plane to intersect.
  8546. * @return {boolean} Whether this ray intersects with the given plane or not.
  8547. */
  8548. intersectsPlane( plane ) {
  8549. // check if the ray lies on the plane first
  8550. const distToPoint = plane.distanceToPoint( this.origin );
  8551. if ( distToPoint === 0 ) {
  8552. return true;
  8553. }
  8554. const denominator = plane.normal.dot( this.direction );
  8555. if ( denominator * distToPoint < 0 ) {
  8556. return true;
  8557. }
  8558. // ray origin is behind the plane (and is pointing behind it)
  8559. return false;
  8560. }
  8561. /**
  8562. * Intersects this ray with the given bounding box, returning the intersection
  8563. * point or `null` if there is no intersection.
  8564. *
  8565. * @param {Box3} box - The box to intersect.
  8566. * @param {Vector3} target - The target vector that is used to store the method's result.
  8567. * @return {?Vector3} The intersection point.
  8568. */
  8569. intersectBox( box, target ) {
  8570. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8571. const invdirx = 1 / this.direction.x,
  8572. invdiry = 1 / this.direction.y,
  8573. invdirz = 1 / this.direction.z;
  8574. const origin = this.origin;
  8575. if ( invdirx >= 0 ) {
  8576. tmin = ( box.min.x - origin.x ) * invdirx;
  8577. tmax = ( box.max.x - origin.x ) * invdirx;
  8578. } else {
  8579. tmin = ( box.max.x - origin.x ) * invdirx;
  8580. tmax = ( box.min.x - origin.x ) * invdirx;
  8581. }
  8582. if ( invdiry >= 0 ) {
  8583. tymin = ( box.min.y - origin.y ) * invdiry;
  8584. tymax = ( box.max.y - origin.y ) * invdiry;
  8585. } else {
  8586. tymin = ( box.max.y - origin.y ) * invdiry;
  8587. tymax = ( box.min.y - origin.y ) * invdiry;
  8588. }
  8589. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8590. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8591. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8592. if ( invdirz >= 0 ) {
  8593. tzmin = ( box.min.z - origin.z ) * invdirz;
  8594. tzmax = ( box.max.z - origin.z ) * invdirz;
  8595. } else {
  8596. tzmin = ( box.max.z - origin.z ) * invdirz;
  8597. tzmax = ( box.min.z - origin.z ) * invdirz;
  8598. }
  8599. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8600. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8601. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8602. //return point closest to the ray (positive side)
  8603. if ( tmax < 0 ) return null;
  8604. return this.at( tmin >= 0 ? tmin : tmax, target );
  8605. }
  8606. /**
  8607. * Returns `true` if this ray intersects with the given box.
  8608. *
  8609. * @param {Box3} box - The box to intersect.
  8610. * @return {boolean} Whether this ray intersects with the given box or not.
  8611. */
  8612. intersectsBox( box ) {
  8613. return this.intersectBox( box, _vector$a ) !== null;
  8614. }
  8615. /**
  8616. * Intersects this ray with the given triangle, returning the intersection
  8617. * point or `null` if there is no intersection.
  8618. *
  8619. * @param {Vector3} a - The first vertex of the triangle.
  8620. * @param {Vector3} b - The second vertex of the triangle.
  8621. * @param {Vector3} c - The third vertex of the triangle.
  8622. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8623. * @param {Vector3} target - The target vector that is used to store the method's result.
  8624. * @return {?Vector3} The intersection point.
  8625. */
  8626. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8627. // Compute the offset origin, edges, and normal.
  8628. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8629. _edge1.subVectors( b, a );
  8630. _edge2.subVectors( c, a );
  8631. _normal$1.crossVectors( _edge1, _edge2 );
  8632. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8633. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8634. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8635. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8636. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8637. let DdN = this.direction.dot( _normal$1 );
  8638. let sign;
  8639. if ( DdN > 0 ) {
  8640. if ( backfaceCulling ) return null;
  8641. sign = 1;
  8642. } else if ( DdN < 0 ) {
  8643. sign = -1;
  8644. DdN = - DdN;
  8645. } else {
  8646. return null;
  8647. }
  8648. _diff.subVectors( this.origin, a );
  8649. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8650. // b1 < 0, no intersection
  8651. if ( DdQxE2 < 0 ) {
  8652. return null;
  8653. }
  8654. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8655. // b2 < 0, no intersection
  8656. if ( DdE1xQ < 0 ) {
  8657. return null;
  8658. }
  8659. // b1+b2 > 1, no intersection
  8660. if ( DdQxE2 + DdE1xQ > DdN ) {
  8661. return null;
  8662. }
  8663. // Line intersects triangle, check if ray does.
  8664. const QdN = - sign * _diff.dot( _normal$1 );
  8665. // t < 0, no intersection
  8666. if ( QdN < 0 ) {
  8667. return null;
  8668. }
  8669. // Ray intersects triangle.
  8670. return this.at( QdN / DdN, target );
  8671. }
  8672. /**
  8673. * Transforms this ray with the given 4x4 transformation matrix.
  8674. *
  8675. * @param {Matrix4} matrix4 - The transformation matrix.
  8676. * @return {Ray} A reference to this ray.
  8677. */
  8678. applyMatrix4( matrix4 ) {
  8679. this.origin.applyMatrix4( matrix4 );
  8680. this.direction.transformDirection( matrix4 );
  8681. return this;
  8682. }
  8683. /**
  8684. * Returns `true` if this ray is equal with the given one.
  8685. *
  8686. * @param {Ray} ray - The ray to test for equality.
  8687. * @return {boolean} Whether this ray is equal with the given one.
  8688. */
  8689. equals( ray ) {
  8690. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8691. }
  8692. /**
  8693. * Returns a new ray with copied values from this instance.
  8694. *
  8695. * @return {Ray} A clone of this instance.
  8696. */
  8697. clone() {
  8698. return new this.constructor().copy( this );
  8699. }
  8700. }
  8701. /**
  8702. * Represents a 4x4 matrix.
  8703. *
  8704. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8705. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8706. *
  8707. * This allows a 3D vector representing a point in 3D space to undergo
  8708. * transformations such as translation, rotation, shear, scale, reflection,
  8709. * orthogonal or perspective projection and so on, by being multiplied by the
  8710. * matrix. This is known as `applying` the matrix to the vector.
  8711. *
  8712. * A Note on Row-Major and Column-Major Ordering:
  8713. *
  8714. * The constructor and {@link Matrix3#set} method take arguments in
  8715. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8716. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8717. * This means that calling:
  8718. * ```js
  8719. * const m = new THREE.Matrix4();
  8720. * m.set( 11, 12, 13, 14,
  8721. * 21, 22, 23, 24,
  8722. * 31, 32, 33, 34,
  8723. * 41, 42, 43, 44 );
  8724. * ```
  8725. * will result in the elements array containing:
  8726. * ```js
  8727. * m.elements = [ 11, 21, 31, 41,
  8728. * 12, 22, 32, 42,
  8729. * 13, 23, 33, 43,
  8730. * 14, 24, 34, 44 ];
  8731. * ```
  8732. * and internally all calculations are performed using column-major ordering.
  8733. * However, as the actual ordering makes no difference mathematically and
  8734. * most people are used to thinking about matrices in row-major order, the
  8735. * three.js documentation shows matrices in row-major order. Just bear in
  8736. * mind that if you are reading the source code, you'll have to take the
  8737. * transpose of any matrices outlined here to make sense of the calculations.
  8738. */
  8739. class Matrix4 {
  8740. /**
  8741. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8742. * in row-major order. If no arguments are provided, the constructor
  8743. * initializes the matrix as an identity matrix.
  8744. *
  8745. * @param {number} [n11] - 1-1 matrix element.
  8746. * @param {number} [n12] - 1-2 matrix element.
  8747. * @param {number} [n13] - 1-3 matrix element.
  8748. * @param {number} [n14] - 1-4 matrix element.
  8749. * @param {number} [n21] - 2-1 matrix element.
  8750. * @param {number} [n22] - 2-2 matrix element.
  8751. * @param {number} [n23] - 2-3 matrix element.
  8752. * @param {number} [n24] - 2-4 matrix element.
  8753. * @param {number} [n31] - 3-1 matrix element.
  8754. * @param {number} [n32] - 3-2 matrix element.
  8755. * @param {number} [n33] - 3-3 matrix element.
  8756. * @param {number} [n34] - 3-4 matrix element.
  8757. * @param {number} [n41] - 4-1 matrix element.
  8758. * @param {number} [n42] - 4-2 matrix element.
  8759. * @param {number} [n43] - 4-3 matrix element.
  8760. * @param {number} [n44] - 4-4 matrix element.
  8761. */
  8762. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8763. /**
  8764. * This flag can be used for type testing.
  8765. *
  8766. * @type {boolean}
  8767. * @readonly
  8768. * @default true
  8769. */
  8770. Matrix4.prototype.isMatrix4 = true;
  8771. /**
  8772. * A column-major list of matrix values.
  8773. *
  8774. * @type {Array<number>}
  8775. */
  8776. this.elements = [
  8777. 1, 0, 0, 0,
  8778. 0, 1, 0, 0,
  8779. 0, 0, 1, 0,
  8780. 0, 0, 0, 1
  8781. ];
  8782. if ( n11 !== undefined ) {
  8783. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8784. }
  8785. }
  8786. /**
  8787. * Sets the elements of the matrix.The arguments are supposed to be
  8788. * in row-major order.
  8789. *
  8790. * @param {number} [n11] - 1-1 matrix element.
  8791. * @param {number} [n12] - 1-2 matrix element.
  8792. * @param {number} [n13] - 1-3 matrix element.
  8793. * @param {number} [n14] - 1-4 matrix element.
  8794. * @param {number} [n21] - 2-1 matrix element.
  8795. * @param {number} [n22] - 2-2 matrix element.
  8796. * @param {number} [n23] - 2-3 matrix element.
  8797. * @param {number} [n24] - 2-4 matrix element.
  8798. * @param {number} [n31] - 3-1 matrix element.
  8799. * @param {number} [n32] - 3-2 matrix element.
  8800. * @param {number} [n33] - 3-3 matrix element.
  8801. * @param {number} [n34] - 3-4 matrix element.
  8802. * @param {number} [n41] - 4-1 matrix element.
  8803. * @param {number} [n42] - 4-2 matrix element.
  8804. * @param {number} [n43] - 4-3 matrix element.
  8805. * @param {number} [n44] - 4-4 matrix element.
  8806. * @return {Matrix4} A reference to this matrix.
  8807. */
  8808. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8809. const te = this.elements;
  8810. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8811. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8812. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8813. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8814. return this;
  8815. }
  8816. /**
  8817. * Sets this matrix to the 4x4 identity matrix.
  8818. *
  8819. * @return {Matrix4} A reference to this matrix.
  8820. */
  8821. identity() {
  8822. this.set(
  8823. 1, 0, 0, 0,
  8824. 0, 1, 0, 0,
  8825. 0, 0, 1, 0,
  8826. 0, 0, 0, 1
  8827. );
  8828. return this;
  8829. }
  8830. /**
  8831. * Returns a matrix with copied values from this instance.
  8832. *
  8833. * @return {Matrix4} A clone of this instance.
  8834. */
  8835. clone() {
  8836. return new Matrix4().fromArray( this.elements );
  8837. }
  8838. /**
  8839. * Copies the values of the given matrix to this instance.
  8840. *
  8841. * @param {Matrix4} m - The matrix to copy.
  8842. * @return {Matrix4} A reference to this matrix.
  8843. */
  8844. copy( m ) {
  8845. const te = this.elements;
  8846. const me = m.elements;
  8847. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8848. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8849. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8850. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8851. return this;
  8852. }
  8853. /**
  8854. * Copies the translation component of the given matrix
  8855. * into this matrix's translation component.
  8856. *
  8857. * @param {Matrix4} m - The matrix to copy the translation component.
  8858. * @return {Matrix4} A reference to this matrix.
  8859. */
  8860. copyPosition( m ) {
  8861. const te = this.elements, me = m.elements;
  8862. te[ 12 ] = me[ 12 ];
  8863. te[ 13 ] = me[ 13 ];
  8864. te[ 14 ] = me[ 14 ];
  8865. return this;
  8866. }
  8867. /**
  8868. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8869. *
  8870. * @param {Matrix3} m - The 3x3 matrix.
  8871. * @return {Matrix4} A reference to this matrix.
  8872. */
  8873. setFromMatrix3( m ) {
  8874. const me = m.elements;
  8875. this.set(
  8876. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8877. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8878. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8879. 0, 0, 0, 1
  8880. );
  8881. return this;
  8882. }
  8883. /**
  8884. * Extracts the basis of this matrix into the three axis vectors provided.
  8885. *
  8886. * @param {Vector3} xAxis - The basis's x axis.
  8887. * @param {Vector3} yAxis - The basis's y axis.
  8888. * @param {Vector3} zAxis - The basis's z axis.
  8889. * @return {Matrix4} A reference to this matrix.
  8890. */
  8891. extractBasis( xAxis, yAxis, zAxis ) {
  8892. if ( this.determinant() === 0 ) {
  8893. xAxis.set( 1, 0, 0 );
  8894. yAxis.set( 0, 1, 0 );
  8895. zAxis.set( 0, 0, 1 );
  8896. return this;
  8897. }
  8898. xAxis.setFromMatrixColumn( this, 0 );
  8899. yAxis.setFromMatrixColumn( this, 1 );
  8900. zAxis.setFromMatrixColumn( this, 2 );
  8901. return this;
  8902. }
  8903. /**
  8904. * Sets the given basis vectors to this matrix.
  8905. *
  8906. * @param {Vector3} xAxis - The basis's x axis.
  8907. * @param {Vector3} yAxis - The basis's y axis.
  8908. * @param {Vector3} zAxis - The basis's z axis.
  8909. * @return {Matrix4} A reference to this matrix.
  8910. */
  8911. makeBasis( xAxis, yAxis, zAxis ) {
  8912. this.set(
  8913. xAxis.x, yAxis.x, zAxis.x, 0,
  8914. xAxis.y, yAxis.y, zAxis.y, 0,
  8915. xAxis.z, yAxis.z, zAxis.z, 0,
  8916. 0, 0, 0, 1
  8917. );
  8918. return this;
  8919. }
  8920. /**
  8921. * Extracts the rotation component of the given matrix
  8922. * into this matrix's rotation component.
  8923. *
  8924. * Note: This method does not support reflection matrices.
  8925. *
  8926. * @param {Matrix4} m - The matrix.
  8927. * @return {Matrix4} A reference to this matrix.
  8928. */
  8929. extractRotation( m ) {
  8930. if ( m.determinant() === 0 ) {
  8931. return this.identity();
  8932. }
  8933. const te = this.elements;
  8934. const me = m.elements;
  8935. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8936. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8937. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8938. te[ 0 ] = me[ 0 ] * scaleX;
  8939. te[ 1 ] = me[ 1 ] * scaleX;
  8940. te[ 2 ] = me[ 2 ] * scaleX;
  8941. te[ 3 ] = 0;
  8942. te[ 4 ] = me[ 4 ] * scaleY;
  8943. te[ 5 ] = me[ 5 ] * scaleY;
  8944. te[ 6 ] = me[ 6 ] * scaleY;
  8945. te[ 7 ] = 0;
  8946. te[ 8 ] = me[ 8 ] * scaleZ;
  8947. te[ 9 ] = me[ 9 ] * scaleZ;
  8948. te[ 10 ] = me[ 10 ] * scaleZ;
  8949. te[ 11 ] = 0;
  8950. te[ 12 ] = 0;
  8951. te[ 13 ] = 0;
  8952. te[ 14 ] = 0;
  8953. te[ 15 ] = 1;
  8954. return this;
  8955. }
  8956. /**
  8957. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8958. * the rotation specified by the given Euler angles. The rest of
  8959. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8960. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  8961. * for a complete list.
  8962. *
  8963. * @param {Euler} euler - The Euler angles.
  8964. * @return {Matrix4} A reference to this matrix.
  8965. */
  8966. makeRotationFromEuler( euler ) {
  8967. const te = this.elements;
  8968. const x = euler.x, y = euler.y, z = euler.z;
  8969. const a = Math.cos( x ), b = Math.sin( x );
  8970. const c = Math.cos( y ), d = Math.sin( y );
  8971. const e = Math.cos( z ), f = Math.sin( z );
  8972. if ( euler.order === 'XYZ' ) {
  8973. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8974. te[ 0 ] = c * e;
  8975. te[ 4 ] = - c * f;
  8976. te[ 8 ] = d;
  8977. te[ 1 ] = af + be * d;
  8978. te[ 5 ] = ae - bf * d;
  8979. te[ 9 ] = - b * c;
  8980. te[ 2 ] = bf - ae * d;
  8981. te[ 6 ] = be + af * d;
  8982. te[ 10 ] = a * c;
  8983. } else if ( euler.order === 'YXZ' ) {
  8984. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8985. te[ 0 ] = ce + df * b;
  8986. te[ 4 ] = de * b - cf;
  8987. te[ 8 ] = a * d;
  8988. te[ 1 ] = a * f;
  8989. te[ 5 ] = a * e;
  8990. te[ 9 ] = - b;
  8991. te[ 2 ] = cf * b - de;
  8992. te[ 6 ] = df + ce * b;
  8993. te[ 10 ] = a * c;
  8994. } else if ( euler.order === 'ZXY' ) {
  8995. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8996. te[ 0 ] = ce - df * b;
  8997. te[ 4 ] = - a * f;
  8998. te[ 8 ] = de + cf * b;
  8999. te[ 1 ] = cf + de * b;
  9000. te[ 5 ] = a * e;
  9001. te[ 9 ] = df - ce * b;
  9002. te[ 2 ] = - a * d;
  9003. te[ 6 ] = b;
  9004. te[ 10 ] = a * c;
  9005. } else if ( euler.order === 'ZYX' ) {
  9006. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9007. te[ 0 ] = c * e;
  9008. te[ 4 ] = be * d - af;
  9009. te[ 8 ] = ae * d + bf;
  9010. te[ 1 ] = c * f;
  9011. te[ 5 ] = bf * d + ae;
  9012. te[ 9 ] = af * d - be;
  9013. te[ 2 ] = - d;
  9014. te[ 6 ] = b * c;
  9015. te[ 10 ] = a * c;
  9016. } else if ( euler.order === 'YZX' ) {
  9017. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9018. te[ 0 ] = c * e;
  9019. te[ 4 ] = bd - ac * f;
  9020. te[ 8 ] = bc * f + ad;
  9021. te[ 1 ] = f;
  9022. te[ 5 ] = a * e;
  9023. te[ 9 ] = - b * e;
  9024. te[ 2 ] = - d * e;
  9025. te[ 6 ] = ad * f + bc;
  9026. te[ 10 ] = ac - bd * f;
  9027. } else if ( euler.order === 'XZY' ) {
  9028. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9029. te[ 0 ] = c * e;
  9030. te[ 4 ] = - f;
  9031. te[ 8 ] = d * e;
  9032. te[ 1 ] = ac * f + bd;
  9033. te[ 5 ] = a * e;
  9034. te[ 9 ] = ad * f - bc;
  9035. te[ 2 ] = bc * f - ad;
  9036. te[ 6 ] = b * e;
  9037. te[ 10 ] = bd * f + ac;
  9038. }
  9039. // bottom row
  9040. te[ 3 ] = 0;
  9041. te[ 7 ] = 0;
  9042. te[ 11 ] = 0;
  9043. // last column
  9044. te[ 12 ] = 0;
  9045. te[ 13 ] = 0;
  9046. te[ 14 ] = 0;
  9047. te[ 15 ] = 1;
  9048. return this;
  9049. }
  9050. /**
  9051. * Sets the rotation component of this matrix to the rotation specified by
  9052. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9053. * The rest of the matrix is set to the identity.
  9054. *
  9055. * @param {Quaternion} q - The Quaternion.
  9056. * @return {Matrix4} A reference to this matrix.
  9057. */
  9058. makeRotationFromQuaternion( q ) {
  9059. return this.compose( _zero, q, _one );
  9060. }
  9061. /**
  9062. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9063. * `target`, and oriented by the up-direction.
  9064. *
  9065. * @param {Vector3} eye - The eye vector.
  9066. * @param {Vector3} target - The target vector.
  9067. * @param {Vector3} up - The up vector.
  9068. * @return {Matrix4} A reference to this matrix.
  9069. */
  9070. lookAt( eye, target, up ) {
  9071. const te = this.elements;
  9072. _z.subVectors( eye, target );
  9073. if ( _z.lengthSq() === 0 ) {
  9074. // eye and target are in the same position
  9075. _z.z = 1;
  9076. }
  9077. _z.normalize();
  9078. _x.crossVectors( up, _z );
  9079. if ( _x.lengthSq() === 0 ) {
  9080. // up and z are parallel
  9081. if ( Math.abs( up.z ) === 1 ) {
  9082. _z.x += 0.0001;
  9083. } else {
  9084. _z.z += 0.0001;
  9085. }
  9086. _z.normalize();
  9087. _x.crossVectors( up, _z );
  9088. }
  9089. _x.normalize();
  9090. _y.crossVectors( _z, _x );
  9091. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9092. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9093. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9094. return this;
  9095. }
  9096. /**
  9097. * Post-multiplies this matrix by the given 4x4 matrix.
  9098. *
  9099. * @param {Matrix4} m - The matrix to multiply with.
  9100. * @return {Matrix4} A reference to this matrix.
  9101. */
  9102. multiply( m ) {
  9103. return this.multiplyMatrices( this, m );
  9104. }
  9105. /**
  9106. * Pre-multiplies this matrix by the given 4x4 matrix.
  9107. *
  9108. * @param {Matrix4} m - The matrix to multiply with.
  9109. * @return {Matrix4} A reference to this matrix.
  9110. */
  9111. premultiply( m ) {
  9112. return this.multiplyMatrices( m, this );
  9113. }
  9114. /**
  9115. * Multiples the given 4x4 matrices and stores the result
  9116. * in this matrix.
  9117. *
  9118. * @param {Matrix4} a - The first matrix.
  9119. * @param {Matrix4} b - The second matrix.
  9120. * @return {Matrix4} A reference to this matrix.
  9121. */
  9122. multiplyMatrices( a, b ) {
  9123. const ae = a.elements;
  9124. const be = b.elements;
  9125. const te = this.elements;
  9126. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9127. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9128. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9129. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9130. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9131. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9132. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9133. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9134. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9135. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9136. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9137. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9138. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9139. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9140. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9141. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9142. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9143. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9144. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9145. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9146. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9147. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9148. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9149. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9150. return this;
  9151. }
  9152. /**
  9153. * Multiplies every component of the matrix by the given scalar.
  9154. *
  9155. * @param {number} s - The scalar.
  9156. * @return {Matrix4} A reference to this matrix.
  9157. */
  9158. multiplyScalar( s ) {
  9159. const te = this.elements;
  9160. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9161. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9162. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9163. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9164. return this;
  9165. }
  9166. /**
  9167. * Computes and returns the determinant of this matrix.
  9168. *
  9169. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9170. *
  9171. * @return {number} The determinant.
  9172. */
  9173. determinant() {
  9174. const te = this.elements;
  9175. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9176. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9177. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9178. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9179. const t11 = n23 * n34 - n24 * n33;
  9180. const t12 = n22 * n34 - n24 * n32;
  9181. const t13 = n22 * n33 - n23 * n32;
  9182. const t21 = n21 * n34 - n24 * n31;
  9183. const t22 = n21 * n33 - n23 * n31;
  9184. const t23 = n21 * n32 - n22 * n31;
  9185. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9186. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9187. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9188. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9189. }
  9190. /**
  9191. * Transposes this matrix in place.
  9192. *
  9193. * @return {Matrix4} A reference to this matrix.
  9194. */
  9195. transpose() {
  9196. const te = this.elements;
  9197. let tmp;
  9198. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9199. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9200. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9201. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9202. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9203. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9204. return this;
  9205. }
  9206. /**
  9207. * Sets the position component for this matrix from the given vector,
  9208. * without affecting the rest of the matrix.
  9209. *
  9210. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9211. * @param {number} y - The y component of the vector.
  9212. * @param {number} z - The z component of the vector.
  9213. * @return {Matrix4} A reference to this matrix.
  9214. */
  9215. setPosition( x, y, z ) {
  9216. const te = this.elements;
  9217. if ( x.isVector3 ) {
  9218. te[ 12 ] = x.x;
  9219. te[ 13 ] = x.y;
  9220. te[ 14 ] = x.z;
  9221. } else {
  9222. te[ 12 ] = x;
  9223. te[ 13 ] = y;
  9224. te[ 14 ] = z;
  9225. }
  9226. return this;
  9227. }
  9228. /**
  9229. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9230. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9231. * a zero matrix instead.
  9232. *
  9233. * @return {Matrix4} A reference to this matrix.
  9234. */
  9235. invert() {
  9236. // based on https://github.com/toji/gl-matrix
  9237. const te = this.elements,
  9238. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9239. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9240. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9241. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9242. t1 = n11 * n22 - n21 * n12,
  9243. t2 = n11 * n32 - n31 * n12,
  9244. t3 = n11 * n42 - n41 * n12,
  9245. t4 = n21 * n32 - n31 * n22,
  9246. t5 = n21 * n42 - n41 * n22,
  9247. t6 = n31 * n42 - n41 * n32,
  9248. t7 = n13 * n24 - n23 * n14,
  9249. t8 = n13 * n34 - n33 * n14,
  9250. t9 = n13 * n44 - n43 * n14,
  9251. t10 = n23 * n34 - n33 * n24,
  9252. t11 = n23 * n44 - n43 * n24,
  9253. t12 = n33 * n44 - n43 * n34;
  9254. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  9255. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9256. const detInv = 1 / det;
  9257. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  9258. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  9259. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  9260. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  9261. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  9262. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  9263. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  9264. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  9265. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  9266. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  9267. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  9268. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  9269. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  9270. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  9271. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  9272. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  9273. return this;
  9274. }
  9275. /**
  9276. * Multiplies the columns of this matrix by the given vector.
  9277. *
  9278. * @param {Vector3} v - The scale vector.
  9279. * @return {Matrix4} A reference to this matrix.
  9280. */
  9281. scale( v ) {
  9282. const te = this.elements;
  9283. const x = v.x, y = v.y, z = v.z;
  9284. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9285. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9286. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9287. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9288. return this;
  9289. }
  9290. /**
  9291. * Gets the maximum scale value of the three axes.
  9292. *
  9293. * @return {number} The maximum scale.
  9294. */
  9295. getMaxScaleOnAxis() {
  9296. const te = this.elements;
  9297. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9298. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9299. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9300. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9301. }
  9302. /**
  9303. * Sets this matrix as a translation transform from the given vector.
  9304. *
  9305. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9306. * @param {number} y - The amount to translate in the Y axis.
  9307. * @param {number} z - The amount to translate in the z axis.
  9308. * @return {Matrix4} A reference to this matrix.
  9309. */
  9310. makeTranslation( x, y, z ) {
  9311. if ( x.isVector3 ) {
  9312. this.set(
  9313. 1, 0, 0, x.x,
  9314. 0, 1, 0, x.y,
  9315. 0, 0, 1, x.z,
  9316. 0, 0, 0, 1
  9317. );
  9318. } else {
  9319. this.set(
  9320. 1, 0, 0, x,
  9321. 0, 1, 0, y,
  9322. 0, 0, 1, z,
  9323. 0, 0, 0, 1
  9324. );
  9325. }
  9326. return this;
  9327. }
  9328. /**
  9329. * Sets this matrix as a rotational transformation around the X axis by
  9330. * the given angle.
  9331. *
  9332. * @param {number} theta - The rotation in radians.
  9333. * @return {Matrix4} A reference to this matrix.
  9334. */
  9335. makeRotationX( theta ) {
  9336. const c = Math.cos( theta ), s = Math.sin( theta );
  9337. this.set(
  9338. 1, 0, 0, 0,
  9339. 0, c, - s, 0,
  9340. 0, s, c, 0,
  9341. 0, 0, 0, 1
  9342. );
  9343. return this;
  9344. }
  9345. /**
  9346. * Sets this matrix as a rotational transformation around the Y axis by
  9347. * the given angle.
  9348. *
  9349. * @param {number} theta - The rotation in radians.
  9350. * @return {Matrix4} A reference to this matrix.
  9351. */
  9352. makeRotationY( theta ) {
  9353. const c = Math.cos( theta ), s = Math.sin( theta );
  9354. this.set(
  9355. c, 0, s, 0,
  9356. 0, 1, 0, 0,
  9357. - s, 0, c, 0,
  9358. 0, 0, 0, 1
  9359. );
  9360. return this;
  9361. }
  9362. /**
  9363. * Sets this matrix as a rotational transformation around the Z axis by
  9364. * the given angle.
  9365. *
  9366. * @param {number} theta - The rotation in radians.
  9367. * @return {Matrix4} A reference to this matrix.
  9368. */
  9369. makeRotationZ( theta ) {
  9370. const c = Math.cos( theta ), s = Math.sin( theta );
  9371. this.set(
  9372. c, - s, 0, 0,
  9373. s, c, 0, 0,
  9374. 0, 0, 1, 0,
  9375. 0, 0, 0, 1
  9376. );
  9377. return this;
  9378. }
  9379. /**
  9380. * Sets this matrix as a rotational transformation around the given axis by
  9381. * the given angle.
  9382. *
  9383. * This is a somewhat controversial but mathematically sound alternative to
  9384. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9385. *
  9386. * @param {Vector3} axis - The normalized rotation axis.
  9387. * @param {number} angle - The rotation in radians.
  9388. * @return {Matrix4} A reference to this matrix.
  9389. */
  9390. makeRotationAxis( axis, angle ) {
  9391. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9392. const c = Math.cos( angle );
  9393. const s = Math.sin( angle );
  9394. const t = 1 - c;
  9395. const x = axis.x, y = axis.y, z = axis.z;
  9396. const tx = t * x, ty = t * y;
  9397. this.set(
  9398. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9399. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9400. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9401. 0, 0, 0, 1
  9402. );
  9403. return this;
  9404. }
  9405. /**
  9406. * Sets this matrix as a scale transformation.
  9407. *
  9408. * @param {number} x - The amount to scale in the X axis.
  9409. * @param {number} y - The amount to scale in the Y axis.
  9410. * @param {number} z - The amount to scale in the Z axis.
  9411. * @return {Matrix4} A reference to this matrix.
  9412. */
  9413. makeScale( x, y, z ) {
  9414. this.set(
  9415. x, 0, 0, 0,
  9416. 0, y, 0, 0,
  9417. 0, 0, z, 0,
  9418. 0, 0, 0, 1
  9419. );
  9420. return this;
  9421. }
  9422. /**
  9423. * Sets this matrix as a shear transformation.
  9424. *
  9425. * @param {number} xy - The amount to shear X by Y.
  9426. * @param {number} xz - The amount to shear X by Z.
  9427. * @param {number} yx - The amount to shear Y by X.
  9428. * @param {number} yz - The amount to shear Y by Z.
  9429. * @param {number} zx - The amount to shear Z by X.
  9430. * @param {number} zy - The amount to shear Z by Y.
  9431. * @return {Matrix4} A reference to this matrix.
  9432. */
  9433. makeShear( xy, xz, yx, yz, zx, zy ) {
  9434. this.set(
  9435. 1, yx, zx, 0,
  9436. xy, 1, zy, 0,
  9437. xz, yz, 1, 0,
  9438. 0, 0, 0, 1
  9439. );
  9440. return this;
  9441. }
  9442. /**
  9443. * Sets this matrix to the transformation composed of the given position,
  9444. * rotation (Quaternion) and scale.
  9445. *
  9446. * @param {Vector3} position - The position vector.
  9447. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9448. * @param {Vector3} scale - The scale vector.
  9449. * @return {Matrix4} A reference to this matrix.
  9450. */
  9451. compose( position, quaternion, scale ) {
  9452. const te = this.elements;
  9453. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9454. const x2 = x + x, y2 = y + y, z2 = z + z;
  9455. const xx = x * x2, xy = x * y2, xz = x * z2;
  9456. const yy = y * y2, yz = y * z2, zz = z * z2;
  9457. const wx = w * x2, wy = w * y2, wz = w * z2;
  9458. const sx = scale.x, sy = scale.y, sz = scale.z;
  9459. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9460. te[ 1 ] = ( xy + wz ) * sx;
  9461. te[ 2 ] = ( xz - wy ) * sx;
  9462. te[ 3 ] = 0;
  9463. te[ 4 ] = ( xy - wz ) * sy;
  9464. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9465. te[ 6 ] = ( yz + wx ) * sy;
  9466. te[ 7 ] = 0;
  9467. te[ 8 ] = ( xz + wy ) * sz;
  9468. te[ 9 ] = ( yz - wx ) * sz;
  9469. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9470. te[ 11 ] = 0;
  9471. te[ 12 ] = position.x;
  9472. te[ 13 ] = position.y;
  9473. te[ 14 ] = position.z;
  9474. te[ 15 ] = 1;
  9475. return this;
  9476. }
  9477. /**
  9478. * Decomposes this matrix into its position, rotation and scale components
  9479. * and provides the result in the given objects.
  9480. *
  9481. * Note: Not all matrices are decomposable in this way. For example, if an
  9482. * object has a non-uniformly scaled parent, then the object's world matrix
  9483. * may not be decomposable, and this method may not be appropriate.
  9484. *
  9485. * @param {Vector3} position - The position vector.
  9486. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9487. * @param {Vector3} scale - The scale vector.
  9488. * @return {Matrix4} A reference to this matrix.
  9489. */
  9490. decompose( position, quaternion, scale ) {
  9491. const te = this.elements;
  9492. position.x = te[ 12 ];
  9493. position.y = te[ 13 ];
  9494. position.z = te[ 14 ];
  9495. const det = this.determinant();
  9496. if ( det === 0 ) {
  9497. scale.set( 1, 1, 1 );
  9498. quaternion.identity();
  9499. return this;
  9500. }
  9501. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9502. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9503. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9504. // if determinant is negative, we need to invert one scale
  9505. if ( det < 0 ) sx = - sx;
  9506. // scale the rotation part
  9507. _m1$4.copy( this );
  9508. const invSX = 1 / sx;
  9509. const invSY = 1 / sy;
  9510. const invSZ = 1 / sz;
  9511. _m1$4.elements[ 0 ] *= invSX;
  9512. _m1$4.elements[ 1 ] *= invSX;
  9513. _m1$4.elements[ 2 ] *= invSX;
  9514. _m1$4.elements[ 4 ] *= invSY;
  9515. _m1$4.elements[ 5 ] *= invSY;
  9516. _m1$4.elements[ 6 ] *= invSY;
  9517. _m1$4.elements[ 8 ] *= invSZ;
  9518. _m1$4.elements[ 9 ] *= invSZ;
  9519. _m1$4.elements[ 10 ] *= invSZ;
  9520. quaternion.setFromRotationMatrix( _m1$4 );
  9521. scale.x = sx;
  9522. scale.y = sy;
  9523. scale.z = sz;
  9524. return this;
  9525. }
  9526. /**
  9527. * Creates a perspective projection matrix. This is used internally by
  9528. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9529. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9530. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9531. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9532. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9533. * @param {number} near - The distance from the camera to the near plane.
  9534. * @param {number} far - The distance from the camera to the far plane.
  9535. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9536. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9537. * @return {Matrix4} A reference to this matrix.
  9538. */
  9539. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9540. const te = this.elements;
  9541. const x = 2 * near / ( right - left );
  9542. const y = 2 * near / ( top - bottom );
  9543. const a = ( right + left ) / ( right - left );
  9544. const b = ( top + bottom ) / ( top - bottom );
  9545. let c, d;
  9546. if ( reversedDepth ) {
  9547. c = near / ( far - near );
  9548. d = ( far * near ) / ( far - near );
  9549. } else {
  9550. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9551. c = - ( far + near ) / ( far - near );
  9552. d = ( -2 * far * near ) / ( far - near );
  9553. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9554. c = - far / ( far - near );
  9555. d = ( - far * near ) / ( far - near );
  9556. } else {
  9557. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9558. }
  9559. }
  9560. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9561. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9562. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9563. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9564. return this;
  9565. }
  9566. /**
  9567. * Creates a orthographic projection matrix. This is used internally by
  9568. * {@link OrthographicCamera#updateProjectionMatrix}.
  9569. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9570. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9571. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9572. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9573. * @param {number} near - The distance from the camera to the near plane.
  9574. * @param {number} far - The distance from the camera to the far plane.
  9575. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9576. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9577. * @return {Matrix4} A reference to this matrix.
  9578. */
  9579. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9580. const te = this.elements;
  9581. const x = 2 / ( right - left );
  9582. const y = 2 / ( top - bottom );
  9583. const a = - ( right + left ) / ( right - left );
  9584. const b = - ( top + bottom ) / ( top - bottom );
  9585. let c, d;
  9586. if ( reversedDepth ) {
  9587. c = 1 / ( far - near );
  9588. d = far / ( far - near );
  9589. } else {
  9590. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9591. c = -2 / ( far - near );
  9592. d = - ( far + near ) / ( far - near );
  9593. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9594. c = -1 / ( far - near );
  9595. d = - near / ( far - near );
  9596. } else {
  9597. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9598. }
  9599. }
  9600. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9601. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9602. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9603. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9604. return this;
  9605. }
  9606. /**
  9607. * Returns `true` if this matrix is equal with the given one.
  9608. *
  9609. * @param {Matrix4} matrix - The matrix to test for equality.
  9610. * @return {boolean} Whether this matrix is equal with the given one.
  9611. */
  9612. equals( matrix ) {
  9613. const te = this.elements;
  9614. const me = matrix.elements;
  9615. for ( let i = 0; i < 16; i ++ ) {
  9616. if ( te[ i ] !== me[ i ] ) return false;
  9617. }
  9618. return true;
  9619. }
  9620. /**
  9621. * Sets the elements of the matrix from the given array.
  9622. *
  9623. * @param {Array<number>} array - The matrix elements in column-major order.
  9624. * @param {number} [offset=0] - Index of the first element in the array.
  9625. * @return {Matrix4} A reference to this matrix.
  9626. */
  9627. fromArray( array, offset = 0 ) {
  9628. for ( let i = 0; i < 16; i ++ ) {
  9629. this.elements[ i ] = array[ i + offset ];
  9630. }
  9631. return this;
  9632. }
  9633. /**
  9634. * Writes the elements of this matrix to the given array. If no array is provided,
  9635. * the method returns a new instance.
  9636. *
  9637. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9638. * @param {number} [offset=0] - Index of the first element in the array.
  9639. * @return {Array<number>} The matrix elements in column-major order.
  9640. */
  9641. toArray( array = [], offset = 0 ) {
  9642. const te = this.elements;
  9643. array[ offset ] = te[ 0 ];
  9644. array[ offset + 1 ] = te[ 1 ];
  9645. array[ offset + 2 ] = te[ 2 ];
  9646. array[ offset + 3 ] = te[ 3 ];
  9647. array[ offset + 4 ] = te[ 4 ];
  9648. array[ offset + 5 ] = te[ 5 ];
  9649. array[ offset + 6 ] = te[ 6 ];
  9650. array[ offset + 7 ] = te[ 7 ];
  9651. array[ offset + 8 ] = te[ 8 ];
  9652. array[ offset + 9 ] = te[ 9 ];
  9653. array[ offset + 10 ] = te[ 10 ];
  9654. array[ offset + 11 ] = te[ 11 ];
  9655. array[ offset + 12 ] = te[ 12 ];
  9656. array[ offset + 13 ] = te[ 13 ];
  9657. array[ offset + 14 ] = te[ 14 ];
  9658. array[ offset + 15 ] = te[ 15 ];
  9659. return array;
  9660. }
  9661. }
  9662. const _v1$5 = /*@__PURE__*/ new Vector3();
  9663. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9664. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9665. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9666. const _x = /*@__PURE__*/ new Vector3();
  9667. const _y = /*@__PURE__*/ new Vector3();
  9668. const _z = /*@__PURE__*/ new Vector3();
  9669. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9670. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9671. /**
  9672. * A class representing Euler angles.
  9673. *
  9674. * Euler angles describe a rotational transformation by rotating an object on
  9675. * its various axes in specified amounts per axis, and a specified axis
  9676. * order.
  9677. *
  9678. * Iterating through an instance will yield its components (x, y, z,
  9679. * order) in the corresponding order.
  9680. *
  9681. * ```js
  9682. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9683. * const b = new THREE.Vector3( 1, 0, 1 );
  9684. * b.applyEuler(a);
  9685. * ```
  9686. */
  9687. class Euler {
  9688. /**
  9689. * Constructs a new euler instance.
  9690. *
  9691. * @param {number} [x=0] - The angle of the x axis in radians.
  9692. * @param {number} [y=0] - The angle of the y axis in radians.
  9693. * @param {number} [z=0] - The angle of the z axis in radians.
  9694. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9695. */
  9696. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9697. /**
  9698. * This flag can be used for type testing.
  9699. *
  9700. * @type {boolean}
  9701. * @readonly
  9702. * @default true
  9703. */
  9704. this.isEuler = true;
  9705. this._x = x;
  9706. this._y = y;
  9707. this._z = z;
  9708. this._order = order;
  9709. }
  9710. /**
  9711. * The angle of the x axis in radians.
  9712. *
  9713. * @type {number}
  9714. * @default 0
  9715. */
  9716. get x() {
  9717. return this._x;
  9718. }
  9719. set x( value ) {
  9720. this._x = value;
  9721. this._onChangeCallback();
  9722. }
  9723. /**
  9724. * The angle of the y axis in radians.
  9725. *
  9726. * @type {number}
  9727. * @default 0
  9728. */
  9729. get y() {
  9730. return this._y;
  9731. }
  9732. set y( value ) {
  9733. this._y = value;
  9734. this._onChangeCallback();
  9735. }
  9736. /**
  9737. * The angle of the z axis in radians.
  9738. *
  9739. * @type {number}
  9740. * @default 0
  9741. */
  9742. get z() {
  9743. return this._z;
  9744. }
  9745. set z( value ) {
  9746. this._z = value;
  9747. this._onChangeCallback();
  9748. }
  9749. /**
  9750. * A string representing the order that the rotations are applied.
  9751. *
  9752. * @type {string}
  9753. * @default 'XYZ'
  9754. */
  9755. get order() {
  9756. return this._order;
  9757. }
  9758. set order( value ) {
  9759. this._order = value;
  9760. this._onChangeCallback();
  9761. }
  9762. /**
  9763. * Sets the Euler components.
  9764. *
  9765. * @param {number} x - The angle of the x axis in radians.
  9766. * @param {number} y - The angle of the y axis in radians.
  9767. * @param {number} z - The angle of the z axis in radians.
  9768. * @param {string} [order] - A string representing the order that the rotations are applied.
  9769. * @return {Euler} A reference to this Euler instance.
  9770. */
  9771. set( x, y, z, order = this._order ) {
  9772. this._x = x;
  9773. this._y = y;
  9774. this._z = z;
  9775. this._order = order;
  9776. this._onChangeCallback();
  9777. return this;
  9778. }
  9779. /**
  9780. * Returns a new Euler instance with copied values from this instance.
  9781. *
  9782. * @return {Euler} A clone of this instance.
  9783. */
  9784. clone() {
  9785. return new this.constructor( this._x, this._y, this._z, this._order );
  9786. }
  9787. /**
  9788. * Copies the values of the given Euler instance to this instance.
  9789. *
  9790. * @param {Euler} euler - The Euler instance to copy.
  9791. * @return {Euler} A reference to this Euler instance.
  9792. */
  9793. copy( euler ) {
  9794. this._x = euler._x;
  9795. this._y = euler._y;
  9796. this._z = euler._z;
  9797. this._order = euler._order;
  9798. this._onChangeCallback();
  9799. return this;
  9800. }
  9801. /**
  9802. * Sets the angles of this Euler instance from a pure rotation matrix.
  9803. *
  9804. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9805. * @param {string} [order] - A string representing the order that the rotations are applied.
  9806. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9807. * @return {Euler} A reference to this Euler instance.
  9808. */
  9809. setFromRotationMatrix( m, order = this._order, update = true ) {
  9810. const te = m.elements;
  9811. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9812. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9813. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9814. switch ( order ) {
  9815. case 'XYZ':
  9816. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9817. if ( Math.abs( m13 ) < 0.9999999 ) {
  9818. this._x = Math.atan2( - m23, m33 );
  9819. this._z = Math.atan2( - m12, m11 );
  9820. } else {
  9821. this._x = Math.atan2( m32, m22 );
  9822. this._z = 0;
  9823. }
  9824. break;
  9825. case 'YXZ':
  9826. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9827. if ( Math.abs( m23 ) < 0.9999999 ) {
  9828. this._y = Math.atan2( m13, m33 );
  9829. this._z = Math.atan2( m21, m22 );
  9830. } else {
  9831. this._y = Math.atan2( - m31, m11 );
  9832. this._z = 0;
  9833. }
  9834. break;
  9835. case 'ZXY':
  9836. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9837. if ( Math.abs( m32 ) < 0.9999999 ) {
  9838. this._y = Math.atan2( - m31, m33 );
  9839. this._z = Math.atan2( - m12, m22 );
  9840. } else {
  9841. this._y = 0;
  9842. this._z = Math.atan2( m21, m11 );
  9843. }
  9844. break;
  9845. case 'ZYX':
  9846. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9847. if ( Math.abs( m31 ) < 0.9999999 ) {
  9848. this._x = Math.atan2( m32, m33 );
  9849. this._z = Math.atan2( m21, m11 );
  9850. } else {
  9851. this._x = 0;
  9852. this._z = Math.atan2( - m12, m22 );
  9853. }
  9854. break;
  9855. case 'YZX':
  9856. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9857. if ( Math.abs( m21 ) < 0.9999999 ) {
  9858. this._x = Math.atan2( - m23, m22 );
  9859. this._y = Math.atan2( - m31, m11 );
  9860. } else {
  9861. this._x = 0;
  9862. this._y = Math.atan2( m13, m33 );
  9863. }
  9864. break;
  9865. case 'XZY':
  9866. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9867. if ( Math.abs( m12 ) < 0.9999999 ) {
  9868. this._x = Math.atan2( m32, m22 );
  9869. this._y = Math.atan2( m13, m11 );
  9870. } else {
  9871. this._x = Math.atan2( - m23, m33 );
  9872. this._y = 0;
  9873. }
  9874. break;
  9875. default:
  9876. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9877. }
  9878. this._order = order;
  9879. if ( update === true ) this._onChangeCallback();
  9880. return this;
  9881. }
  9882. /**
  9883. * Sets the angles of this Euler instance from a normalized quaternion.
  9884. *
  9885. * @param {Quaternion} q - A normalized Quaternion.
  9886. * @param {string} [order] - A string representing the order that the rotations are applied.
  9887. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9888. * @return {Euler} A reference to this Euler instance.
  9889. */
  9890. setFromQuaternion( q, order, update ) {
  9891. _matrix$2.makeRotationFromQuaternion( q );
  9892. return this.setFromRotationMatrix( _matrix$2, order, update );
  9893. }
  9894. /**
  9895. * Sets the angles of this Euler instance from the given vector.
  9896. *
  9897. * @param {Vector3} v - The vector.
  9898. * @param {string} [order] - A string representing the order that the rotations are applied.
  9899. * @return {Euler} A reference to this Euler instance.
  9900. */
  9901. setFromVector3( v, order = this._order ) {
  9902. return this.set( v.x, v.y, v.z, order );
  9903. }
  9904. /**
  9905. * Resets the euler angle with a new order by creating a quaternion from this
  9906. * euler angle and then setting this euler angle with the quaternion and the
  9907. * new order.
  9908. *
  9909. * Warning: This discards revolution information.
  9910. *
  9911. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9912. * @return {Euler} A reference to this Euler instance.
  9913. */
  9914. reorder( newOrder ) {
  9915. _quaternion$3.setFromEuler( this );
  9916. return this.setFromQuaternion( _quaternion$3, newOrder );
  9917. }
  9918. /**
  9919. * Returns `true` if this Euler instance is equal with the given one.
  9920. *
  9921. * @param {Euler} euler - The Euler instance to test for equality.
  9922. * @return {boolean} Whether this Euler instance is equal with the given one.
  9923. */
  9924. equals( euler ) {
  9925. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9926. }
  9927. /**
  9928. * Sets this Euler instance's components to values from the given array. The first three
  9929. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9930. * defines the Euler order.
  9931. *
  9932. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9933. * @return {Euler} A reference to this Euler instance.
  9934. */
  9935. fromArray( array ) {
  9936. this._x = array[ 0 ];
  9937. this._y = array[ 1 ];
  9938. this._z = array[ 2 ];
  9939. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9940. this._onChangeCallback();
  9941. return this;
  9942. }
  9943. /**
  9944. * Writes the components of this Euler instance to the given array. If no array is provided,
  9945. * the method returns a new instance.
  9946. *
  9947. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9948. * @param {number} [offset=0] - Index of the first element in the array.
  9949. * @return {Array<number,number,number,string>} The Euler components.
  9950. */
  9951. toArray( array = [], offset = 0 ) {
  9952. array[ offset ] = this._x;
  9953. array[ offset + 1 ] = this._y;
  9954. array[ offset + 2 ] = this._z;
  9955. array[ offset + 3 ] = this._order;
  9956. return array;
  9957. }
  9958. _onChange( callback ) {
  9959. this._onChangeCallback = callback;
  9960. return this;
  9961. }
  9962. _onChangeCallback() {}
  9963. *[ Symbol.iterator ]() {
  9964. yield this._x;
  9965. yield this._y;
  9966. yield this._z;
  9967. yield this._order;
  9968. }
  9969. }
  9970. /**
  9971. * The default Euler angle order.
  9972. *
  9973. * @static
  9974. * @type {string}
  9975. * @default 'XYZ'
  9976. */
  9977. Euler.DEFAULT_ORDER = 'XYZ';
  9978. /**
  9979. * A layers object assigns an 3D object to 1 or more of 32
  9980. * layers numbered `0` to `31` - internally the layers are stored as a
  9981. * bit mask], and by default all 3D objects are a member of layer `0`.
  9982. *
  9983. * This can be used to control visibility - an object must share a layer with
  9984. * a camera to be visible when that camera's view is
  9985. * rendered.
  9986. *
  9987. * All classes that inherit from {@link Object3D} have an `layers` property which
  9988. * is an instance of this class.
  9989. */
  9990. class Layers {
  9991. /**
  9992. * Constructs a new layers instance, with membership
  9993. * initially set to layer `0`.
  9994. */
  9995. constructor() {
  9996. /**
  9997. * A bit mask storing which of the 32 layers this layers object is currently
  9998. * a member of.
  9999. *
  10000. * @type {number}
  10001. */
  10002. this.mask = 1 | 0;
  10003. }
  10004. /**
  10005. * Sets membership to the given layer, and remove membership all other layers.
  10006. *
  10007. * @param {number} layer - The layer to set.
  10008. */
  10009. set( layer ) {
  10010. this.mask = ( 1 << layer | 0 ) >>> 0;
  10011. }
  10012. /**
  10013. * Adds membership of the given layer.
  10014. *
  10015. * @param {number} layer - The layer to enable.
  10016. */
  10017. enable( layer ) {
  10018. this.mask |= 1 << layer | 0;
  10019. }
  10020. /**
  10021. * Adds membership to all layers.
  10022. */
  10023. enableAll() {
  10024. this.mask = 0xffffffff | 0;
  10025. }
  10026. /**
  10027. * Toggles the membership of the given layer.
  10028. *
  10029. * @param {number} layer - The layer to toggle.
  10030. */
  10031. toggle( layer ) {
  10032. this.mask ^= 1 << layer | 0;
  10033. }
  10034. /**
  10035. * Removes membership of the given layer.
  10036. *
  10037. * @param {number} layer - The layer to enable.
  10038. */
  10039. disable( layer ) {
  10040. this.mask &= ~ ( 1 << layer | 0 );
  10041. }
  10042. /**
  10043. * Removes the membership from all layers.
  10044. */
  10045. disableAll() {
  10046. this.mask = 0;
  10047. }
  10048. /**
  10049. * Returns `true` if this and the given layers object have at least one
  10050. * layer in common.
  10051. *
  10052. * @param {Layers} layers - The layers to test.
  10053. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10054. */
  10055. test( layers ) {
  10056. return ( this.mask & layers.mask ) !== 0;
  10057. }
  10058. /**
  10059. * Returns `true` if the given layer is enabled.
  10060. *
  10061. * @param {number} layer - The layer to test.
  10062. * @return {boolean } Whether the given layer is enabled or not.
  10063. */
  10064. isEnabled( layer ) {
  10065. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10066. }
  10067. }
  10068. let _object3DId = 0;
  10069. const _v1$4 = /*@__PURE__*/ new Vector3();
  10070. const _q1 = /*@__PURE__*/ new Quaternion();
  10071. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10072. const _target = /*@__PURE__*/ new Vector3();
  10073. const _position$3 = /*@__PURE__*/ new Vector3();
  10074. const _scale$2 = /*@__PURE__*/ new Vector3();
  10075. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10076. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10077. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10078. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10079. /**
  10080. * Fires when the object has been added to its parent object.
  10081. *
  10082. * @event Object3D#added
  10083. * @type {Object}
  10084. */
  10085. const _addedEvent = { type: 'added' };
  10086. /**
  10087. * Fires when the object has been removed from its parent object.
  10088. *
  10089. * @event Object3D#removed
  10090. * @type {Object}
  10091. */
  10092. const _removedEvent = { type: 'removed' };
  10093. /**
  10094. * Fires when a new child object has been added.
  10095. *
  10096. * @event Object3D#childadded
  10097. * @type {Object}
  10098. */
  10099. const _childaddedEvent = { type: 'childadded', child: null };
  10100. /**
  10101. * Fires when a child object has been removed.
  10102. *
  10103. * @event Object3D#childremoved
  10104. * @type {Object}
  10105. */
  10106. const _childremovedEvent = { type: 'childremoved', child: null };
  10107. /**
  10108. * This is the base class for most objects in three.js and provides a set of
  10109. * properties and methods for manipulating objects in 3D space.
  10110. *
  10111. * @augments EventDispatcher
  10112. */
  10113. class Object3D extends EventDispatcher {
  10114. /**
  10115. * Constructs a new 3D object.
  10116. */
  10117. constructor() {
  10118. super();
  10119. /**
  10120. * This flag can be used for type testing.
  10121. *
  10122. * @type {boolean}
  10123. * @readonly
  10124. * @default true
  10125. */
  10126. this.isObject3D = true;
  10127. /**
  10128. * The ID of the 3D object.
  10129. *
  10130. * @name Object3D#id
  10131. * @type {number}
  10132. * @readonly
  10133. */
  10134. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10135. /**
  10136. * The UUID of the 3D object.
  10137. *
  10138. * @type {string}
  10139. * @readonly
  10140. */
  10141. this.uuid = generateUUID();
  10142. /**
  10143. * The name of the 3D object.
  10144. *
  10145. * @type {string}
  10146. */
  10147. this.name = '';
  10148. /**
  10149. * The type property is used for detecting the object type
  10150. * in context of serialization/deserialization.
  10151. *
  10152. * @type {string}
  10153. * @readonly
  10154. */
  10155. this.type = 'Object3D';
  10156. /**
  10157. * A reference to the parent object.
  10158. *
  10159. * @type {?Object3D}
  10160. * @default null
  10161. */
  10162. this.parent = null;
  10163. /**
  10164. * An array holding the child 3D objects of this instance.
  10165. *
  10166. * @type {Array<Object3D>}
  10167. */
  10168. this.children = [];
  10169. /**
  10170. * Defines the `up` direction of the 3D object which influences
  10171. * the orientation via methods like {@link Object3D#lookAt}.
  10172. *
  10173. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10174. *
  10175. * @type {Vector3}
  10176. */
  10177. this.up = Object3D.DEFAULT_UP.clone();
  10178. const position = new Vector3();
  10179. const rotation = new Euler();
  10180. const quaternion = new Quaternion();
  10181. const scale = new Vector3( 1, 1, 1 );
  10182. function onRotationChange() {
  10183. quaternion.setFromEuler( rotation, false );
  10184. }
  10185. function onQuaternionChange() {
  10186. rotation.setFromQuaternion( quaternion, undefined, false );
  10187. }
  10188. rotation._onChange( onRotationChange );
  10189. quaternion._onChange( onQuaternionChange );
  10190. Object.defineProperties( this, {
  10191. /**
  10192. * Represents the object's local position.
  10193. *
  10194. * @name Object3D#position
  10195. * @type {Vector3}
  10196. * @default (0,0,0)
  10197. */
  10198. position: {
  10199. configurable: true,
  10200. enumerable: true,
  10201. value: position
  10202. },
  10203. /**
  10204. * Represents the object's local rotation as Euler angles, in radians.
  10205. *
  10206. * @name Object3D#rotation
  10207. * @type {Euler}
  10208. * @default (0,0,0)
  10209. */
  10210. rotation: {
  10211. configurable: true,
  10212. enumerable: true,
  10213. value: rotation
  10214. },
  10215. /**
  10216. * Represents the object's local rotation as Quaternions.
  10217. *
  10218. * @name Object3D#quaternion
  10219. * @type {Quaternion}
  10220. */
  10221. quaternion: {
  10222. configurable: true,
  10223. enumerable: true,
  10224. value: quaternion
  10225. },
  10226. /**
  10227. * Represents the object's local scale.
  10228. *
  10229. * @name Object3D#scale
  10230. * @type {Vector3}
  10231. * @default (1,1,1)
  10232. */
  10233. scale: {
  10234. configurable: true,
  10235. enumerable: true,
  10236. value: scale
  10237. },
  10238. /**
  10239. * Represents the object's model-view matrix.
  10240. *
  10241. * @name Object3D#modelViewMatrix
  10242. * @type {Matrix4}
  10243. */
  10244. modelViewMatrix: {
  10245. value: new Matrix4()
  10246. },
  10247. /**
  10248. * Represents the object's normal matrix.
  10249. *
  10250. * @name Object3D#normalMatrix
  10251. * @type {Matrix3}
  10252. */
  10253. normalMatrix: {
  10254. value: new Matrix3()
  10255. }
  10256. } );
  10257. /**
  10258. * Represents the object's transformation matrix in local space.
  10259. *
  10260. * @type {Matrix4}
  10261. */
  10262. this.matrix = new Matrix4();
  10263. /**
  10264. * Represents the object's transformation matrix in world space.
  10265. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10266. *
  10267. * @type {Matrix4}
  10268. */
  10269. this.matrixWorld = new Matrix4();
  10270. /**
  10271. * When set to `true`, the engine automatically computes the local matrix from position,
  10272. * rotation and scale every frame.
  10273. *
  10274. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10275. *
  10276. * @type {boolean}
  10277. * @default true
  10278. */
  10279. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10280. /**
  10281. * When set to `true`, the engine automatically computes the world matrix from the current local
  10282. * matrix and the object's transformation hierarchy.
  10283. *
  10284. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10285. *
  10286. * @type {boolean}
  10287. * @default true
  10288. */
  10289. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10290. /**
  10291. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10292. * to `false`.
  10293. *
  10294. * @type {boolean}
  10295. * @default false
  10296. */
  10297. this.matrixWorldNeedsUpdate = false;
  10298. /**
  10299. * The layer membership of the 3D object. The 3D object is only visible if it has
  10300. * at least one layer in common with the camera in use. This property can also be
  10301. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10302. *
  10303. * @type {Layers}
  10304. */
  10305. this.layers = new Layers();
  10306. /**
  10307. * When set to `true`, the 3D object gets rendered.
  10308. *
  10309. * @type {boolean}
  10310. * @default true
  10311. */
  10312. this.visible = true;
  10313. /**
  10314. * When set to `true`, the 3D object gets rendered into shadow maps.
  10315. *
  10316. * @type {boolean}
  10317. * @default false
  10318. */
  10319. this.castShadow = false;
  10320. /**
  10321. * When set to `true`, the 3D object is affected by shadows in the scene.
  10322. *
  10323. * @type {boolean}
  10324. * @default false
  10325. */
  10326. this.receiveShadow = false;
  10327. /**
  10328. * When set to `true`, the 3D object is honored by view frustum culling.
  10329. *
  10330. * @type {boolean}
  10331. * @default true
  10332. */
  10333. this.frustumCulled = true;
  10334. /**
  10335. * This value allows the default rendering order of scene graph objects to be
  10336. * overridden although opaque and transparent objects remain sorted independently.
  10337. * When this property is set for an instance of {@link Group},all descendants
  10338. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10339. * render order.
  10340. *
  10341. * @type {number}
  10342. * @default 0
  10343. */
  10344. this.renderOrder = 0;
  10345. /**
  10346. * An array holding the animation clips of the 3D object.
  10347. *
  10348. * @type {Array<AnimationClip>}
  10349. */
  10350. this.animations = [];
  10351. /**
  10352. * Custom depth material to be used when rendering to the depth map. Can only be used
  10353. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10354. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10355. * material for proper shadows.
  10356. *
  10357. * Only relevant in context of {@link WebGLRenderer}.
  10358. *
  10359. * @type {(Material|undefined)}
  10360. * @default undefined
  10361. */
  10362. this.customDepthMaterial = undefined;
  10363. /**
  10364. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10365. *
  10366. * Only relevant in context of {@link WebGLRenderer}.
  10367. *
  10368. * @type {(Material|undefined)}
  10369. * @default undefined
  10370. */
  10371. this.customDistanceMaterial = undefined;
  10372. /**
  10373. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  10374. * the 3D object is not going to be changed after the initial renderer. This includes
  10375. * geometry and material settings. A static 3D object can be processed by the renderer
  10376. * slightly faster since certain state checks can be bypassed.
  10377. *
  10378. * Only relevant in context of {@link WebGPURenderer}.
  10379. *
  10380. * @type {boolean}
  10381. * @default false
  10382. */
  10383. this.static = false;
  10384. /**
  10385. * An object that can be used to store custom data about the 3D object. It
  10386. * should not hold references to functions as these will not be cloned.
  10387. *
  10388. * @type {Object}
  10389. */
  10390. this.userData = {};
  10391. /**
  10392. * The pivot point for rotation and scale transformations.
  10393. * When set, rotation and scale are applied around this point
  10394. * instead of the object's origin.
  10395. *
  10396. * @type {?Vector3}
  10397. * @default null
  10398. */
  10399. this.pivot = null;
  10400. }
  10401. /**
  10402. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10403. *
  10404. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10405. * @param {Object3D} object - The 3D object.
  10406. * @param {Camera} camera - The camera that is used to render the scene.
  10407. * @param {Camera} shadowCamera - The shadow camera.
  10408. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10409. * @param {Material} depthMaterial - The depth material.
  10410. * @param {Object} group - The geometry group data.
  10411. */
  10412. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10413. /**
  10414. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10415. *
  10416. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10417. * @param {Object3D} object - The 3D object.
  10418. * @param {Camera} camera - The camera that is used to render the scene.
  10419. * @param {Camera} shadowCamera - The shadow camera.
  10420. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10421. * @param {Material} depthMaterial - The depth material.
  10422. * @param {Object} group - The geometry group data.
  10423. */
  10424. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10425. /**
  10426. * A callback that is executed immediately before a 3D object is rendered.
  10427. *
  10428. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10429. * @param {Object3D} object - The 3D object.
  10430. * @param {Camera} camera - The camera that is used to render the scene.
  10431. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10432. * @param {Material} material - The 3D object's material.
  10433. * @param {Object} group - The geometry group data.
  10434. */
  10435. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10436. /**
  10437. * A callback that is executed immediately after a 3D object is rendered.
  10438. *
  10439. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10440. * @param {Object3D} object - The 3D object.
  10441. * @param {Camera} camera - The camera that is used to render the scene.
  10442. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10443. * @param {Material} material - The 3D object's material.
  10444. * @param {Object} group - The geometry group data.
  10445. */
  10446. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10447. /**
  10448. * Applies the given transformation matrix to the object and updates the object's position,
  10449. * rotation and scale.
  10450. *
  10451. * @param {Matrix4} matrix - The transformation matrix.
  10452. */
  10453. applyMatrix4( matrix ) {
  10454. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10455. this.matrix.premultiply( matrix );
  10456. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10457. }
  10458. /**
  10459. * Applies a rotation represented by given the quaternion to the 3D object.
  10460. *
  10461. * @param {Quaternion} q - The quaternion.
  10462. * @return {Object3D} A reference to this instance.
  10463. */
  10464. applyQuaternion( q ) {
  10465. this.quaternion.premultiply( q );
  10466. return this;
  10467. }
  10468. /**
  10469. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10470. *
  10471. * @param {Vector3} axis - The (normalized) axis vector.
  10472. * @param {number} angle - The angle in radians.
  10473. */
  10474. setRotationFromAxisAngle( axis, angle ) {
  10475. // assumes axis is normalized
  10476. this.quaternion.setFromAxisAngle( axis, angle );
  10477. }
  10478. /**
  10479. * Sets the given rotation represented as Euler angles to the 3D object.
  10480. *
  10481. * @param {Euler} euler - The Euler angles.
  10482. */
  10483. setRotationFromEuler( euler ) {
  10484. this.quaternion.setFromEuler( euler, true );
  10485. }
  10486. /**
  10487. * Sets the given rotation represented as rotation matrix to the 3D object.
  10488. *
  10489. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10490. * a pure rotation matrix (i.e, unscaled).
  10491. */
  10492. setRotationFromMatrix( m ) {
  10493. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10494. this.quaternion.setFromRotationMatrix( m );
  10495. }
  10496. /**
  10497. * Sets the given rotation represented as a Quaternion to the 3D object.
  10498. *
  10499. * @param {Quaternion} q - The Quaternion
  10500. */
  10501. setRotationFromQuaternion( q ) {
  10502. // assumes q is normalized
  10503. this.quaternion.copy( q );
  10504. }
  10505. /**
  10506. * Rotates the 3D object along an axis in local space.
  10507. *
  10508. * @param {Vector3} axis - The (normalized) axis vector.
  10509. * @param {number} angle - The angle in radians.
  10510. * @return {Object3D} A reference to this instance.
  10511. */
  10512. rotateOnAxis( axis, angle ) {
  10513. // rotate object on axis in object space
  10514. // axis is assumed to be normalized
  10515. _q1.setFromAxisAngle( axis, angle );
  10516. this.quaternion.multiply( _q1 );
  10517. return this;
  10518. }
  10519. /**
  10520. * Rotates the 3D object along an axis in world space.
  10521. *
  10522. * @param {Vector3} axis - The (normalized) axis vector.
  10523. * @param {number} angle - The angle in radians.
  10524. * @return {Object3D} A reference to this instance.
  10525. */
  10526. rotateOnWorldAxis( axis, angle ) {
  10527. // rotate object on axis in world space
  10528. // axis is assumed to be normalized
  10529. // method assumes no rotated parent
  10530. _q1.setFromAxisAngle( axis, angle );
  10531. this.quaternion.premultiply( _q1 );
  10532. return this;
  10533. }
  10534. /**
  10535. * Rotates the 3D object around its X axis in local space.
  10536. *
  10537. * @param {number} angle - The angle in radians.
  10538. * @return {Object3D} A reference to this instance.
  10539. */
  10540. rotateX( angle ) {
  10541. return this.rotateOnAxis( _xAxis, angle );
  10542. }
  10543. /**
  10544. * Rotates the 3D object around its Y axis in local space.
  10545. *
  10546. * @param {number} angle - The angle in radians.
  10547. * @return {Object3D} A reference to this instance.
  10548. */
  10549. rotateY( angle ) {
  10550. return this.rotateOnAxis( _yAxis, angle );
  10551. }
  10552. /**
  10553. * Rotates the 3D object around its Z axis in local space.
  10554. *
  10555. * @param {number} angle - The angle in radians.
  10556. * @return {Object3D} A reference to this instance.
  10557. */
  10558. rotateZ( angle ) {
  10559. return this.rotateOnAxis( _zAxis, angle );
  10560. }
  10561. /**
  10562. * Translate the 3D object by a distance along the given axis in local space.
  10563. *
  10564. * @param {Vector3} axis - The (normalized) axis vector.
  10565. * @param {number} distance - The distance in world units.
  10566. * @return {Object3D} A reference to this instance.
  10567. */
  10568. translateOnAxis( axis, distance ) {
  10569. // translate object by distance along axis in object space
  10570. // axis is assumed to be normalized
  10571. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10572. this.position.add( _v1$4.multiplyScalar( distance ) );
  10573. return this;
  10574. }
  10575. /**
  10576. * Translate the 3D object by a distance along its X-axis in local space.
  10577. *
  10578. * @param {number} distance - The distance in world units.
  10579. * @return {Object3D} A reference to this instance.
  10580. */
  10581. translateX( distance ) {
  10582. return this.translateOnAxis( _xAxis, distance );
  10583. }
  10584. /**
  10585. * Translate the 3D object by a distance along its Y-axis in local space.
  10586. *
  10587. * @param {number} distance - The distance in world units.
  10588. * @return {Object3D} A reference to this instance.
  10589. */
  10590. translateY( distance ) {
  10591. return this.translateOnAxis( _yAxis, distance );
  10592. }
  10593. /**
  10594. * Translate the 3D object by a distance along its Z-axis in local space.
  10595. *
  10596. * @param {number} distance - The distance in world units.
  10597. * @return {Object3D} A reference to this instance.
  10598. */
  10599. translateZ( distance ) {
  10600. return this.translateOnAxis( _zAxis, distance );
  10601. }
  10602. /**
  10603. * Converts the given vector from this 3D object's local space to world space.
  10604. *
  10605. * @param {Vector3} vector - The vector to convert.
  10606. * @return {Vector3} The converted vector.
  10607. */
  10608. localToWorld( vector ) {
  10609. this.updateWorldMatrix( true, false );
  10610. return vector.applyMatrix4( this.matrixWorld );
  10611. }
  10612. /**
  10613. * Converts the given vector from this 3D object's world space to local space.
  10614. *
  10615. * @param {Vector3} vector - The vector to convert.
  10616. * @return {Vector3} The converted vector.
  10617. */
  10618. worldToLocal( vector ) {
  10619. this.updateWorldMatrix( true, false );
  10620. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10621. }
  10622. /**
  10623. * Rotates the object to face a point in world space.
  10624. *
  10625. * This method does not support objects having non-uniformly-scaled parent(s).
  10626. *
  10627. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10628. * @param {number} [y] - The y coordinate in world space.
  10629. * @param {number} [z] - The z coordinate in world space.
  10630. */
  10631. lookAt( x, y, z ) {
  10632. // This method does not support objects having non-uniformly-scaled parent(s)
  10633. if ( x.isVector3 ) {
  10634. _target.copy( x );
  10635. } else {
  10636. _target.set( x, y, z );
  10637. }
  10638. const parent = this.parent;
  10639. this.updateWorldMatrix( true, false );
  10640. _position$3.setFromMatrixPosition( this.matrixWorld );
  10641. if ( this.isCamera || this.isLight ) {
  10642. _m1$3.lookAt( _position$3, _target, this.up );
  10643. } else {
  10644. _m1$3.lookAt( _target, _position$3, this.up );
  10645. }
  10646. this.quaternion.setFromRotationMatrix( _m1$3 );
  10647. if ( parent ) {
  10648. _m1$3.extractRotation( parent.matrixWorld );
  10649. _q1.setFromRotationMatrix( _m1$3 );
  10650. this.quaternion.premultiply( _q1.invert() );
  10651. }
  10652. }
  10653. /**
  10654. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10655. * objects may be added. Any current parent on an object passed in here will be
  10656. * removed, since an object can have at most one parent.
  10657. *
  10658. * @fires Object3D#added
  10659. * @fires Object3D#childadded
  10660. * @param {Object3D} object - The 3D object to add.
  10661. * @return {Object3D} A reference to this instance.
  10662. */
  10663. add( object ) {
  10664. if ( arguments.length > 1 ) {
  10665. for ( let i = 0; i < arguments.length; i ++ ) {
  10666. this.add( arguments[ i ] );
  10667. }
  10668. return this;
  10669. }
  10670. if ( object === this ) {
  10671. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10672. return this;
  10673. }
  10674. if ( object && object.isObject3D ) {
  10675. object.removeFromParent();
  10676. object.parent = this;
  10677. this.children.push( object );
  10678. object.dispatchEvent( _addedEvent );
  10679. _childaddedEvent.child = object;
  10680. this.dispatchEvent( _childaddedEvent );
  10681. _childaddedEvent.child = null;
  10682. } else {
  10683. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10684. }
  10685. return this;
  10686. }
  10687. /**
  10688. * Removes the given 3D object as child from this 3D object.
  10689. * An arbitrary number of objects may be removed.
  10690. *
  10691. * @fires Object3D#removed
  10692. * @fires Object3D#childremoved
  10693. * @param {Object3D} object - The 3D object to remove.
  10694. * @return {Object3D} A reference to this instance.
  10695. */
  10696. remove( object ) {
  10697. if ( arguments.length > 1 ) {
  10698. for ( let i = 0; i < arguments.length; i ++ ) {
  10699. this.remove( arguments[ i ] );
  10700. }
  10701. return this;
  10702. }
  10703. const index = this.children.indexOf( object );
  10704. if ( index !== -1 ) {
  10705. object.parent = null;
  10706. this.children.splice( index, 1 );
  10707. object.dispatchEvent( _removedEvent );
  10708. _childremovedEvent.child = object;
  10709. this.dispatchEvent( _childremovedEvent );
  10710. _childremovedEvent.child = null;
  10711. }
  10712. return this;
  10713. }
  10714. /**
  10715. * Removes this 3D object from its current parent.
  10716. *
  10717. * @fires Object3D#removed
  10718. * @fires Object3D#childremoved
  10719. * @return {Object3D} A reference to this instance.
  10720. */
  10721. removeFromParent() {
  10722. const parent = this.parent;
  10723. if ( parent !== null ) {
  10724. parent.remove( this );
  10725. }
  10726. return this;
  10727. }
  10728. /**
  10729. * Removes all child objects.
  10730. *
  10731. * @fires Object3D#removed
  10732. * @fires Object3D#childremoved
  10733. * @return {Object3D} A reference to this instance.
  10734. */
  10735. clear() {
  10736. return this.remove( ... this.children );
  10737. }
  10738. /**
  10739. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10740. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10741. *
  10742. * @fires Object3D#added
  10743. * @fires Object3D#childadded
  10744. * @param {Object3D} object - The 3D object to attach.
  10745. * @return {Object3D} A reference to this instance.
  10746. */
  10747. attach( object ) {
  10748. // adds object as a child of this, while maintaining the object's world transform
  10749. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10750. this.updateWorldMatrix( true, false );
  10751. _m1$3.copy( this.matrixWorld ).invert();
  10752. if ( object.parent !== null ) {
  10753. object.parent.updateWorldMatrix( true, false );
  10754. _m1$3.multiply( object.parent.matrixWorld );
  10755. }
  10756. object.applyMatrix4( _m1$3 );
  10757. object.removeFromParent();
  10758. object.parent = this;
  10759. this.children.push( object );
  10760. object.updateWorldMatrix( false, true );
  10761. object.dispatchEvent( _addedEvent );
  10762. _childaddedEvent.child = object;
  10763. this.dispatchEvent( _childaddedEvent );
  10764. _childaddedEvent.child = null;
  10765. return this;
  10766. }
  10767. /**
  10768. * Searches through the 3D object and its children, starting with the 3D object
  10769. * itself, and returns the first with a matching ID.
  10770. *
  10771. * @param {number} id - The id.
  10772. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10773. */
  10774. getObjectById( id ) {
  10775. return this.getObjectByProperty( 'id', id );
  10776. }
  10777. /**
  10778. * Searches through the 3D object and its children, starting with the 3D object
  10779. * itself, and returns the first with a matching name.
  10780. *
  10781. * @param {string} name - The name.
  10782. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10783. */
  10784. getObjectByName( name ) {
  10785. return this.getObjectByProperty( 'name', name );
  10786. }
  10787. /**
  10788. * Searches through the 3D object and its children, starting with the 3D object
  10789. * itself, and returns the first with a matching property value.
  10790. *
  10791. * @param {string} name - The name of the property.
  10792. * @param {any} value - The value.
  10793. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10794. */
  10795. getObjectByProperty( name, value ) {
  10796. if ( this[ name ] === value ) return this;
  10797. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10798. const child = this.children[ i ];
  10799. const object = child.getObjectByProperty( name, value );
  10800. if ( object !== undefined ) {
  10801. return object;
  10802. }
  10803. }
  10804. return undefined;
  10805. }
  10806. /**
  10807. * Searches through the 3D object and its children, starting with the 3D object
  10808. * itself, and returns all 3D objects with a matching property value.
  10809. *
  10810. * @param {string} name - The name of the property.
  10811. * @param {any} value - The value.
  10812. * @param {Array<Object3D>} result - The method stores the result in this array.
  10813. * @return {Array<Object3D>} The found 3D objects.
  10814. */
  10815. getObjectsByProperty( name, value, result = [] ) {
  10816. if ( this[ name ] === value ) result.push( this );
  10817. const children = this.children;
  10818. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10819. children[ i ].getObjectsByProperty( name, value, result );
  10820. }
  10821. return result;
  10822. }
  10823. /**
  10824. * Returns a vector representing the position of the 3D object in world space.
  10825. *
  10826. * @param {Vector3} target - The target vector the result is stored to.
  10827. * @return {Vector3} The 3D object's position in world space.
  10828. */
  10829. getWorldPosition( target ) {
  10830. this.updateWorldMatrix( true, false );
  10831. return target.setFromMatrixPosition( this.matrixWorld );
  10832. }
  10833. /**
  10834. * Returns a Quaternion representing the position of the 3D object in world space.
  10835. *
  10836. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10837. * @return {Quaternion} The 3D object's rotation in world space.
  10838. */
  10839. getWorldQuaternion( target ) {
  10840. this.updateWorldMatrix( true, false );
  10841. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10842. return target;
  10843. }
  10844. /**
  10845. * Returns a vector representing the scale of the 3D object in world space.
  10846. *
  10847. * @param {Vector3} target - The target vector the result is stored to.
  10848. * @return {Vector3} The 3D object's scale in world space.
  10849. */
  10850. getWorldScale( target ) {
  10851. this.updateWorldMatrix( true, false );
  10852. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10853. return target;
  10854. }
  10855. /**
  10856. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10857. *
  10858. * @param {Vector3} target - The target vector the result is stored to.
  10859. * @return {Vector3} The 3D object's direction in world space.
  10860. */
  10861. getWorldDirection( target ) {
  10862. this.updateWorldMatrix( true, false );
  10863. const e = this.matrixWorld.elements;
  10864. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10865. }
  10866. /**
  10867. * Abstract method to get intersections between a casted ray and this
  10868. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10869. * implement this method in order to use raycasting.
  10870. *
  10871. * @abstract
  10872. * @param {Raycaster} raycaster - The raycaster.
  10873. * @param {Array<Object>} intersects - An array holding the result of the method.
  10874. */
  10875. raycast( /* raycaster, intersects */ ) {}
  10876. /**
  10877. * Executes the callback on this 3D object and all descendants.
  10878. *
  10879. * Note: Modifying the scene graph inside the callback is discouraged.
  10880. *
  10881. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10882. */
  10883. traverse( callback ) {
  10884. callback( this );
  10885. const children = this.children;
  10886. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10887. children[ i ].traverse( callback );
  10888. }
  10889. }
  10890. /**
  10891. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10892. * Descendants of invisible 3D objects are not traversed.
  10893. *
  10894. * Note: Modifying the scene graph inside the callback is discouraged.
  10895. *
  10896. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10897. */
  10898. traverseVisible( callback ) {
  10899. if ( this.visible === false ) return;
  10900. callback( this );
  10901. const children = this.children;
  10902. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10903. children[ i ].traverseVisible( callback );
  10904. }
  10905. }
  10906. /**
  10907. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10908. *
  10909. * Note: Modifying the scene graph inside the callback is discouraged.
  10910. *
  10911. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10912. */
  10913. traverseAncestors( callback ) {
  10914. const parent = this.parent;
  10915. if ( parent !== null ) {
  10916. callback( parent );
  10917. parent.traverseAncestors( callback );
  10918. }
  10919. }
  10920. /**
  10921. * Updates the transformation matrix in local space by computing it from the current
  10922. * position, rotation and scale values.
  10923. */
  10924. updateMatrix() {
  10925. this.matrix.compose( this.position, this.quaternion, this.scale );
  10926. const pivot = this.pivot;
  10927. if ( pivot !== null ) {
  10928. const px = pivot.x, py = pivot.y, pz = pivot.z;
  10929. const te = this.matrix.elements;
  10930. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  10931. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  10932. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  10933. }
  10934. this.matrixWorldNeedsUpdate = true;
  10935. }
  10936. /**
  10937. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10938. *
  10939. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10940. * local space. The computation of the local and world matrix can be controlled with the
  10941. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10942. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10943. *
  10944. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10945. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10946. */
  10947. updateMatrixWorld( force ) {
  10948. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10949. if ( this.matrixWorldNeedsUpdate || force ) {
  10950. if ( this.matrixWorldAutoUpdate === true ) {
  10951. if ( this.parent === null ) {
  10952. this.matrixWorld.copy( this.matrix );
  10953. } else {
  10954. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10955. }
  10956. }
  10957. this.matrixWorldNeedsUpdate = false;
  10958. force = true;
  10959. }
  10960. // make sure descendants are updated if required
  10961. const children = this.children;
  10962. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10963. const child = children[ i ];
  10964. child.updateMatrixWorld( force );
  10965. }
  10966. }
  10967. /**
  10968. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10969. * update of ancestor and descendant nodes.
  10970. *
  10971. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10972. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10973. */
  10974. updateWorldMatrix( updateParents, updateChildren ) {
  10975. const parent = this.parent;
  10976. if ( updateParents === true && parent !== null ) {
  10977. parent.updateWorldMatrix( true, false );
  10978. }
  10979. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10980. if ( this.matrixWorldAutoUpdate === true ) {
  10981. if ( this.parent === null ) {
  10982. this.matrixWorld.copy( this.matrix );
  10983. } else {
  10984. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10985. }
  10986. }
  10987. // make sure descendants are updated
  10988. if ( updateChildren === true ) {
  10989. const children = this.children;
  10990. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10991. const child = children[ i ];
  10992. child.updateWorldMatrix( false, true );
  10993. }
  10994. }
  10995. }
  10996. /**
  10997. * Serializes the 3D object into JSON.
  10998. *
  10999. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11000. * @return {Object} A JSON object representing the serialized 3D object.
  11001. * @see {@link ObjectLoader#parse}
  11002. */
  11003. toJSON( meta ) {
  11004. // meta is a string when called from JSON.stringify
  11005. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  11006. const output = {};
  11007. // meta is a hash used to collect geometries, materials.
  11008. // not providing it implies that this is the root object
  11009. // being serialized.
  11010. if ( isRootObject ) {
  11011. // initialize meta obj
  11012. meta = {
  11013. geometries: {},
  11014. materials: {},
  11015. textures: {},
  11016. images: {},
  11017. shapes: {},
  11018. skeletons: {},
  11019. animations: {},
  11020. nodes: {}
  11021. };
  11022. output.metadata = {
  11023. version: 4.7,
  11024. type: 'Object',
  11025. generator: 'Object3D.toJSON'
  11026. };
  11027. }
  11028. // standard Object3D serialization
  11029. const object = {};
  11030. object.uuid = this.uuid;
  11031. object.type = this.type;
  11032. if ( this.name !== '' ) object.name = this.name;
  11033. if ( this.castShadow === true ) object.castShadow = true;
  11034. if ( this.receiveShadow === true ) object.receiveShadow = true;
  11035. if ( this.visible === false ) object.visible = false;
  11036. if ( this.frustumCulled === false ) object.frustumCulled = false;
  11037. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  11038. if ( this.static !== false ) object.static = this.static;
  11039. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  11040. object.layers = this.layers.mask;
  11041. object.matrix = this.matrix.toArray();
  11042. object.up = this.up.toArray();
  11043. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  11044. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  11045. // object specific properties
  11046. if ( this.isInstancedMesh ) {
  11047. object.type = 'InstancedMesh';
  11048. object.count = this.count;
  11049. object.instanceMatrix = this.instanceMatrix.toJSON();
  11050. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11051. }
  11052. if ( this.isBatchedMesh ) {
  11053. object.type = 'BatchedMesh';
  11054. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11055. object.sortObjects = this.sortObjects;
  11056. object.drawRanges = this._drawRanges;
  11057. object.reservedRanges = this._reservedRanges;
  11058. object.geometryInfo = this._geometryInfo.map( info => ( {
  11059. ...info,
  11060. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11061. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11062. } ) );
  11063. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11064. object.availableInstanceIds = this._availableInstanceIds.slice();
  11065. object.availableGeometryIds = this._availableGeometryIds.slice();
  11066. object.nextIndexStart = this._nextIndexStart;
  11067. object.nextVertexStart = this._nextVertexStart;
  11068. object.geometryCount = this._geometryCount;
  11069. object.maxInstanceCount = this._maxInstanceCount;
  11070. object.maxVertexCount = this._maxVertexCount;
  11071. object.maxIndexCount = this._maxIndexCount;
  11072. object.geometryInitialized = this._geometryInitialized;
  11073. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11074. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11075. if ( this._colorsTexture !== null ) {
  11076. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11077. }
  11078. if ( this.boundingSphere !== null ) {
  11079. object.boundingSphere = this.boundingSphere.toJSON();
  11080. }
  11081. if ( this.boundingBox !== null ) {
  11082. object.boundingBox = this.boundingBox.toJSON();
  11083. }
  11084. }
  11085. //
  11086. function serialize( library, element ) {
  11087. if ( library[ element.uuid ] === undefined ) {
  11088. library[ element.uuid ] = element.toJSON( meta );
  11089. }
  11090. return element.uuid;
  11091. }
  11092. if ( this.isScene ) {
  11093. if ( this.background ) {
  11094. if ( this.background.isColor ) {
  11095. object.background = this.background.toJSON();
  11096. } else if ( this.background.isTexture ) {
  11097. object.background = this.background.toJSON( meta ).uuid;
  11098. }
  11099. }
  11100. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11101. object.environment = this.environment.toJSON( meta ).uuid;
  11102. }
  11103. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11104. object.geometry = serialize( meta.geometries, this.geometry );
  11105. const parameters = this.geometry.parameters;
  11106. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11107. const shapes = parameters.shapes;
  11108. if ( Array.isArray( shapes ) ) {
  11109. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11110. const shape = shapes[ i ];
  11111. serialize( meta.shapes, shape );
  11112. }
  11113. } else {
  11114. serialize( meta.shapes, shapes );
  11115. }
  11116. }
  11117. }
  11118. if ( this.isSkinnedMesh ) {
  11119. object.bindMode = this.bindMode;
  11120. object.bindMatrix = this.bindMatrix.toArray();
  11121. if ( this.skeleton !== undefined ) {
  11122. serialize( meta.skeletons, this.skeleton );
  11123. object.skeleton = this.skeleton.uuid;
  11124. }
  11125. }
  11126. if ( this.material !== undefined ) {
  11127. if ( Array.isArray( this.material ) ) {
  11128. const uuids = [];
  11129. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11130. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11131. }
  11132. object.material = uuids;
  11133. } else {
  11134. object.material = serialize( meta.materials, this.material );
  11135. }
  11136. }
  11137. //
  11138. if ( this.children.length > 0 ) {
  11139. object.children = [];
  11140. for ( let i = 0; i < this.children.length; i ++ ) {
  11141. object.children.push( this.children[ i ].toJSON( meta ).object );
  11142. }
  11143. }
  11144. //
  11145. if ( this.animations.length > 0 ) {
  11146. object.animations = [];
  11147. for ( let i = 0; i < this.animations.length; i ++ ) {
  11148. const animation = this.animations[ i ];
  11149. object.animations.push( serialize( meta.animations, animation ) );
  11150. }
  11151. }
  11152. if ( isRootObject ) {
  11153. const geometries = extractFromCache( meta.geometries );
  11154. const materials = extractFromCache( meta.materials );
  11155. const textures = extractFromCache( meta.textures );
  11156. const images = extractFromCache( meta.images );
  11157. const shapes = extractFromCache( meta.shapes );
  11158. const skeletons = extractFromCache( meta.skeletons );
  11159. const animations = extractFromCache( meta.animations );
  11160. const nodes = extractFromCache( meta.nodes );
  11161. if ( geometries.length > 0 ) output.geometries = geometries;
  11162. if ( materials.length > 0 ) output.materials = materials;
  11163. if ( textures.length > 0 ) output.textures = textures;
  11164. if ( images.length > 0 ) output.images = images;
  11165. if ( shapes.length > 0 ) output.shapes = shapes;
  11166. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11167. if ( animations.length > 0 ) output.animations = animations;
  11168. if ( nodes.length > 0 ) output.nodes = nodes;
  11169. }
  11170. output.object = object;
  11171. return output;
  11172. // extract data from the cache hash
  11173. // remove metadata on each item
  11174. // and return as array
  11175. function extractFromCache( cache ) {
  11176. const values = [];
  11177. for ( const key in cache ) {
  11178. const data = cache[ key ];
  11179. delete data.metadata;
  11180. values.push( data );
  11181. }
  11182. return values;
  11183. }
  11184. }
  11185. /**
  11186. * Returns a new 3D object with copied values from this instance.
  11187. *
  11188. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11189. * @return {Object3D} A clone of this instance.
  11190. */
  11191. clone( recursive ) {
  11192. return new this.constructor().copy( this, recursive );
  11193. }
  11194. /**
  11195. * Copies the values of the given 3D object to this instance.
  11196. *
  11197. * @param {Object3D} source - The 3D object to copy.
  11198. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11199. * @return {Object3D} A reference to this instance.
  11200. */
  11201. copy( source, recursive = true ) {
  11202. this.name = source.name;
  11203. this.up.copy( source.up );
  11204. this.position.copy( source.position );
  11205. this.rotation.order = source.rotation.order;
  11206. this.quaternion.copy( source.quaternion );
  11207. this.scale.copy( source.scale );
  11208. if ( source.pivot !== null ) {
  11209. this.pivot = source.pivot.clone();
  11210. }
  11211. this.matrix.copy( source.matrix );
  11212. this.matrixWorld.copy( source.matrixWorld );
  11213. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11214. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11215. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11216. this.layers.mask = source.layers.mask;
  11217. this.visible = source.visible;
  11218. this.castShadow = source.castShadow;
  11219. this.receiveShadow = source.receiveShadow;
  11220. this.frustumCulled = source.frustumCulled;
  11221. this.renderOrder = source.renderOrder;
  11222. this.static = source.static;
  11223. this.animations = source.animations.slice();
  11224. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11225. if ( recursive === true ) {
  11226. for ( let i = 0; i < source.children.length; i ++ ) {
  11227. const child = source.children[ i ];
  11228. this.add( child.clone() );
  11229. }
  11230. }
  11231. return this;
  11232. }
  11233. }
  11234. /**
  11235. * The default up direction for objects, also used as the default
  11236. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11237. *
  11238. * @static
  11239. * @type {Vector3}
  11240. * @default (0,1,0)
  11241. */
  11242. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11243. /**
  11244. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11245. * newly created 3D objects.
  11246. *
  11247. * @static
  11248. * @type {boolean}
  11249. * @default true
  11250. */
  11251. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11252. /**
  11253. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11254. * newly created 3D objects.
  11255. *
  11256. * @static
  11257. * @type {boolean}
  11258. * @default true
  11259. */
  11260. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11261. const _v0$2 = /*@__PURE__*/ new Vector3();
  11262. const _v1$3 = /*@__PURE__*/ new Vector3();
  11263. const _v2$2 = /*@__PURE__*/ new Vector3();
  11264. const _v3$2 = /*@__PURE__*/ new Vector3();
  11265. const _vab = /*@__PURE__*/ new Vector3();
  11266. const _vac = /*@__PURE__*/ new Vector3();
  11267. const _vbc = /*@__PURE__*/ new Vector3();
  11268. const _vap = /*@__PURE__*/ new Vector3();
  11269. const _vbp = /*@__PURE__*/ new Vector3();
  11270. const _vcp = /*@__PURE__*/ new Vector3();
  11271. const _v40 = /*@__PURE__*/ new Vector4();
  11272. const _v41 = /*@__PURE__*/ new Vector4();
  11273. const _v42 = /*@__PURE__*/ new Vector4();
  11274. /**
  11275. * A geometric triangle as defined by three vectors representing its three corners.
  11276. */
  11277. class Triangle {
  11278. /**
  11279. * Constructs a new triangle.
  11280. *
  11281. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11282. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11283. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11284. */
  11285. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11286. /**
  11287. * The first corner of the triangle.
  11288. *
  11289. * @type {Vector3}
  11290. */
  11291. this.a = a;
  11292. /**
  11293. * The second corner of the triangle.
  11294. *
  11295. * @type {Vector3}
  11296. */
  11297. this.b = b;
  11298. /**
  11299. * The third corner of the triangle.
  11300. *
  11301. * @type {Vector3}
  11302. */
  11303. this.c = c;
  11304. }
  11305. /**
  11306. * Computes the normal vector of a triangle.
  11307. *
  11308. * @param {Vector3} a - The first corner of the triangle.
  11309. * @param {Vector3} b - The second corner of the triangle.
  11310. * @param {Vector3} c - The third corner of the triangle.
  11311. * @param {Vector3} target - The target vector that is used to store the method's result.
  11312. * @return {Vector3} The triangle's normal.
  11313. */
  11314. static getNormal( a, b, c, target ) {
  11315. target.subVectors( c, b );
  11316. _v0$2.subVectors( a, b );
  11317. target.cross( _v0$2 );
  11318. const targetLengthSq = target.lengthSq();
  11319. if ( targetLengthSq > 0 ) {
  11320. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11321. }
  11322. return target.set( 0, 0, 0 );
  11323. }
  11324. /**
  11325. * Computes a barycentric coordinates from the given vector.
  11326. * Returns `null` if the triangle is degenerate.
  11327. *
  11328. * @param {Vector3} point - A point in 3D space.
  11329. * @param {Vector3} a - The first corner of the triangle.
  11330. * @param {Vector3} b - The second corner of the triangle.
  11331. * @param {Vector3} c - The third corner of the triangle.
  11332. * @param {Vector3} target - The target vector that is used to store the method's result.
  11333. * @return {?Vector3} The barycentric coordinates for the given point
  11334. */
  11335. static getBarycoord( point, a, b, c, target ) {
  11336. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11337. _v0$2.subVectors( c, a );
  11338. _v1$3.subVectors( b, a );
  11339. _v2$2.subVectors( point, a );
  11340. const dot00 = _v0$2.dot( _v0$2 );
  11341. const dot01 = _v0$2.dot( _v1$3 );
  11342. const dot02 = _v0$2.dot( _v2$2 );
  11343. const dot11 = _v1$3.dot( _v1$3 );
  11344. const dot12 = _v1$3.dot( _v2$2 );
  11345. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11346. // collinear or singular triangle
  11347. if ( denom === 0 ) {
  11348. target.set( 0, 0, 0 );
  11349. return null;
  11350. }
  11351. const invDenom = 1 / denom;
  11352. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11353. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11354. // barycentric coordinates must always sum to 1
  11355. return target.set( 1 - u - v, v, u );
  11356. }
  11357. /**
  11358. * Returns `true` if the given point, when projected onto the plane of the
  11359. * triangle, lies within the triangle.
  11360. *
  11361. * @param {Vector3} point - The point in 3D space to test.
  11362. * @param {Vector3} a - The first corner of the triangle.
  11363. * @param {Vector3} b - The second corner of the triangle.
  11364. * @param {Vector3} c - The third corner of the triangle.
  11365. * @return {boolean} Whether the given point, when projected onto the plane of the
  11366. * triangle, lies within the triangle or not.
  11367. */
  11368. static containsPoint( point, a, b, c ) {
  11369. // if the triangle is degenerate then we can't contain a point
  11370. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11371. return false;
  11372. }
  11373. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11374. }
  11375. /**
  11376. * Computes the value barycentrically interpolated for the given point on the
  11377. * triangle. Returns `null` if the triangle is degenerate.
  11378. *
  11379. * @param {Vector3} point - Position of interpolated point.
  11380. * @param {Vector3} p1 - The first corner of the triangle.
  11381. * @param {Vector3} p2 - The second corner of the triangle.
  11382. * @param {Vector3} p3 - The third corner of the triangle.
  11383. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11384. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11385. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11386. * @param {Vector3} target - The target vector that is used to store the method's result.
  11387. * @return {?Vector3} The interpolated value.
  11388. */
  11389. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11390. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11391. target.x = 0;
  11392. target.y = 0;
  11393. if ( 'z' in target ) target.z = 0;
  11394. if ( 'w' in target ) target.w = 0;
  11395. return null;
  11396. }
  11397. target.setScalar( 0 );
  11398. target.addScaledVector( v1, _v3$2.x );
  11399. target.addScaledVector( v2, _v3$2.y );
  11400. target.addScaledVector( v3, _v3$2.z );
  11401. return target;
  11402. }
  11403. /**
  11404. * Computes the value barycentrically interpolated for the given attribute and indices.
  11405. *
  11406. * @param {BufferAttribute} attr - The attribute to interpolate.
  11407. * @param {number} i1 - Index of first vertex.
  11408. * @param {number} i2 - Index of second vertex.
  11409. * @param {number} i3 - Index of third vertex.
  11410. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11411. * @param {Vector3} target - The target vector that is used to store the method's result.
  11412. * @return {Vector3} The interpolated attribute value.
  11413. */
  11414. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11415. _v40.setScalar( 0 );
  11416. _v41.setScalar( 0 );
  11417. _v42.setScalar( 0 );
  11418. _v40.fromBufferAttribute( attr, i1 );
  11419. _v41.fromBufferAttribute( attr, i2 );
  11420. _v42.fromBufferAttribute( attr, i3 );
  11421. target.setScalar( 0 );
  11422. target.addScaledVector( _v40, barycoord.x );
  11423. target.addScaledVector( _v41, barycoord.y );
  11424. target.addScaledVector( _v42, barycoord.z );
  11425. return target;
  11426. }
  11427. /**
  11428. * Returns `true` if the triangle is oriented towards the given direction.
  11429. *
  11430. * @param {Vector3} a - The first corner of the triangle.
  11431. * @param {Vector3} b - The second corner of the triangle.
  11432. * @param {Vector3} c - The third corner of the triangle.
  11433. * @param {Vector3} direction - The (normalized) direction vector.
  11434. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11435. */
  11436. static isFrontFacing( a, b, c, direction ) {
  11437. _v0$2.subVectors( c, b );
  11438. _v1$3.subVectors( a, b );
  11439. // strictly front facing
  11440. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11441. }
  11442. /**
  11443. * Sets the triangle's vertices by copying the given values.
  11444. *
  11445. * @param {Vector3} a - The first corner of the triangle.
  11446. * @param {Vector3} b - The second corner of the triangle.
  11447. * @param {Vector3} c - The third corner of the triangle.
  11448. * @return {Triangle} A reference to this triangle.
  11449. */
  11450. set( a, b, c ) {
  11451. this.a.copy( a );
  11452. this.b.copy( b );
  11453. this.c.copy( c );
  11454. return this;
  11455. }
  11456. /**
  11457. * Sets the triangle's vertices by copying the given array values.
  11458. *
  11459. * @param {Array<Vector3>} points - An array with 3D points.
  11460. * @param {number} i0 - The array index representing the first corner of the triangle.
  11461. * @param {number} i1 - The array index representing the second corner of the triangle.
  11462. * @param {number} i2 - The array index representing the third corner of the triangle.
  11463. * @return {Triangle} A reference to this triangle.
  11464. */
  11465. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11466. this.a.copy( points[ i0 ] );
  11467. this.b.copy( points[ i1 ] );
  11468. this.c.copy( points[ i2 ] );
  11469. return this;
  11470. }
  11471. /**
  11472. * Sets the triangle's vertices by copying the given attribute values.
  11473. *
  11474. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11475. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11476. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11477. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11478. * @return {Triangle} A reference to this triangle.
  11479. */
  11480. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11481. this.a.fromBufferAttribute( attribute, i0 );
  11482. this.b.fromBufferAttribute( attribute, i1 );
  11483. this.c.fromBufferAttribute( attribute, i2 );
  11484. return this;
  11485. }
  11486. /**
  11487. * Returns a new triangle with copied values from this instance.
  11488. *
  11489. * @return {Triangle} A clone of this instance.
  11490. */
  11491. clone() {
  11492. return new this.constructor().copy( this );
  11493. }
  11494. /**
  11495. * Copies the values of the given triangle to this instance.
  11496. *
  11497. * @param {Triangle} triangle - The triangle to copy.
  11498. * @return {Triangle} A reference to this triangle.
  11499. */
  11500. copy( triangle ) {
  11501. this.a.copy( triangle.a );
  11502. this.b.copy( triangle.b );
  11503. this.c.copy( triangle.c );
  11504. return this;
  11505. }
  11506. /**
  11507. * Computes the area of the triangle.
  11508. *
  11509. * @return {number} The triangle's area.
  11510. */
  11511. getArea() {
  11512. _v0$2.subVectors( this.c, this.b );
  11513. _v1$3.subVectors( this.a, this.b );
  11514. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11515. }
  11516. /**
  11517. * Computes the midpoint of the triangle.
  11518. *
  11519. * @param {Vector3} target - The target vector that is used to store the method's result.
  11520. * @return {Vector3} The triangle's midpoint.
  11521. */
  11522. getMidpoint( target ) {
  11523. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11524. }
  11525. /**
  11526. * Computes the normal of the triangle.
  11527. *
  11528. * @param {Vector3} target - The target vector that is used to store the method's result.
  11529. * @return {Vector3} The triangle's normal.
  11530. */
  11531. getNormal( target ) {
  11532. return Triangle.getNormal( this.a, this.b, this.c, target );
  11533. }
  11534. /**
  11535. * Computes a plane the triangle lies within.
  11536. *
  11537. * @param {Plane} target - The target vector that is used to store the method's result.
  11538. * @return {Plane} The plane the triangle lies within.
  11539. */
  11540. getPlane( target ) {
  11541. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11542. }
  11543. /**
  11544. * Computes a barycentric coordinates from the given vector.
  11545. * Returns `null` if the triangle is degenerate.
  11546. *
  11547. * @param {Vector3} point - A point in 3D space.
  11548. * @param {Vector3} target - The target vector that is used to store the method's result.
  11549. * @return {?Vector3} The barycentric coordinates for the given point
  11550. */
  11551. getBarycoord( point, target ) {
  11552. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11553. }
  11554. /**
  11555. * Computes the value barycentrically interpolated for the given point on the
  11556. * triangle. Returns `null` if the triangle is degenerate.
  11557. *
  11558. * @param {Vector3} point - Position of interpolated point.
  11559. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11560. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11561. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11562. * @param {Vector3} target - The target vector that is used to store the method's result.
  11563. * @return {?Vector3} The interpolated value.
  11564. */
  11565. getInterpolation( point, v1, v2, v3, target ) {
  11566. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11567. }
  11568. /**
  11569. * Returns `true` if the given point, when projected onto the plane of the
  11570. * triangle, lies within the triangle.
  11571. *
  11572. * @param {Vector3} point - The point in 3D space to test.
  11573. * @return {boolean} Whether the given point, when projected onto the plane of the
  11574. * triangle, lies within the triangle or not.
  11575. */
  11576. containsPoint( point ) {
  11577. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11578. }
  11579. /**
  11580. * Returns `true` if the triangle is oriented towards the given direction.
  11581. *
  11582. * @param {Vector3} direction - The (normalized) direction vector.
  11583. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11584. */
  11585. isFrontFacing( direction ) {
  11586. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11587. }
  11588. /**
  11589. * Returns `true` if this triangle intersects with the given box.
  11590. *
  11591. * @param {Box3} box - The box to intersect.
  11592. * @return {boolean} Whether this triangle intersects with the given box or not.
  11593. */
  11594. intersectsBox( box ) {
  11595. return box.intersectsTriangle( this );
  11596. }
  11597. /**
  11598. * Returns the closest point on the triangle to the given point.
  11599. *
  11600. * @param {Vector3} p - The point to compute the closest point for.
  11601. * @param {Vector3} target - The target vector that is used to store the method's result.
  11602. * @return {Vector3} The closest point on the triangle.
  11603. */
  11604. closestPointToPoint( p, target ) {
  11605. const a = this.a, b = this.b, c = this.c;
  11606. let v, w;
  11607. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11608. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11609. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11610. // basically, we're distinguishing which of the voronoi regions of the triangle
  11611. // the point lies in with the minimum amount of redundant computation.
  11612. _vab.subVectors( b, a );
  11613. _vac.subVectors( c, a );
  11614. _vap.subVectors( p, a );
  11615. const d1 = _vab.dot( _vap );
  11616. const d2 = _vac.dot( _vap );
  11617. if ( d1 <= 0 && d2 <= 0 ) {
  11618. // vertex region of A; barycentric coords (1, 0, 0)
  11619. return target.copy( a );
  11620. }
  11621. _vbp.subVectors( p, b );
  11622. const d3 = _vab.dot( _vbp );
  11623. const d4 = _vac.dot( _vbp );
  11624. if ( d3 >= 0 && d4 <= d3 ) {
  11625. // vertex region of B; barycentric coords (0, 1, 0)
  11626. return target.copy( b );
  11627. }
  11628. const vc = d1 * d4 - d3 * d2;
  11629. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11630. v = d1 / ( d1 - d3 );
  11631. // edge region of AB; barycentric coords (1-v, v, 0)
  11632. return target.copy( a ).addScaledVector( _vab, v );
  11633. }
  11634. _vcp.subVectors( p, c );
  11635. const d5 = _vab.dot( _vcp );
  11636. const d6 = _vac.dot( _vcp );
  11637. if ( d6 >= 0 && d5 <= d6 ) {
  11638. // vertex region of C; barycentric coords (0, 0, 1)
  11639. return target.copy( c );
  11640. }
  11641. const vb = d5 * d2 - d1 * d6;
  11642. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11643. w = d2 / ( d2 - d6 );
  11644. // edge region of AC; barycentric coords (1-w, 0, w)
  11645. return target.copy( a ).addScaledVector( _vac, w );
  11646. }
  11647. const va = d3 * d6 - d5 * d4;
  11648. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11649. _vbc.subVectors( c, b );
  11650. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11651. // edge region of BC; barycentric coords (0, 1-w, w)
  11652. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11653. }
  11654. // face region
  11655. const denom = 1 / ( va + vb + vc );
  11656. // u = va * denom
  11657. v = vb * denom;
  11658. w = vc * denom;
  11659. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11660. }
  11661. /**
  11662. * Returns `true` if this triangle is equal with the given one.
  11663. *
  11664. * @param {Triangle} triangle - The triangle to test for equality.
  11665. * @return {boolean} Whether this triangle is equal with the given one.
  11666. */
  11667. equals( triangle ) {
  11668. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11669. }
  11670. }
  11671. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11672. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11673. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11674. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11675. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11676. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11677. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11678. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11679. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11680. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11681. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11682. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11683. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11684. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11685. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11686. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11687. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11688. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11689. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11690. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11691. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11692. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11693. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11694. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11695. const _hslA = { h: 0, s: 0, l: 0 };
  11696. const _hslB = { h: 0, s: 0, l: 0 };
  11697. function hue2rgb( p, q, t ) {
  11698. if ( t < 0 ) t += 1;
  11699. if ( t > 1 ) t -= 1;
  11700. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11701. if ( t < 1 / 2 ) return q;
  11702. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11703. return p;
  11704. }
  11705. /**
  11706. * A Color instance is represented by RGB components in the linear <i>working
  11707. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11708. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11709. * strings) are converted to the working color space automatically.
  11710. *
  11711. * ```js
  11712. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11713. * const color = new THREE.Color().setHex( 0x112233 );
  11714. * ```
  11715. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11716. * ```js
  11717. * // assumed already LinearSRGBColorSpace; no conversion
  11718. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11719. *
  11720. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11721. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11722. * ```
  11723. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11724. * see <i>Color management</i>. Iterating through a Color instance will yield
  11725. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11726. * in any of the following ways:
  11727. * ```js
  11728. * //empty constructor - will default white
  11729. * const color1 = new THREE.Color();
  11730. *
  11731. * //Hexadecimal color (recommended)
  11732. * const color2 = new THREE.Color( 0xff0000 );
  11733. *
  11734. * //RGB string
  11735. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11736. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11737. *
  11738. * //X11 color name - all 140 color names are supported.
  11739. * //Note the lack of CamelCase in the name
  11740. * const color5 = new THREE.Color( 'skyblue' );
  11741. * //HSL string
  11742. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11743. *
  11744. * //Separate RGB values between 0 and 1
  11745. * const color7 = new THREE.Color( 1, 0, 0 );
  11746. * ```
  11747. */
  11748. class Color {
  11749. /**
  11750. * Constructs a new color.
  11751. *
  11752. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11753. * and that method is used throughout the rest of the documentation.
  11754. *
  11755. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11756. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11757. * @param {number} [g] - The green component.
  11758. * @param {number} [b] - The blue component.
  11759. */
  11760. constructor( r, g, b ) {
  11761. /**
  11762. * This flag can be used for type testing.
  11763. *
  11764. * @type {boolean}
  11765. * @readonly
  11766. * @default true
  11767. */
  11768. this.isColor = true;
  11769. /**
  11770. * The red component.
  11771. *
  11772. * @type {number}
  11773. * @default 1
  11774. */
  11775. this.r = 1;
  11776. /**
  11777. * The green component.
  11778. *
  11779. * @type {number}
  11780. * @default 1
  11781. */
  11782. this.g = 1;
  11783. /**
  11784. * The blue component.
  11785. *
  11786. * @type {number}
  11787. * @default 1
  11788. */
  11789. this.b = 1;
  11790. return this.set( r, g, b );
  11791. }
  11792. /**
  11793. * Sets the colors's components from the given values.
  11794. *
  11795. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11796. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11797. * @param {number} [g] - The green component.
  11798. * @param {number} [b] - The blue component.
  11799. * @return {Color} A reference to this color.
  11800. */
  11801. set( r, g, b ) {
  11802. if ( g === undefined && b === undefined ) {
  11803. // r is THREE.Color, hex or string
  11804. const value = r;
  11805. if ( value && value.isColor ) {
  11806. this.copy( value );
  11807. } else if ( typeof value === 'number' ) {
  11808. this.setHex( value );
  11809. } else if ( typeof value === 'string' ) {
  11810. this.setStyle( value );
  11811. }
  11812. } else {
  11813. this.setRGB( r, g, b );
  11814. }
  11815. return this;
  11816. }
  11817. /**
  11818. * Sets the colors's components to the given scalar value.
  11819. *
  11820. * @param {number} scalar - The scalar value.
  11821. * @return {Color} A reference to this color.
  11822. */
  11823. setScalar( scalar ) {
  11824. this.r = scalar;
  11825. this.g = scalar;
  11826. this.b = scalar;
  11827. return this;
  11828. }
  11829. /**
  11830. * Sets this color from a hexadecimal value.
  11831. *
  11832. * @param {number} hex - The hexadecimal value.
  11833. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11834. * @return {Color} A reference to this color.
  11835. */
  11836. setHex( hex, colorSpace = SRGBColorSpace ) {
  11837. hex = Math.floor( hex );
  11838. this.r = ( hex >> 16 & 255 ) / 255;
  11839. this.g = ( hex >> 8 & 255 ) / 255;
  11840. this.b = ( hex & 255 ) / 255;
  11841. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11842. return this;
  11843. }
  11844. /**
  11845. * Sets this color from RGB values.
  11846. *
  11847. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11848. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11849. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11850. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11851. * @return {Color} A reference to this color.
  11852. */
  11853. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11854. this.r = r;
  11855. this.g = g;
  11856. this.b = b;
  11857. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11858. return this;
  11859. }
  11860. /**
  11861. * Sets this color from RGB values.
  11862. *
  11863. * @param {number} h - Hue value between `0.0` and `1.0`.
  11864. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11865. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11866. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11867. * @return {Color} A reference to this color.
  11868. */
  11869. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11870. // h,s,l ranges are in 0.0 - 1.0
  11871. h = euclideanModulo( h, 1 );
  11872. s = clamp( s, 0, 1 );
  11873. l = clamp( l, 0, 1 );
  11874. if ( s === 0 ) {
  11875. this.r = this.g = this.b = l;
  11876. } else {
  11877. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11878. const q = ( 2 * l ) - p;
  11879. this.r = hue2rgb( q, p, h + 1 / 3 );
  11880. this.g = hue2rgb( q, p, h );
  11881. this.b = hue2rgb( q, p, h - 1 / 3 );
  11882. }
  11883. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11884. return this;
  11885. }
  11886. /**
  11887. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11888. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11889. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  11890. * all 140 color names are supported).
  11891. *
  11892. * @param {string} style - Color as a CSS-style string.
  11893. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11894. * @return {Color} A reference to this color.
  11895. */
  11896. setStyle( style, colorSpace = SRGBColorSpace ) {
  11897. function handleAlpha( string ) {
  11898. if ( string === undefined ) return;
  11899. if ( parseFloat( string ) < 1 ) {
  11900. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  11901. }
  11902. }
  11903. let m;
  11904. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11905. // rgb / hsl
  11906. let color;
  11907. const name = m[ 1 ];
  11908. const components = m[ 2 ];
  11909. switch ( name ) {
  11910. case 'rgb':
  11911. case 'rgba':
  11912. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11913. // rgb(255,0,0) rgba(255,0,0,0.5)
  11914. handleAlpha( color[ 4 ] );
  11915. return this.setRGB(
  11916. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11917. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11918. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11919. colorSpace
  11920. );
  11921. }
  11922. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11923. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11924. handleAlpha( color[ 4 ] );
  11925. return this.setRGB(
  11926. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11927. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11928. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11929. colorSpace
  11930. );
  11931. }
  11932. break;
  11933. case 'hsl':
  11934. case 'hsla':
  11935. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11936. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11937. handleAlpha( color[ 4 ] );
  11938. return this.setHSL(
  11939. parseFloat( color[ 1 ] ) / 360,
  11940. parseFloat( color[ 2 ] ) / 100,
  11941. parseFloat( color[ 3 ] ) / 100,
  11942. colorSpace
  11943. );
  11944. }
  11945. break;
  11946. default:
  11947. warn( 'Color: Unknown color model ' + style );
  11948. }
  11949. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11950. // hex color
  11951. const hex = m[ 1 ];
  11952. const size = hex.length;
  11953. if ( size === 3 ) {
  11954. // #ff0
  11955. return this.setRGB(
  11956. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11957. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11958. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11959. colorSpace
  11960. );
  11961. } else if ( size === 6 ) {
  11962. // #ff0000
  11963. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11964. } else {
  11965. warn( 'Color: Invalid hex color ' + style );
  11966. }
  11967. } else if ( style && style.length > 0 ) {
  11968. return this.setColorName( style, colorSpace );
  11969. }
  11970. return this;
  11971. }
  11972. /**
  11973. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11974. * you don't need the other CSS-style formats.
  11975. *
  11976. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11977. * ```js
  11978. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11979. * ```
  11980. *
  11981. * @param {string} style - The color name.
  11982. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11983. * @return {Color} A reference to this color.
  11984. */
  11985. setColorName( style, colorSpace = SRGBColorSpace ) {
  11986. // color keywords
  11987. const hex = _colorKeywords[ style.toLowerCase() ];
  11988. if ( hex !== undefined ) {
  11989. // red
  11990. this.setHex( hex, colorSpace );
  11991. } else {
  11992. // unknown color
  11993. warn( 'Color: Unknown color ' + style );
  11994. }
  11995. return this;
  11996. }
  11997. /**
  11998. * Returns a new color with copied values from this instance.
  11999. *
  12000. * @return {Color} A clone of this instance.
  12001. */
  12002. clone() {
  12003. return new this.constructor( this.r, this.g, this.b );
  12004. }
  12005. /**
  12006. * Copies the values of the given color to this instance.
  12007. *
  12008. * @param {Color} color - The color to copy.
  12009. * @return {Color} A reference to this color.
  12010. */
  12011. copy( color ) {
  12012. this.r = color.r;
  12013. this.g = color.g;
  12014. this.b = color.b;
  12015. return this;
  12016. }
  12017. /**
  12018. * Copies the given color into this color, and then converts this color from
  12019. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12020. *
  12021. * @param {Color} color - The color to copy/convert.
  12022. * @return {Color} A reference to this color.
  12023. */
  12024. copySRGBToLinear( color ) {
  12025. this.r = SRGBToLinear( color.r );
  12026. this.g = SRGBToLinear( color.g );
  12027. this.b = SRGBToLinear( color.b );
  12028. return this;
  12029. }
  12030. /**
  12031. * Copies the given color into this color, and then converts this color from
  12032. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12033. *
  12034. * @param {Color} color - The color to copy/convert.
  12035. * @return {Color} A reference to this color.
  12036. */
  12037. copyLinearToSRGB( color ) {
  12038. this.r = LinearToSRGB( color.r );
  12039. this.g = LinearToSRGB( color.g );
  12040. this.b = LinearToSRGB( color.b );
  12041. return this;
  12042. }
  12043. /**
  12044. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12045. *
  12046. * @return {Color} A reference to this color.
  12047. */
  12048. convertSRGBToLinear() {
  12049. this.copySRGBToLinear( this );
  12050. return this;
  12051. }
  12052. /**
  12053. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12054. *
  12055. * @return {Color} A reference to this color.
  12056. */
  12057. convertLinearToSRGB() {
  12058. this.copyLinearToSRGB( this );
  12059. return this;
  12060. }
  12061. /**
  12062. * Returns the hexadecimal value of this color.
  12063. *
  12064. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12065. * @return {number} The hexadecimal value.
  12066. */
  12067. getHex( colorSpace = SRGBColorSpace ) {
  12068. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12069. 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 ) );
  12070. }
  12071. /**
  12072. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12073. *
  12074. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12075. * @return {string} The hexadecimal value as a string.
  12076. */
  12077. getHexString( colorSpace = SRGBColorSpace ) {
  12078. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12079. }
  12080. /**
  12081. * Converts the colors RGB values into the HSL format and stores them into the
  12082. * given target object.
  12083. *
  12084. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12085. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12086. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12087. */
  12088. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12089. // h,s,l ranges are in 0.0 - 1.0
  12090. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12091. const r = _color.r, g = _color.g, b = _color.b;
  12092. const max = Math.max( r, g, b );
  12093. const min = Math.min( r, g, b );
  12094. let hue, saturation;
  12095. const lightness = ( min + max ) / 2.0;
  12096. if ( min === max ) {
  12097. hue = 0;
  12098. saturation = 0;
  12099. } else {
  12100. const delta = max - min;
  12101. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12102. switch ( max ) {
  12103. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12104. case g: hue = ( b - r ) / delta + 2; break;
  12105. case b: hue = ( r - g ) / delta + 4; break;
  12106. }
  12107. hue /= 6;
  12108. }
  12109. target.h = hue;
  12110. target.s = saturation;
  12111. target.l = lightness;
  12112. return target;
  12113. }
  12114. /**
  12115. * Returns the RGB values of this color and stores them into the given target object.
  12116. *
  12117. * @param {Color} target - The target color that is used to store the method's result.
  12118. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12119. * @return {Color} The RGB representation of this color.
  12120. */
  12121. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12122. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12123. target.r = _color.r;
  12124. target.g = _color.g;
  12125. target.b = _color.b;
  12126. return target;
  12127. }
  12128. /**
  12129. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12130. *
  12131. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12132. * @return {string} The CSS representation of this color.
  12133. */
  12134. getStyle( colorSpace = SRGBColorSpace ) {
  12135. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12136. const r = _color.r, g = _color.g, b = _color.b;
  12137. if ( colorSpace !== SRGBColorSpace ) {
  12138. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12139. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12140. }
  12141. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12142. }
  12143. /**
  12144. * Adds the given HSL values to this color's values.
  12145. * Internally, this converts the color's RGB values to HSL, adds HSL
  12146. * and then converts the color back to RGB.
  12147. *
  12148. * @param {number} h - Hue value between `0.0` and `1.0`.
  12149. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12150. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12151. * @return {Color} A reference to this color.
  12152. */
  12153. offsetHSL( h, s, l ) {
  12154. this.getHSL( _hslA );
  12155. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12156. }
  12157. /**
  12158. * Adds the RGB values of the given color to the RGB values of this color.
  12159. *
  12160. * @param {Color} color - The color to add.
  12161. * @return {Color} A reference to this color.
  12162. */
  12163. add( color ) {
  12164. this.r += color.r;
  12165. this.g += color.g;
  12166. this.b += color.b;
  12167. return this;
  12168. }
  12169. /**
  12170. * Adds the RGB values of the given colors and stores the result in this instance.
  12171. *
  12172. * @param {Color} color1 - The first color.
  12173. * @param {Color} color2 - The second color.
  12174. * @return {Color} A reference to this color.
  12175. */
  12176. addColors( color1, color2 ) {
  12177. this.r = color1.r + color2.r;
  12178. this.g = color1.g + color2.g;
  12179. this.b = color1.b + color2.b;
  12180. return this;
  12181. }
  12182. /**
  12183. * Adds the given scalar value to the RGB values of this color.
  12184. *
  12185. * @param {number} s - The scalar to add.
  12186. * @return {Color} A reference to this color.
  12187. */
  12188. addScalar( s ) {
  12189. this.r += s;
  12190. this.g += s;
  12191. this.b += s;
  12192. return this;
  12193. }
  12194. /**
  12195. * Subtracts the RGB values of the given color from the RGB values of this color.
  12196. *
  12197. * @param {Color} color - The color to subtract.
  12198. * @return {Color} A reference to this color.
  12199. */
  12200. sub( color ) {
  12201. this.r = Math.max( 0, this.r - color.r );
  12202. this.g = Math.max( 0, this.g - color.g );
  12203. this.b = Math.max( 0, this.b - color.b );
  12204. return this;
  12205. }
  12206. /**
  12207. * Multiplies the RGB values of the given color with the RGB values of this color.
  12208. *
  12209. * @param {Color} color - The color to multiply.
  12210. * @return {Color} A reference to this color.
  12211. */
  12212. multiply( color ) {
  12213. this.r *= color.r;
  12214. this.g *= color.g;
  12215. this.b *= color.b;
  12216. return this;
  12217. }
  12218. /**
  12219. * Multiplies the given scalar value with the RGB values of this color.
  12220. *
  12221. * @param {number} s - The scalar to multiply.
  12222. * @return {Color} A reference to this color.
  12223. */
  12224. multiplyScalar( s ) {
  12225. this.r *= s;
  12226. this.g *= s;
  12227. this.b *= s;
  12228. return this;
  12229. }
  12230. /**
  12231. * Linearly interpolates this color's RGB values toward the RGB values of the
  12232. * given color. The alpha argument can be thought of as the ratio between
  12233. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12234. *
  12235. * @param {Color} color - The color to converge on.
  12236. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12237. * @return {Color} A reference to this color.
  12238. */
  12239. lerp( color, alpha ) {
  12240. this.r += ( color.r - this.r ) * alpha;
  12241. this.g += ( color.g - this.g ) * alpha;
  12242. this.b += ( color.b - this.b ) * alpha;
  12243. return this;
  12244. }
  12245. /**
  12246. * Linearly interpolates between the given colors and stores the result in this instance.
  12247. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12248. * is the first and `1.0` is the second color.
  12249. *
  12250. * @param {Color} color1 - The first color.
  12251. * @param {Color} color2 - The second color.
  12252. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12253. * @return {Color} A reference to this color.
  12254. */
  12255. lerpColors( color1, color2, alpha ) {
  12256. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12257. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12258. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12259. return this;
  12260. }
  12261. /**
  12262. * Linearly interpolates this color's HSL values toward the HSL values of the
  12263. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12264. * from one color to the other, but instead going through all the hues in between
  12265. * those two colors. The alpha argument can be thought of as the ratio between
  12266. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12267. *
  12268. * @param {Color} color - The color to converge on.
  12269. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12270. * @return {Color} A reference to this color.
  12271. */
  12272. lerpHSL( color, alpha ) {
  12273. this.getHSL( _hslA );
  12274. color.getHSL( _hslB );
  12275. const h = lerp( _hslA.h, _hslB.h, alpha );
  12276. const s = lerp( _hslA.s, _hslB.s, alpha );
  12277. const l = lerp( _hslA.l, _hslB.l, alpha );
  12278. this.setHSL( h, s, l );
  12279. return this;
  12280. }
  12281. /**
  12282. * Sets the color's RGB components from the given 3D vector.
  12283. *
  12284. * @param {Vector3} v - The vector to set.
  12285. * @return {Color} A reference to this color.
  12286. */
  12287. setFromVector3( v ) {
  12288. this.r = v.x;
  12289. this.g = v.y;
  12290. this.b = v.z;
  12291. return this;
  12292. }
  12293. /**
  12294. * Transforms this color with the given 3x3 matrix.
  12295. *
  12296. * @param {Matrix3} m - The matrix.
  12297. * @return {Color} A reference to this color.
  12298. */
  12299. applyMatrix3( m ) {
  12300. const r = this.r, g = this.g, b = this.b;
  12301. const e = m.elements;
  12302. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12303. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12304. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12305. return this;
  12306. }
  12307. /**
  12308. * Returns `true` if this color is equal with the given one.
  12309. *
  12310. * @param {Color} c - The color to test for equality.
  12311. * @return {boolean} Whether this bounding color is equal with the given one.
  12312. */
  12313. equals( c ) {
  12314. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12315. }
  12316. /**
  12317. * Sets this color's RGB components from the given array.
  12318. *
  12319. * @param {Array<number>} array - An array holding the RGB values.
  12320. * @param {number} [offset=0] - The offset into the array.
  12321. * @return {Color} A reference to this color.
  12322. */
  12323. fromArray( array, offset = 0 ) {
  12324. this.r = array[ offset ];
  12325. this.g = array[ offset + 1 ];
  12326. this.b = array[ offset + 2 ];
  12327. return this;
  12328. }
  12329. /**
  12330. * Writes the RGB components of this color to the given array. If no array is provided,
  12331. * the method returns a new instance.
  12332. *
  12333. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12334. * @param {number} [offset=0] - Index of the first element in the array.
  12335. * @return {Array<number>} The color components.
  12336. */
  12337. toArray( array = [], offset = 0 ) {
  12338. array[ offset ] = this.r;
  12339. array[ offset + 1 ] = this.g;
  12340. array[ offset + 2 ] = this.b;
  12341. return array;
  12342. }
  12343. /**
  12344. * Sets the components of this color from the given buffer attribute.
  12345. *
  12346. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12347. * @param {number} index - The index into the attribute.
  12348. * @return {Color} A reference to this color.
  12349. */
  12350. fromBufferAttribute( attribute, index ) {
  12351. this.r = attribute.getX( index );
  12352. this.g = attribute.getY( index );
  12353. this.b = attribute.getZ( index );
  12354. return this;
  12355. }
  12356. /**
  12357. * This methods defines the serialization result of this class. Returns the color
  12358. * as a hexadecimal value.
  12359. *
  12360. * @return {number} The hexadecimal value.
  12361. */
  12362. toJSON() {
  12363. return this.getHex();
  12364. }
  12365. *[ Symbol.iterator ]() {
  12366. yield this.r;
  12367. yield this.g;
  12368. yield this.b;
  12369. }
  12370. }
  12371. const _color = /*@__PURE__*/ new Color();
  12372. /**
  12373. * A dictionary with X11 color names.
  12374. *
  12375. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12376. *
  12377. * @static
  12378. * @type {Object}
  12379. */
  12380. Color.NAMES = _colorKeywords;
  12381. let _materialId = 0;
  12382. /**
  12383. * Abstract base class for materials.
  12384. *
  12385. * Materials define the appearance of renderable 3D objects.
  12386. *
  12387. * @abstract
  12388. * @augments EventDispatcher
  12389. */
  12390. class Material extends EventDispatcher {
  12391. /**
  12392. * Constructs a new material.
  12393. */
  12394. constructor() {
  12395. super();
  12396. /**
  12397. * This flag can be used for type testing.
  12398. *
  12399. * @type {boolean}
  12400. * @readonly
  12401. * @default true
  12402. */
  12403. this.isMaterial = true;
  12404. /**
  12405. * The ID of the material.
  12406. *
  12407. * @name Material#id
  12408. * @type {number}
  12409. * @readonly
  12410. */
  12411. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12412. /**
  12413. * The UUID of the material.
  12414. *
  12415. * @type {string}
  12416. * @readonly
  12417. */
  12418. this.uuid = generateUUID();
  12419. /**
  12420. * The name of the material.
  12421. *
  12422. * @type {string}
  12423. */
  12424. this.name = '';
  12425. /**
  12426. * The type property is used for detecting the object type
  12427. * in context of serialization/deserialization.
  12428. *
  12429. * @type {string}
  12430. * @readonly
  12431. */
  12432. this.type = 'Material';
  12433. /**
  12434. * Defines the blending type of the material.
  12435. *
  12436. * It must be set to `CustomBlending` if custom blending properties like
  12437. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12438. * should have any effect.
  12439. *
  12440. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12441. * @default NormalBlending
  12442. */
  12443. this.blending = NormalBlending;
  12444. /**
  12445. * Defines which side of faces will be rendered - front, back or both.
  12446. *
  12447. * @type {(FrontSide|BackSide|DoubleSide)}
  12448. * @default FrontSide
  12449. */
  12450. this.side = FrontSide;
  12451. /**
  12452. * If set to `true`, vertex colors should be used.
  12453. *
  12454. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12455. * four (RGBA) component color buffer attribute is used.
  12456. *
  12457. * @type {boolean}
  12458. * @default false
  12459. */
  12460. this.vertexColors = false;
  12461. /**
  12462. * Defines how transparent the material is.
  12463. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12464. *
  12465. * If the {@link Material#transparent} is not set to `true`,
  12466. * the material will remain fully opaque and this value will only affect its color.
  12467. *
  12468. * @type {number}
  12469. * @default 1
  12470. */
  12471. this.opacity = 1;
  12472. /**
  12473. * Defines whether this material is transparent. This has an effect on
  12474. * rendering as transparent objects need special treatment and are rendered
  12475. * after non-transparent objects.
  12476. *
  12477. * When set to true, the extent to which the material is transparent is
  12478. * controlled by {@link Material#opacity}.
  12479. *
  12480. * @type {boolean}
  12481. * @default false
  12482. */
  12483. this.transparent = false;
  12484. /**
  12485. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12486. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12487. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12488. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12489. *
  12490. * @type {boolean}
  12491. * @default false
  12492. */
  12493. this.alphaHash = false;
  12494. /**
  12495. * Defines the blending source factor.
  12496. *
  12497. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12498. * @default SrcAlphaFactor
  12499. */
  12500. this.blendSrc = SrcAlphaFactor;
  12501. /**
  12502. * Defines the blending destination factor.
  12503. *
  12504. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12505. * @default OneMinusSrcAlphaFactor
  12506. */
  12507. this.blendDst = OneMinusSrcAlphaFactor;
  12508. /**
  12509. * Defines the blending equation.
  12510. *
  12511. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12512. * @default AddEquation
  12513. */
  12514. this.blendEquation = AddEquation;
  12515. /**
  12516. * Defines the blending source alpha factor.
  12517. *
  12518. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12519. * @default null
  12520. */
  12521. this.blendSrcAlpha = null;
  12522. /**
  12523. * Defines the blending destination alpha factor.
  12524. *
  12525. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12526. * @default null
  12527. */
  12528. this.blendDstAlpha = null;
  12529. /**
  12530. * Defines the blending equation of the alpha channel.
  12531. *
  12532. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12533. * @default null
  12534. */
  12535. this.blendEquationAlpha = null;
  12536. /**
  12537. * Represents the RGB values of the constant blend color.
  12538. *
  12539. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12540. *
  12541. * @type {Color}
  12542. * @default (0,0,0)
  12543. */
  12544. this.blendColor = new Color( 0, 0, 0 );
  12545. /**
  12546. * Represents the alpha value of the constant blend color.
  12547. *
  12548. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12549. *
  12550. * @type {number}
  12551. * @default 0
  12552. */
  12553. this.blendAlpha = 0;
  12554. /**
  12555. * Defines the depth function.
  12556. *
  12557. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12558. * @default LessEqualDepth
  12559. */
  12560. this.depthFunc = LessEqualDepth;
  12561. /**
  12562. * Whether to have depth test enabled when rendering this material.
  12563. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12564. *
  12565. * @type {boolean}
  12566. * @default true
  12567. */
  12568. this.depthTest = true;
  12569. /**
  12570. * Whether rendering this material has any effect on the depth buffer.
  12571. *
  12572. * When drawing 2D overlays it can be useful to disable the depth writing in
  12573. * order to layer several things together without creating z-index artifacts.
  12574. *
  12575. * @type {boolean}
  12576. * @default true
  12577. */
  12578. this.depthWrite = true;
  12579. /**
  12580. * The bit mask to use when writing to the stencil buffer.
  12581. *
  12582. * @type {number}
  12583. * @default 0xff
  12584. */
  12585. this.stencilWriteMask = 0xff;
  12586. /**
  12587. * The stencil comparison function to use.
  12588. *
  12589. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12590. * @default AlwaysStencilFunc
  12591. */
  12592. this.stencilFunc = AlwaysStencilFunc;
  12593. /**
  12594. * The value to use when performing stencil comparisons or stencil operations.
  12595. *
  12596. * @type {number}
  12597. * @default 0
  12598. */
  12599. this.stencilRef = 0;
  12600. /**
  12601. * The bit mask to use when comparing against the stencil buffer.
  12602. *
  12603. * @type {number}
  12604. * @default 0xff
  12605. */
  12606. this.stencilFuncMask = 0xff;
  12607. /**
  12608. * Which stencil operation to perform when the comparison function returns `false`.
  12609. *
  12610. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12611. * @default KeepStencilOp
  12612. */
  12613. this.stencilFail = KeepStencilOp;
  12614. /**
  12615. * Which stencil operation to perform when the comparison function returns
  12616. * `true` but the depth test fails.
  12617. *
  12618. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12619. * @default KeepStencilOp
  12620. */
  12621. this.stencilZFail = KeepStencilOp;
  12622. /**
  12623. * Which stencil operation to perform when the comparison function returns
  12624. * `true` and the depth test passes.
  12625. *
  12626. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12627. * @default KeepStencilOp
  12628. */
  12629. this.stencilZPass = KeepStencilOp;
  12630. /**
  12631. * Whether stencil operations are performed against the stencil buffer. In
  12632. * order to perform writes or comparisons against the stencil buffer this
  12633. * value must be `true`.
  12634. *
  12635. * @type {boolean}
  12636. * @default false
  12637. */
  12638. this.stencilWrite = false;
  12639. /**
  12640. * User-defined clipping planes specified as THREE.Plane objects in world
  12641. * space. These planes apply to the objects this material is attached to.
  12642. * Points in space whose signed distance to the plane is negative are clipped
  12643. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12644. * be `true`.
  12645. *
  12646. * @type {?Array<Plane>}
  12647. * @default null
  12648. */
  12649. this.clippingPlanes = null;
  12650. /**
  12651. * Changes the behavior of clipping planes so that only their intersection is
  12652. * clipped, rather than their union.
  12653. *
  12654. * @type {boolean}
  12655. * @default false
  12656. */
  12657. this.clipIntersection = false;
  12658. /**
  12659. * Defines whether to clip shadows according to the clipping planes specified
  12660. * on this material.
  12661. *
  12662. * @type {boolean}
  12663. * @default false
  12664. */
  12665. this.clipShadows = false;
  12666. /**
  12667. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12668. * is determined as follows:
  12669. *
  12670. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12671. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12672. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12673. *
  12674. * @type {?(FrontSide|BackSide|DoubleSide)}
  12675. * @default null
  12676. */
  12677. this.shadowSide = null;
  12678. /**
  12679. * Whether to render the material's color.
  12680. *
  12681. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12682. * objects that occlude other objects.
  12683. *
  12684. * @type {boolean}
  12685. * @default true
  12686. */
  12687. this.colorWrite = true;
  12688. /**
  12689. * Override the renderer's default precision for this material.
  12690. *
  12691. * @type {?('highp'|'mediump'|'lowp')}
  12692. * @default null
  12693. */
  12694. this.precision = null;
  12695. /**
  12696. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12697. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12698. * The offset is added before the depth test is performed and before the value is written
  12699. * into the depth buffer.
  12700. *
  12701. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12702. * rendering solids with highlighted edges.
  12703. *
  12704. * @type {boolean}
  12705. * @default false
  12706. */
  12707. this.polygonOffset = false;
  12708. /**
  12709. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12710. *
  12711. * @type {number}
  12712. * @default 0
  12713. */
  12714. this.polygonOffsetFactor = 0;
  12715. /**
  12716. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12717. *
  12718. * @type {number}
  12719. * @default 0
  12720. */
  12721. this.polygonOffsetUnits = 0;
  12722. /**
  12723. * Whether to apply dithering to the color to remove the appearance of banding.
  12724. *
  12725. * @type {boolean}
  12726. * @default false
  12727. */
  12728. this.dithering = false;
  12729. /**
  12730. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12731. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12732. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12733. *
  12734. * @type {boolean}
  12735. * @default false
  12736. */
  12737. this.alphaToCoverage = false;
  12738. /**
  12739. * Whether to premultiply the alpha (transparency) value.
  12740. *
  12741. * @type {boolean}
  12742. * @default false
  12743. */
  12744. this.premultipliedAlpha = false;
  12745. /**
  12746. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12747. *
  12748. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12749. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12750. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12751. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12752. * disable the two pass rendering to avoid performance issues.
  12753. *
  12754. * @type {boolean}
  12755. * @default false
  12756. */
  12757. this.forceSinglePass = false;
  12758. /**
  12759. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12760. *
  12761. * @type {boolean}
  12762. * @default true
  12763. */
  12764. this.allowOverride = true;
  12765. /**
  12766. * Defines whether 3D objects using this material are visible.
  12767. *
  12768. * @type {boolean}
  12769. * @default true
  12770. */
  12771. this.visible = true;
  12772. /**
  12773. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12774. *
  12775. * It is ignored when rendering to a render target or using post processing or when using
  12776. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12777. *
  12778. * @type {boolean}
  12779. * @default true
  12780. */
  12781. this.toneMapped = true;
  12782. /**
  12783. * An object that can be used to store custom data about the Material. It
  12784. * should not hold references to functions as these will not be cloned.
  12785. *
  12786. * @type {Object}
  12787. */
  12788. this.userData = {};
  12789. /**
  12790. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12791. *
  12792. * @type {number}
  12793. * @readonly
  12794. * @default 0
  12795. */
  12796. this.version = 0;
  12797. this._alphaTest = 0;
  12798. }
  12799. /**
  12800. * Sets the alpha value to be used when running an alpha test. The material
  12801. * will not be rendered if the opacity is lower than this value.
  12802. *
  12803. * @type {number}
  12804. * @readonly
  12805. * @default 0
  12806. */
  12807. get alphaTest() {
  12808. return this._alphaTest;
  12809. }
  12810. set alphaTest( value ) {
  12811. if ( this._alphaTest > 0 !== value > 0 ) {
  12812. this.version ++;
  12813. }
  12814. this._alphaTest = value;
  12815. }
  12816. /**
  12817. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12818. *
  12819. * This method can only be used when rendering with {@link WebGLRenderer}.
  12820. *
  12821. * @param {WebGLRenderer} renderer - The renderer.
  12822. * @param {Scene} scene - The scene.
  12823. * @param {Camera} camera - The camera that is used to render the scene.
  12824. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12825. * @param {Object3D} object - The 3D object.
  12826. * @param {Object} group - The geometry group data.
  12827. */
  12828. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12829. /**
  12830. * An optional callback that is executed immediately before the shader
  12831. * program is compiled. This function is called with the shader source code
  12832. * as a parameter. Useful for the modification of built-in materials.
  12833. *
  12834. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12835. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12836. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12837. *
  12838. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12839. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12840. */
  12841. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12842. /**
  12843. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12844. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12845. * shader or recompile the shader for this material as needed.
  12846. *
  12847. * This method can only be used when rendering with {@link WebGLRenderer}.
  12848. *
  12849. * @return {string} The custom program cache key.
  12850. */
  12851. customProgramCacheKey() {
  12852. return this.onBeforeCompile.toString();
  12853. }
  12854. /**
  12855. * This method can be used to set default values from parameter objects.
  12856. * It is a generic implementation so it can be used with different types
  12857. * of materials.
  12858. *
  12859. * @param {Object} [values] - The material values to set.
  12860. */
  12861. setValues( values ) {
  12862. if ( values === undefined ) return;
  12863. for ( const key in values ) {
  12864. const newValue = values[ key ];
  12865. if ( newValue === undefined ) {
  12866. warn( `Material: parameter '${ key }' has value of undefined.` );
  12867. continue;
  12868. }
  12869. const currentValue = this[ key ];
  12870. if ( currentValue === undefined ) {
  12871. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12872. continue;
  12873. }
  12874. if ( currentValue && currentValue.isColor ) {
  12875. currentValue.set( newValue );
  12876. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12877. currentValue.copy( newValue );
  12878. } else {
  12879. this[ key ] = newValue;
  12880. }
  12881. }
  12882. }
  12883. /**
  12884. * Serializes the material into JSON.
  12885. *
  12886. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12887. * @return {Object} A JSON object representing the serialized material.
  12888. * @see {@link ObjectLoader#parse}
  12889. */
  12890. toJSON( meta ) {
  12891. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12892. if ( isRootObject ) {
  12893. meta = {
  12894. textures: {},
  12895. images: {}
  12896. };
  12897. }
  12898. const data = {
  12899. metadata: {
  12900. version: 4.7,
  12901. type: 'Material',
  12902. generator: 'Material.toJSON'
  12903. }
  12904. };
  12905. // standard Material serialization
  12906. data.uuid = this.uuid;
  12907. data.type = this.type;
  12908. if ( this.name !== '' ) data.name = this.name;
  12909. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12910. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12911. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12912. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12913. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12914. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12915. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12916. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12917. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12918. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12919. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12920. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12921. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12922. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12923. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12924. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12925. }
  12926. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12927. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12928. }
  12929. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12930. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12931. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12932. }
  12933. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12934. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12935. }
  12936. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12937. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12938. }
  12939. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12940. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12941. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12942. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12943. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12944. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12945. }
  12946. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12947. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12948. }
  12949. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12950. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12951. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12952. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12953. }
  12954. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12955. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12956. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12957. if ( this.lightMap && this.lightMap.isTexture ) {
  12958. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12959. data.lightMapIntensity = this.lightMapIntensity;
  12960. }
  12961. if ( this.aoMap && this.aoMap.isTexture ) {
  12962. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12963. data.aoMapIntensity = this.aoMapIntensity;
  12964. }
  12965. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12966. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12967. data.bumpScale = this.bumpScale;
  12968. }
  12969. if ( this.normalMap && this.normalMap.isTexture ) {
  12970. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12971. data.normalMapType = this.normalMapType;
  12972. data.normalScale = this.normalScale.toArray();
  12973. }
  12974. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12975. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12976. data.displacementScale = this.displacementScale;
  12977. data.displacementBias = this.displacementBias;
  12978. }
  12979. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12980. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12981. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12982. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12983. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12984. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12985. if ( this.envMap && this.envMap.isTexture ) {
  12986. data.envMap = this.envMap.toJSON( meta ).uuid;
  12987. if ( this.combine !== undefined ) data.combine = this.combine;
  12988. }
  12989. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12990. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12991. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12992. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12993. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12994. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12995. }
  12996. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12997. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12998. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12999. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  13000. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  13001. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  13002. if ( this.size !== undefined ) data.size = this.size;
  13003. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  13004. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  13005. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  13006. if ( this.side !== FrontSide ) data.side = this.side;
  13007. if ( this.vertexColors === true ) data.vertexColors = true;
  13008. if ( this.opacity < 1 ) data.opacity = this.opacity;
  13009. if ( this.transparent === true ) data.transparent = true;
  13010. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  13011. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  13012. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  13013. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  13014. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  13015. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  13016. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  13017. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  13018. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  13019. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  13020. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  13021. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  13022. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  13023. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  13024. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  13025. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  13026. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  13027. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  13028. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  13029. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  13030. // rotation (SpriteMaterial)
  13031. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  13032. if ( this.polygonOffset === true ) data.polygonOffset = true;
  13033. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  13034. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  13035. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  13036. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  13037. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  13038. if ( this.scale !== undefined ) data.scale = this.scale;
  13039. if ( this.dithering === true ) data.dithering = true;
  13040. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  13041. if ( this.alphaHash === true ) data.alphaHash = true;
  13042. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  13043. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  13044. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  13045. if ( this.allowOverride === false ) data.allowOverride = false;
  13046. if ( this.wireframe === true ) data.wireframe = true;
  13047. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  13048. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  13049. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13050. if ( this.flatShading === true ) data.flatShading = true;
  13051. if ( this.visible === false ) data.visible = false;
  13052. if ( this.toneMapped === false ) data.toneMapped = false;
  13053. if ( this.fog === false ) data.fog = false;
  13054. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13055. // TODO: Copied from Object3D.toJSON
  13056. function extractFromCache( cache ) {
  13057. const values = [];
  13058. for ( const key in cache ) {
  13059. const data = cache[ key ];
  13060. delete data.metadata;
  13061. values.push( data );
  13062. }
  13063. return values;
  13064. }
  13065. if ( isRootObject ) {
  13066. const textures = extractFromCache( meta.textures );
  13067. const images = extractFromCache( meta.images );
  13068. if ( textures.length > 0 ) data.textures = textures;
  13069. if ( images.length > 0 ) data.images = images;
  13070. }
  13071. return data;
  13072. }
  13073. /**
  13074. * Returns a new material with copied values from this instance.
  13075. *
  13076. * @return {Material} A clone of this instance.
  13077. */
  13078. clone() {
  13079. return new this.constructor().copy( this );
  13080. }
  13081. /**
  13082. * Copies the values of the given material to this instance.
  13083. *
  13084. * @param {Material} source - The material to copy.
  13085. * @return {Material} A reference to this instance.
  13086. */
  13087. copy( source ) {
  13088. this.name = source.name;
  13089. this.blending = source.blending;
  13090. this.side = source.side;
  13091. this.vertexColors = source.vertexColors;
  13092. this.opacity = source.opacity;
  13093. this.transparent = source.transparent;
  13094. this.blendSrc = source.blendSrc;
  13095. this.blendDst = source.blendDst;
  13096. this.blendEquation = source.blendEquation;
  13097. this.blendSrcAlpha = source.blendSrcAlpha;
  13098. this.blendDstAlpha = source.blendDstAlpha;
  13099. this.blendEquationAlpha = source.blendEquationAlpha;
  13100. this.blendColor.copy( source.blendColor );
  13101. this.blendAlpha = source.blendAlpha;
  13102. this.depthFunc = source.depthFunc;
  13103. this.depthTest = source.depthTest;
  13104. this.depthWrite = source.depthWrite;
  13105. this.stencilWriteMask = source.stencilWriteMask;
  13106. this.stencilFunc = source.stencilFunc;
  13107. this.stencilRef = source.stencilRef;
  13108. this.stencilFuncMask = source.stencilFuncMask;
  13109. this.stencilFail = source.stencilFail;
  13110. this.stencilZFail = source.stencilZFail;
  13111. this.stencilZPass = source.stencilZPass;
  13112. this.stencilWrite = source.stencilWrite;
  13113. const srcPlanes = source.clippingPlanes;
  13114. let dstPlanes = null;
  13115. if ( srcPlanes !== null ) {
  13116. const n = srcPlanes.length;
  13117. dstPlanes = new Array( n );
  13118. for ( let i = 0; i !== n; ++ i ) {
  13119. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13120. }
  13121. }
  13122. this.clippingPlanes = dstPlanes;
  13123. this.clipIntersection = source.clipIntersection;
  13124. this.clipShadows = source.clipShadows;
  13125. this.shadowSide = source.shadowSide;
  13126. this.colorWrite = source.colorWrite;
  13127. this.precision = source.precision;
  13128. this.polygonOffset = source.polygonOffset;
  13129. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13130. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13131. this.dithering = source.dithering;
  13132. this.alphaTest = source.alphaTest;
  13133. this.alphaHash = source.alphaHash;
  13134. this.alphaToCoverage = source.alphaToCoverage;
  13135. this.premultipliedAlpha = source.premultipliedAlpha;
  13136. this.forceSinglePass = source.forceSinglePass;
  13137. this.allowOverride = source.allowOverride;
  13138. this.visible = source.visible;
  13139. this.toneMapped = source.toneMapped;
  13140. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13141. return this;
  13142. }
  13143. /**
  13144. * Frees the GPU-related resources allocated by this instance. Call this
  13145. * method whenever this instance is no longer used in your app.
  13146. *
  13147. * @fires Material#dispose
  13148. */
  13149. dispose() {
  13150. /**
  13151. * Fires when the material has been disposed of.
  13152. *
  13153. * @event Material#dispose
  13154. * @type {Object}
  13155. */
  13156. this.dispatchEvent( { type: 'dispose' } );
  13157. }
  13158. /**
  13159. * Setting this property to `true` indicates the engine the material
  13160. * needs to be recompiled.
  13161. *
  13162. * @type {boolean}
  13163. * @default false
  13164. * @param {boolean} value
  13165. */
  13166. set needsUpdate( value ) {
  13167. if ( value === true ) this.version ++;
  13168. }
  13169. }
  13170. /**
  13171. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13172. *
  13173. * This material is not affected by lights.
  13174. *
  13175. * @augments Material
  13176. * @demo scenes/material-browser.html#MeshBasicMaterial
  13177. */
  13178. class MeshBasicMaterial extends Material {
  13179. /**
  13180. * Constructs a new mesh basic material.
  13181. *
  13182. * @param {Object} [parameters] - An object with one or more properties
  13183. * defining the material's appearance. Any property of the material
  13184. * (including any property from inherited materials) can be passed
  13185. * in here. Color values can be passed any type of value accepted
  13186. * by {@link Color#set}.
  13187. */
  13188. constructor( parameters ) {
  13189. super();
  13190. /**
  13191. * This flag can be used for type testing.
  13192. *
  13193. * @type {boolean}
  13194. * @readonly
  13195. * @default true
  13196. */
  13197. this.isMeshBasicMaterial = true;
  13198. this.type = 'MeshBasicMaterial';
  13199. /**
  13200. * Color of the material.
  13201. *
  13202. * @type {Color}
  13203. * @default (1,1,1)
  13204. */
  13205. this.color = new Color( 0xffffff ); // diffuse
  13206. /**
  13207. * The color map. May optionally include an alpha channel, typically combined
  13208. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13209. * color is modulated by the diffuse `color`.
  13210. *
  13211. * @type {?Texture}
  13212. * @default null
  13213. */
  13214. this.map = null;
  13215. /**
  13216. * The light map. Requires a second set of UVs.
  13217. *
  13218. * @type {?Texture}
  13219. * @default null
  13220. */
  13221. this.lightMap = null;
  13222. /**
  13223. * Intensity of the baked light.
  13224. *
  13225. * @type {number}
  13226. * @default 1
  13227. */
  13228. this.lightMapIntensity = 1.0;
  13229. /**
  13230. * The red channel of this texture is used as the ambient occlusion map.
  13231. * Requires a second set of UVs.
  13232. *
  13233. * @type {?Texture}
  13234. * @default null
  13235. */
  13236. this.aoMap = null;
  13237. /**
  13238. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13239. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13240. * red channel is also `1`, ambient light is fully occluded on a surface.
  13241. *
  13242. * @type {number}
  13243. * @default 1
  13244. */
  13245. this.aoMapIntensity = 1.0;
  13246. /**
  13247. * Specular map used by the material.
  13248. *
  13249. * @type {?Texture}
  13250. * @default null
  13251. */
  13252. this.specularMap = null;
  13253. /**
  13254. * The alpha map is a grayscale texture that controls the opacity across the
  13255. * surface (black: fully transparent; white: fully opaque).
  13256. *
  13257. * Only the color of the texture is used, ignoring the alpha channel if one
  13258. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13259. * when sampling this texture due to the extra bit of precision provided for
  13260. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13261. * luminance/alpha textures will also still work as expected.
  13262. *
  13263. * @type {?Texture}
  13264. * @default null
  13265. */
  13266. this.alphaMap = null;
  13267. /**
  13268. * The environment map.
  13269. *
  13270. * @type {?Texture}
  13271. * @default null
  13272. */
  13273. this.envMap = null;
  13274. /**
  13275. * The rotation of the environment map in radians.
  13276. *
  13277. * @type {Euler}
  13278. * @default (0,0,0)
  13279. */
  13280. this.envMapRotation = new Euler();
  13281. /**
  13282. * How to combine the result of the surface's color with the environment map, if any.
  13283. *
  13284. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13285. * blend between the two colors.
  13286. *
  13287. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13288. * @default MultiplyOperation
  13289. */
  13290. this.combine = MultiplyOperation;
  13291. /**
  13292. * How much the environment map affects the surface.
  13293. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13294. *
  13295. * @type {number}
  13296. * @default 1
  13297. */
  13298. this.reflectivity = 1;
  13299. /**
  13300. * The index of refraction (IOR) of air (approximately 1) divided by the
  13301. * index of refraction of the material. It is used with environment mapping
  13302. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13303. * The refraction ratio should not exceed `1`.
  13304. *
  13305. * @type {number}
  13306. * @default 0.98
  13307. */
  13308. this.refractionRatio = 0.98;
  13309. /**
  13310. * Renders the geometry as a wireframe.
  13311. *
  13312. * @type {boolean}
  13313. * @default false
  13314. */
  13315. this.wireframe = false;
  13316. /**
  13317. * Controls the thickness of the wireframe.
  13318. *
  13319. * Can only be used with {@link SVGRenderer}.
  13320. *
  13321. * @type {number}
  13322. * @default 1
  13323. */
  13324. this.wireframeLinewidth = 1;
  13325. /**
  13326. * Defines appearance of wireframe ends.
  13327. *
  13328. * Can only be used with {@link SVGRenderer}.
  13329. *
  13330. * @type {('round'|'bevel'|'miter')}
  13331. * @default 'round'
  13332. */
  13333. this.wireframeLinecap = 'round';
  13334. /**
  13335. * Defines appearance of wireframe joints.
  13336. *
  13337. * Can only be used with {@link SVGRenderer}.
  13338. *
  13339. * @type {('round'|'bevel'|'miter')}
  13340. * @default 'round'
  13341. */
  13342. this.wireframeLinejoin = 'round';
  13343. /**
  13344. * Whether the material is affected by fog or not.
  13345. *
  13346. * @type {boolean}
  13347. * @default true
  13348. */
  13349. this.fog = true;
  13350. this.setValues( parameters );
  13351. }
  13352. copy( source ) {
  13353. super.copy( source );
  13354. this.color.copy( source.color );
  13355. this.map = source.map;
  13356. this.lightMap = source.lightMap;
  13357. this.lightMapIntensity = source.lightMapIntensity;
  13358. this.aoMap = source.aoMap;
  13359. this.aoMapIntensity = source.aoMapIntensity;
  13360. this.specularMap = source.specularMap;
  13361. this.alphaMap = source.alphaMap;
  13362. this.envMap = source.envMap;
  13363. this.envMapRotation.copy( source.envMapRotation );
  13364. this.combine = source.combine;
  13365. this.reflectivity = source.reflectivity;
  13366. this.refractionRatio = source.refractionRatio;
  13367. this.wireframe = source.wireframe;
  13368. this.wireframeLinewidth = source.wireframeLinewidth;
  13369. this.wireframeLinecap = source.wireframeLinecap;
  13370. this.wireframeLinejoin = source.wireframeLinejoin;
  13371. this.fog = source.fog;
  13372. return this;
  13373. }
  13374. }
  13375. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13376. const _tables = /*@__PURE__*/ _generateTables();
  13377. function _generateTables() {
  13378. // float32 to float16 helpers
  13379. const buffer = new ArrayBuffer( 4 );
  13380. const floatView = new Float32Array( buffer );
  13381. const uint32View = new Uint32Array( buffer );
  13382. const baseTable = new Uint32Array( 512 );
  13383. const shiftTable = new Uint32Array( 512 );
  13384. for ( let i = 0; i < 256; ++ i ) {
  13385. const e = i - 127;
  13386. // very small number (0, -0)
  13387. if ( e < -27 ) {
  13388. baseTable[ i ] = 0x0000;
  13389. baseTable[ i | 0x100 ] = 0x8000;
  13390. shiftTable[ i ] = 24;
  13391. shiftTable[ i | 0x100 ] = 24;
  13392. // small number (denorm)
  13393. } else if ( e < -14 ) {
  13394. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13395. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13396. shiftTable[ i ] = - e - 1;
  13397. shiftTable[ i | 0x100 ] = - e - 1;
  13398. // normal number
  13399. } else if ( e <= 15 ) {
  13400. baseTable[ i ] = ( e + 15 ) << 10;
  13401. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13402. shiftTable[ i ] = 13;
  13403. shiftTable[ i | 0x100 ] = 13;
  13404. // large number (Infinity, -Infinity)
  13405. } else if ( e < 128 ) {
  13406. baseTable[ i ] = 0x7c00;
  13407. baseTable[ i | 0x100 ] = 0xfc00;
  13408. shiftTable[ i ] = 24;
  13409. shiftTable[ i | 0x100 ] = 24;
  13410. // stay (NaN, Infinity, -Infinity)
  13411. } else {
  13412. baseTable[ i ] = 0x7c00;
  13413. baseTable[ i | 0x100 ] = 0xfc00;
  13414. shiftTable[ i ] = 13;
  13415. shiftTable[ i | 0x100 ] = 13;
  13416. }
  13417. }
  13418. // float16 to float32 helpers
  13419. const mantissaTable = new Uint32Array( 2048 );
  13420. const exponentTable = new Uint32Array( 64 );
  13421. const offsetTable = new Uint32Array( 64 );
  13422. for ( let i = 1; i < 1024; ++ i ) {
  13423. let m = i << 13; // zero pad mantissa bits
  13424. let e = 0; // zero exponent
  13425. // normalized
  13426. while ( ( m & 0x00800000 ) === 0 ) {
  13427. m <<= 1;
  13428. e -= 0x00800000; // decrement exponent
  13429. }
  13430. m &= -8388609; // clear leading 1 bit
  13431. e += 0x38800000; // adjust bias
  13432. mantissaTable[ i ] = m | e;
  13433. }
  13434. for ( let i = 1024; i < 2048; ++ i ) {
  13435. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13436. }
  13437. for ( let i = 1; i < 31; ++ i ) {
  13438. exponentTable[ i ] = i << 23;
  13439. }
  13440. exponentTable[ 31 ] = 0x47800000;
  13441. exponentTable[ 32 ] = 0x80000000;
  13442. for ( let i = 33; i < 63; ++ i ) {
  13443. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13444. }
  13445. exponentTable[ 63 ] = 0xc7800000;
  13446. for ( let i = 1; i < 64; ++ i ) {
  13447. if ( i !== 32 ) {
  13448. offsetTable[ i ] = 1024;
  13449. }
  13450. }
  13451. return {
  13452. floatView: floatView,
  13453. uint32View: uint32View,
  13454. baseTable: baseTable,
  13455. shiftTable: shiftTable,
  13456. mantissaTable: mantissaTable,
  13457. exponentTable: exponentTable,
  13458. offsetTable: offsetTable
  13459. };
  13460. }
  13461. /**
  13462. * Returns a half precision floating point value (FP16) from the given single
  13463. * precision floating point value (FP32).
  13464. *
  13465. * @param {number} val - A single precision floating point value.
  13466. * @return {number} The FP16 value.
  13467. */
  13468. function toHalfFloat( val ) {
  13469. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13470. val = clamp( val, -65504, 65504 );
  13471. _tables.floatView[ 0 ] = val;
  13472. const f = _tables.uint32View[ 0 ];
  13473. const e = ( f >> 23 ) & 0x1ff;
  13474. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13475. }
  13476. /**
  13477. * Returns a single precision floating point value (FP32) from the given half
  13478. * precision floating point value (FP16).
  13479. *
  13480. * @param {number} val - A half precision floating point value.
  13481. * @return {number} The FP32 value.
  13482. */
  13483. function fromHalfFloat( val ) {
  13484. const m = val >> 10;
  13485. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13486. return _tables.floatView[ 0 ];
  13487. }
  13488. /**
  13489. * A class containing utility functions for data.
  13490. *
  13491. * @hideconstructor
  13492. */
  13493. class DataUtils {
  13494. /**
  13495. * Returns a half precision floating point value (FP16) from the given single
  13496. * precision floating point value (FP32).
  13497. *
  13498. * @param {number} val - A single precision floating point value.
  13499. * @return {number} The FP16 value.
  13500. */
  13501. static toHalfFloat( val ) {
  13502. return toHalfFloat( val );
  13503. }
  13504. /**
  13505. * Returns a single precision floating point value (FP32) from the given half
  13506. * precision floating point value (FP16).
  13507. *
  13508. * @param {number} val - A half precision floating point value.
  13509. * @return {number} The FP32 value.
  13510. */
  13511. static fromHalfFloat( val ) {
  13512. return fromHalfFloat( val );
  13513. }
  13514. }
  13515. const _vector$9 = /*@__PURE__*/ new Vector3();
  13516. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13517. let _id$3 = 0;
  13518. /**
  13519. * This class stores data for an attribute (such as vertex positions, face
  13520. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13521. * a geometry, which allows for more efficient passing of data to the GPU.
  13522. *
  13523. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13524. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13525. */
  13526. class BufferAttribute {
  13527. /**
  13528. * Constructs a new buffer attribute.
  13529. *
  13530. * @param {TypedArray} array - The array holding the attribute data.
  13531. * @param {number} itemSize - The item size.
  13532. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13533. */
  13534. constructor( array, itemSize, normalized = false ) {
  13535. if ( Array.isArray( array ) ) {
  13536. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13537. }
  13538. /**
  13539. * This flag can be used for type testing.
  13540. *
  13541. * @type {boolean}
  13542. * @readonly
  13543. * @default true
  13544. */
  13545. this.isBufferAttribute = true;
  13546. /**
  13547. * The ID of the buffer attribute.
  13548. *
  13549. * @name BufferAttribute#id
  13550. * @type {number}
  13551. * @readonly
  13552. */
  13553. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13554. /**
  13555. * The name of the buffer attribute.
  13556. *
  13557. * @type {string}
  13558. */
  13559. this.name = '';
  13560. /**
  13561. * The array holding the attribute data. It should have `itemSize * numVertices`
  13562. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13563. *
  13564. * @type {TypedArray}
  13565. */
  13566. this.array = array;
  13567. /**
  13568. * The number of values of the array that should be associated with a particular vertex.
  13569. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13570. * normal, or color), then the value should be `3`.
  13571. *
  13572. * @type {number}
  13573. */
  13574. this.itemSize = itemSize;
  13575. /**
  13576. * Represents the number of items this buffer attribute stores. It is internally computed
  13577. * by dividing the `array` length by the `itemSize`.
  13578. *
  13579. * @type {number}
  13580. * @readonly
  13581. */
  13582. this.count = array !== undefined ? array.length / itemSize : 0;
  13583. /**
  13584. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13585. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13586. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13587. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13588. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13589. *
  13590. * @type {boolean}
  13591. */
  13592. this.normalized = normalized;
  13593. /**
  13594. * Defines the intended usage pattern of the data store for optimization purposes.
  13595. *
  13596. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13597. * instantiate a new one and set the desired usage before the next render.
  13598. *
  13599. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13600. * @default StaticDrawUsage
  13601. */
  13602. this.usage = StaticDrawUsage;
  13603. /**
  13604. * This can be used to only update some components of stored vectors (for example, just the
  13605. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13606. *
  13607. * @type {Array<Object>}
  13608. */
  13609. this.updateRanges = [];
  13610. /**
  13611. * Configures the bound GPU type for use in shaders.
  13612. *
  13613. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13614. * For lower precision float types, use `Float16BufferAttribute`.
  13615. *
  13616. * @type {(FloatType|IntType)}
  13617. * @default FloatType
  13618. */
  13619. this.gpuType = FloatType;
  13620. /**
  13621. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13622. *
  13623. * @type {number}
  13624. */
  13625. this.version = 0;
  13626. }
  13627. /**
  13628. * A callback function that is executed after the renderer has transferred the attribute
  13629. * array data to the GPU.
  13630. */
  13631. onUploadCallback() {}
  13632. /**
  13633. * Flag to indicate that this attribute has changed and should be re-sent to
  13634. * the GPU. Set this to `true` when you modify the value of the array.
  13635. *
  13636. * @type {number}
  13637. * @default false
  13638. * @param {boolean} value
  13639. */
  13640. set needsUpdate( value ) {
  13641. if ( value === true ) this.version ++;
  13642. }
  13643. /**
  13644. * Sets the usage of this buffer attribute.
  13645. *
  13646. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13647. * @return {BufferAttribute} A reference to this buffer attribute.
  13648. */
  13649. setUsage( value ) {
  13650. this.usage = value;
  13651. return this;
  13652. }
  13653. /**
  13654. * Adds a range of data in the data array to be updated on the GPU.
  13655. *
  13656. * @param {number} start - Position at which to start update.
  13657. * @param {number} count - The number of components to update.
  13658. */
  13659. addUpdateRange( start, count ) {
  13660. this.updateRanges.push( { start, count } );
  13661. }
  13662. /**
  13663. * Clears the update ranges.
  13664. */
  13665. clearUpdateRanges() {
  13666. this.updateRanges.length = 0;
  13667. }
  13668. /**
  13669. * Copies the values of the given buffer attribute to this instance.
  13670. *
  13671. * @param {BufferAttribute} source - The buffer attribute to copy.
  13672. * @return {BufferAttribute} A reference to this instance.
  13673. */
  13674. copy( source ) {
  13675. this.name = source.name;
  13676. this.array = new source.array.constructor( source.array );
  13677. this.itemSize = source.itemSize;
  13678. this.count = source.count;
  13679. this.normalized = source.normalized;
  13680. this.usage = source.usage;
  13681. this.gpuType = source.gpuType;
  13682. return this;
  13683. }
  13684. /**
  13685. * Copies a vector from the given buffer attribute to this one. The start
  13686. * and destination position in the attribute buffers are represented by the
  13687. * given indices.
  13688. *
  13689. * @param {number} index1 - The destination index into this buffer attribute.
  13690. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13691. * @param {number} index2 - The source index into the given buffer attribute.
  13692. * @return {BufferAttribute} A reference to this instance.
  13693. */
  13694. copyAt( index1, attribute, index2 ) {
  13695. index1 *= this.itemSize;
  13696. index2 *= attribute.itemSize;
  13697. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13698. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13699. }
  13700. return this;
  13701. }
  13702. /**
  13703. * Copies the given array data into this buffer attribute.
  13704. *
  13705. * @param {(TypedArray|Array)} array - The array to copy.
  13706. * @return {BufferAttribute} A reference to this instance.
  13707. */
  13708. copyArray( array ) {
  13709. this.array.set( array );
  13710. return this;
  13711. }
  13712. /**
  13713. * Applies the given 3x3 matrix to the given attribute. Works with
  13714. * item size `2` and `3`.
  13715. *
  13716. * @param {Matrix3} m - The matrix to apply.
  13717. * @return {BufferAttribute} A reference to this instance.
  13718. */
  13719. applyMatrix3( m ) {
  13720. if ( this.itemSize === 2 ) {
  13721. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13722. _vector2$1.fromBufferAttribute( this, i );
  13723. _vector2$1.applyMatrix3( m );
  13724. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13725. }
  13726. } else if ( this.itemSize === 3 ) {
  13727. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13728. _vector$9.fromBufferAttribute( this, i );
  13729. _vector$9.applyMatrix3( m );
  13730. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13731. }
  13732. }
  13733. return this;
  13734. }
  13735. /**
  13736. * Applies the given 4x4 matrix to the given attribute. Only works with
  13737. * item size `3`.
  13738. *
  13739. * @param {Matrix4} m - The matrix to apply.
  13740. * @return {BufferAttribute} A reference to this instance.
  13741. */
  13742. applyMatrix4( m ) {
  13743. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13744. _vector$9.fromBufferAttribute( this, i );
  13745. _vector$9.applyMatrix4( m );
  13746. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13747. }
  13748. return this;
  13749. }
  13750. /**
  13751. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13752. * item size `3`.
  13753. *
  13754. * @param {Matrix3} m - The normal matrix to apply.
  13755. * @return {BufferAttribute} A reference to this instance.
  13756. */
  13757. applyNormalMatrix( m ) {
  13758. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13759. _vector$9.fromBufferAttribute( this, i );
  13760. _vector$9.applyNormalMatrix( m );
  13761. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13762. }
  13763. return this;
  13764. }
  13765. /**
  13766. * Applies the given 4x4 matrix to the given attribute. Only works with
  13767. * item size `3` and with direction vectors.
  13768. *
  13769. * @param {Matrix4} m - The matrix to apply.
  13770. * @return {BufferAttribute} A reference to this instance.
  13771. */
  13772. transformDirection( m ) {
  13773. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13774. _vector$9.fromBufferAttribute( this, i );
  13775. _vector$9.transformDirection( m );
  13776. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13777. }
  13778. return this;
  13779. }
  13780. /**
  13781. * Sets the given array data in the buffer attribute.
  13782. *
  13783. * @param {(TypedArray|Array)} value - The array data to set.
  13784. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13785. * @return {BufferAttribute} A reference to this instance.
  13786. */
  13787. set( value, offset = 0 ) {
  13788. // Matching BufferAttribute constructor, do not normalize the array.
  13789. this.array.set( value, offset );
  13790. return this;
  13791. }
  13792. /**
  13793. * Returns the given component of the vector at the given index.
  13794. *
  13795. * @param {number} index - The index into the buffer attribute.
  13796. * @param {number} component - The component index.
  13797. * @return {number} The returned value.
  13798. */
  13799. getComponent( index, component ) {
  13800. let value = this.array[ index * this.itemSize + component ];
  13801. if ( this.normalized ) value = denormalize( value, this.array );
  13802. return value;
  13803. }
  13804. /**
  13805. * Sets the given value to the given component of the vector at the given index.
  13806. *
  13807. * @param {number} index - The index into the buffer attribute.
  13808. * @param {number} component - The component index.
  13809. * @param {number} value - The value to set.
  13810. * @return {BufferAttribute} A reference to this instance.
  13811. */
  13812. setComponent( index, component, value ) {
  13813. if ( this.normalized ) value = normalize( value, this.array );
  13814. this.array[ index * this.itemSize + component ] = value;
  13815. return this;
  13816. }
  13817. /**
  13818. * Returns the x component of the vector at the given index.
  13819. *
  13820. * @param {number} index - The index into the buffer attribute.
  13821. * @return {number} The x component.
  13822. */
  13823. getX( index ) {
  13824. let x = this.array[ index * this.itemSize ];
  13825. if ( this.normalized ) x = denormalize( x, this.array );
  13826. return x;
  13827. }
  13828. /**
  13829. * Sets the x component of the vector at the given index.
  13830. *
  13831. * @param {number} index - The index into the buffer attribute.
  13832. * @param {number} x - The value to set.
  13833. * @return {BufferAttribute} A reference to this instance.
  13834. */
  13835. setX( index, x ) {
  13836. if ( this.normalized ) x = normalize( x, this.array );
  13837. this.array[ index * this.itemSize ] = x;
  13838. return this;
  13839. }
  13840. /**
  13841. * Returns the y component of the vector at the given index.
  13842. *
  13843. * @param {number} index - The index into the buffer attribute.
  13844. * @return {number} The y component.
  13845. */
  13846. getY( index ) {
  13847. let y = this.array[ index * this.itemSize + 1 ];
  13848. if ( this.normalized ) y = denormalize( y, this.array );
  13849. return y;
  13850. }
  13851. /**
  13852. * Sets the y component of the vector at the given index.
  13853. *
  13854. * @param {number} index - The index into the buffer attribute.
  13855. * @param {number} y - The value to set.
  13856. * @return {BufferAttribute} A reference to this instance.
  13857. */
  13858. setY( index, y ) {
  13859. if ( this.normalized ) y = normalize( y, this.array );
  13860. this.array[ index * this.itemSize + 1 ] = y;
  13861. return this;
  13862. }
  13863. /**
  13864. * Returns the z component of the vector at the given index.
  13865. *
  13866. * @param {number} index - The index into the buffer attribute.
  13867. * @return {number} The z component.
  13868. */
  13869. getZ( index ) {
  13870. let z = this.array[ index * this.itemSize + 2 ];
  13871. if ( this.normalized ) z = denormalize( z, this.array );
  13872. return z;
  13873. }
  13874. /**
  13875. * Sets the z component of the vector at the given index.
  13876. *
  13877. * @param {number} index - The index into the buffer attribute.
  13878. * @param {number} z - The value to set.
  13879. * @return {BufferAttribute} A reference to this instance.
  13880. */
  13881. setZ( index, z ) {
  13882. if ( this.normalized ) z = normalize( z, this.array );
  13883. this.array[ index * this.itemSize + 2 ] = z;
  13884. return this;
  13885. }
  13886. /**
  13887. * Returns the w component of the vector at the given index.
  13888. *
  13889. * @param {number} index - The index into the buffer attribute.
  13890. * @return {number} The w component.
  13891. */
  13892. getW( index ) {
  13893. let w = this.array[ index * this.itemSize + 3 ];
  13894. if ( this.normalized ) w = denormalize( w, this.array );
  13895. return w;
  13896. }
  13897. /**
  13898. * Sets the w component of the vector at the given index.
  13899. *
  13900. * @param {number} index - The index into the buffer attribute.
  13901. * @param {number} w - The value to set.
  13902. * @return {BufferAttribute} A reference to this instance.
  13903. */
  13904. setW( index, w ) {
  13905. if ( this.normalized ) w = normalize( w, this.array );
  13906. this.array[ index * this.itemSize + 3 ] = w;
  13907. return this;
  13908. }
  13909. /**
  13910. * Sets the x and y component of the vector at the given index.
  13911. *
  13912. * @param {number} index - The index into the buffer attribute.
  13913. * @param {number} x - The value for the x component to set.
  13914. * @param {number} y - The value for the y component to set.
  13915. * @return {BufferAttribute} A reference to this instance.
  13916. */
  13917. setXY( index, x, y ) {
  13918. index *= this.itemSize;
  13919. if ( this.normalized ) {
  13920. x = normalize( x, this.array );
  13921. y = normalize( y, this.array );
  13922. }
  13923. this.array[ index + 0 ] = x;
  13924. this.array[ index + 1 ] = y;
  13925. return this;
  13926. }
  13927. /**
  13928. * Sets the x, y and z component of the vector at the given index.
  13929. *
  13930. * @param {number} index - The index into the buffer attribute.
  13931. * @param {number} x - The value for the x component to set.
  13932. * @param {number} y - The value for the y component to set.
  13933. * @param {number} z - The value for the z component to set.
  13934. * @return {BufferAttribute} A reference to this instance.
  13935. */
  13936. setXYZ( index, x, y, z ) {
  13937. index *= this.itemSize;
  13938. if ( this.normalized ) {
  13939. x = normalize( x, this.array );
  13940. y = normalize( y, this.array );
  13941. z = normalize( z, this.array );
  13942. }
  13943. this.array[ index + 0 ] = x;
  13944. this.array[ index + 1 ] = y;
  13945. this.array[ index + 2 ] = z;
  13946. return this;
  13947. }
  13948. /**
  13949. * Sets the x, y, z and w component of the vector at the given index.
  13950. *
  13951. * @param {number} index - The index into the buffer attribute.
  13952. * @param {number} x - The value for the x component to set.
  13953. * @param {number} y - The value for the y component to set.
  13954. * @param {number} z - The value for the z component to set.
  13955. * @param {number} w - The value for the w component to set.
  13956. * @return {BufferAttribute} A reference to this instance.
  13957. */
  13958. setXYZW( index, x, y, z, w ) {
  13959. index *= this.itemSize;
  13960. if ( this.normalized ) {
  13961. x = normalize( x, this.array );
  13962. y = normalize( y, this.array );
  13963. z = normalize( z, this.array );
  13964. w = normalize( w, this.array );
  13965. }
  13966. this.array[ index + 0 ] = x;
  13967. this.array[ index + 1 ] = y;
  13968. this.array[ index + 2 ] = z;
  13969. this.array[ index + 3 ] = w;
  13970. return this;
  13971. }
  13972. /**
  13973. * Sets the given callback function that is executed after the Renderer has transferred
  13974. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13975. * the upload when attribute data are not needed anymore on the CPU side.
  13976. *
  13977. * @param {Function} callback - The `onUpload()` callback.
  13978. * @return {BufferAttribute} A reference to this instance.
  13979. */
  13980. onUpload( callback ) {
  13981. this.onUploadCallback = callback;
  13982. return this;
  13983. }
  13984. /**
  13985. * Returns a new buffer attribute with copied values from this instance.
  13986. *
  13987. * @return {BufferAttribute} A clone of this instance.
  13988. */
  13989. clone() {
  13990. return new this.constructor( this.array, this.itemSize ).copy( this );
  13991. }
  13992. /**
  13993. * Serializes the buffer attribute into JSON.
  13994. *
  13995. * @return {Object} A JSON object representing the serialized buffer attribute.
  13996. */
  13997. toJSON() {
  13998. const data = {
  13999. itemSize: this.itemSize,
  14000. type: this.array.constructor.name,
  14001. array: Array.from( this.array ),
  14002. normalized: this.normalized
  14003. };
  14004. if ( this.name !== '' ) data.name = this.name;
  14005. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  14006. return data;
  14007. }
  14008. }
  14009. /**
  14010. * Convenient class that can be used when creating a `Int8` buffer attribute with
  14011. * a plain `Array` instance.
  14012. *
  14013. * @augments BufferAttribute
  14014. */
  14015. class Int8BufferAttribute extends BufferAttribute {
  14016. /**
  14017. * Constructs a new buffer attribute.
  14018. *
  14019. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  14020. * @param {number} itemSize - The item size.
  14021. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14022. */
  14023. constructor( array, itemSize, normalized ) {
  14024. super( new Int8Array( array ), itemSize, normalized );
  14025. }
  14026. }
  14027. /**
  14028. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  14029. * a plain `Array` instance.
  14030. *
  14031. * @augments BufferAttribute
  14032. */
  14033. class Uint8BufferAttribute extends BufferAttribute {
  14034. /**
  14035. * Constructs a new buffer attribute.
  14036. *
  14037. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  14038. * @param {number} itemSize - The item size.
  14039. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14040. */
  14041. constructor( array, itemSize, normalized ) {
  14042. super( new Uint8Array( array ), itemSize, normalized );
  14043. }
  14044. }
  14045. /**
  14046. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  14047. * a plain `Array` instance.
  14048. *
  14049. * @augments BufferAttribute
  14050. */
  14051. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14052. /**
  14053. * Constructs a new buffer attribute.
  14054. *
  14055. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14056. * @param {number} itemSize - The item size.
  14057. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14058. */
  14059. constructor( array, itemSize, normalized ) {
  14060. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14061. }
  14062. }
  14063. /**
  14064. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14065. * a plain `Array` instance.
  14066. *
  14067. * @augments BufferAttribute
  14068. */
  14069. class Int16BufferAttribute extends BufferAttribute {
  14070. /**
  14071. * Constructs a new buffer attribute.
  14072. *
  14073. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14074. * @param {number} itemSize - The item size.
  14075. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14076. */
  14077. constructor( array, itemSize, normalized ) {
  14078. super( new Int16Array( array ), itemSize, normalized );
  14079. }
  14080. }
  14081. /**
  14082. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14083. * a plain `Array` instance.
  14084. *
  14085. * @augments BufferAttribute
  14086. */
  14087. class Uint16BufferAttribute extends BufferAttribute {
  14088. /**
  14089. * Constructs a new buffer attribute.
  14090. *
  14091. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14092. * @param {number} itemSize - The item size.
  14093. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14094. */
  14095. constructor( array, itemSize, normalized ) {
  14096. super( new Uint16Array( array ), itemSize, normalized );
  14097. }
  14098. }
  14099. /**
  14100. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14101. * a plain `Array` instance.
  14102. *
  14103. * @augments BufferAttribute
  14104. */
  14105. class Int32BufferAttribute extends BufferAttribute {
  14106. /**
  14107. * Constructs a new buffer attribute.
  14108. *
  14109. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14110. * @param {number} itemSize - The item size.
  14111. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14112. */
  14113. constructor( array, itemSize, normalized ) {
  14114. super( new Int32Array( array ), itemSize, normalized );
  14115. }
  14116. }
  14117. /**
  14118. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14119. * a plain `Array` instance.
  14120. *
  14121. * @augments BufferAttribute
  14122. */
  14123. class Uint32BufferAttribute extends BufferAttribute {
  14124. /**
  14125. * Constructs a new buffer attribute.
  14126. *
  14127. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14128. * @param {number} itemSize - The item size.
  14129. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14130. */
  14131. constructor( array, itemSize, normalized ) {
  14132. super( new Uint32Array( array ), itemSize, normalized );
  14133. }
  14134. }
  14135. /**
  14136. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14137. * a plain `Array` instance.
  14138. *
  14139. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14140. * browser support is still problematic.
  14141. *
  14142. * @augments BufferAttribute
  14143. */
  14144. class Float16BufferAttribute extends BufferAttribute {
  14145. /**
  14146. * Constructs a new buffer attribute.
  14147. *
  14148. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14149. * @param {number} itemSize - The item size.
  14150. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14151. */
  14152. constructor( array, itemSize, normalized ) {
  14153. super( new Uint16Array( array ), itemSize, normalized );
  14154. this.isFloat16BufferAttribute = true;
  14155. }
  14156. getX( index ) {
  14157. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14158. if ( this.normalized ) x = denormalize( x, this.array );
  14159. return x;
  14160. }
  14161. setX( index, x ) {
  14162. if ( this.normalized ) x = normalize( x, this.array );
  14163. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14164. return this;
  14165. }
  14166. getY( index ) {
  14167. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14168. if ( this.normalized ) y = denormalize( y, this.array );
  14169. return y;
  14170. }
  14171. setY( index, y ) {
  14172. if ( this.normalized ) y = normalize( y, this.array );
  14173. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14174. return this;
  14175. }
  14176. getZ( index ) {
  14177. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14178. if ( this.normalized ) z = denormalize( z, this.array );
  14179. return z;
  14180. }
  14181. setZ( index, z ) {
  14182. if ( this.normalized ) z = normalize( z, this.array );
  14183. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14184. return this;
  14185. }
  14186. getW( index ) {
  14187. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14188. if ( this.normalized ) w = denormalize( w, this.array );
  14189. return w;
  14190. }
  14191. setW( index, w ) {
  14192. if ( this.normalized ) w = normalize( w, this.array );
  14193. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14194. return this;
  14195. }
  14196. setXY( index, x, y ) {
  14197. index *= this.itemSize;
  14198. if ( this.normalized ) {
  14199. x = normalize( x, this.array );
  14200. y = normalize( y, this.array );
  14201. }
  14202. this.array[ index + 0 ] = toHalfFloat( x );
  14203. this.array[ index + 1 ] = toHalfFloat( y );
  14204. return this;
  14205. }
  14206. setXYZ( index, x, y, z ) {
  14207. index *= this.itemSize;
  14208. if ( this.normalized ) {
  14209. x = normalize( x, this.array );
  14210. y = normalize( y, this.array );
  14211. z = normalize( z, this.array );
  14212. }
  14213. this.array[ index + 0 ] = toHalfFloat( x );
  14214. this.array[ index + 1 ] = toHalfFloat( y );
  14215. this.array[ index + 2 ] = toHalfFloat( z );
  14216. return this;
  14217. }
  14218. setXYZW( index, x, y, z, w ) {
  14219. index *= this.itemSize;
  14220. if ( this.normalized ) {
  14221. x = normalize( x, this.array );
  14222. y = normalize( y, this.array );
  14223. z = normalize( z, this.array );
  14224. w = normalize( w, this.array );
  14225. }
  14226. this.array[ index + 0 ] = toHalfFloat( x );
  14227. this.array[ index + 1 ] = toHalfFloat( y );
  14228. this.array[ index + 2 ] = toHalfFloat( z );
  14229. this.array[ index + 3 ] = toHalfFloat( w );
  14230. return this;
  14231. }
  14232. }
  14233. /**
  14234. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14235. * a plain `Array` instance.
  14236. *
  14237. * @augments BufferAttribute
  14238. */
  14239. class Float32BufferAttribute extends BufferAttribute {
  14240. /**
  14241. * Constructs a new buffer attribute.
  14242. *
  14243. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14244. * @param {number} itemSize - The item size.
  14245. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14246. */
  14247. constructor( array, itemSize, normalized ) {
  14248. super( new Float32Array( array ), itemSize, normalized );
  14249. }
  14250. }
  14251. let _id$2 = 0;
  14252. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14253. const _obj = /*@__PURE__*/ new Object3D();
  14254. const _offset = /*@__PURE__*/ new Vector3();
  14255. const _box$2 = /*@__PURE__*/ new Box3();
  14256. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14257. const _vector$8 = /*@__PURE__*/ new Vector3();
  14258. /**
  14259. * A representation of mesh, line, or point geometry. Includes vertex
  14260. * positions, face indices, normals, colors, UVs, and custom attributes
  14261. * within buffers, reducing the cost of passing all this data to the GPU.
  14262. *
  14263. * ```js
  14264. * const geometry = new THREE.BufferGeometry();
  14265. * // create a simple square shape. We duplicate the top left and bottom right
  14266. * // vertices because each vertex needs to appear once per triangle.
  14267. * const vertices = new Float32Array( [
  14268. * -1.0, -1.0, 1.0, // v0
  14269. * 1.0, -1.0, 1.0, // v1
  14270. * 1.0, 1.0, 1.0, // v2
  14271. *
  14272. * 1.0, 1.0, 1.0, // v3
  14273. * -1.0, 1.0, 1.0, // v4
  14274. * -1.0, -1.0, 1.0 // v5
  14275. * ] );
  14276. * // itemSize = 3 because there are 3 values (components) per vertex
  14277. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14278. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14279. * const mesh = new THREE.Mesh( geometry, material );
  14280. * ```
  14281. *
  14282. * @augments EventDispatcher
  14283. */
  14284. class BufferGeometry extends EventDispatcher {
  14285. /**
  14286. * Constructs a new geometry.
  14287. */
  14288. constructor() {
  14289. super();
  14290. /**
  14291. * This flag can be used for type testing.
  14292. *
  14293. * @type {boolean}
  14294. * @readonly
  14295. * @default true
  14296. */
  14297. this.isBufferGeometry = true;
  14298. /**
  14299. * The ID of the geometry.
  14300. *
  14301. * @name BufferGeometry#id
  14302. * @type {number}
  14303. * @readonly
  14304. */
  14305. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14306. /**
  14307. * The UUID of the geometry.
  14308. *
  14309. * @type {string}
  14310. * @readonly
  14311. */
  14312. this.uuid = generateUUID();
  14313. /**
  14314. * The name of the geometry.
  14315. *
  14316. * @type {string}
  14317. */
  14318. this.name = '';
  14319. this.type = 'BufferGeometry';
  14320. /**
  14321. * Allows for vertices to be re-used across multiple triangles; this is
  14322. * called using "indexed triangles". Each triangle is associated with the
  14323. * indices of three vertices. This attribute therefore stores the index of
  14324. * each vertex for each triangular face. If this attribute is not set, the
  14325. * renderer assumes that each three contiguous positions represent a single triangle.
  14326. *
  14327. * @type {?BufferAttribute}
  14328. * @default null
  14329. */
  14330. this.index = null;
  14331. /**
  14332. * A (storage) buffer attribute which was generated with a compute shader and
  14333. * now defines indirect draw calls.
  14334. *
  14335. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14336. *
  14337. * @type {?BufferAttribute}
  14338. * @default null
  14339. */
  14340. this.indirect = null;
  14341. /**
  14342. * 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.
  14343. *
  14344. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14345. *
  14346. * @type {number|Array<number>}
  14347. * @default 0
  14348. */
  14349. this.indirectOffset = 0;
  14350. /**
  14351. * This dictionary has as id the name of the attribute to be set and as value
  14352. * the buffer attribute to set it to. Rather than accessing this property directly,
  14353. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14354. *
  14355. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14356. */
  14357. this.attributes = {};
  14358. /**
  14359. * This dictionary holds the morph targets of the geometry.
  14360. *
  14361. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14362. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14363. *
  14364. * @type {Object}
  14365. */
  14366. this.morphAttributes = {};
  14367. /**
  14368. * Used to control the morph target behavior; when set to `true`, the morph
  14369. * target data is treated as relative offsets, rather than as absolute
  14370. * positions/normals.
  14371. *
  14372. * @type {boolean}
  14373. * @default false
  14374. */
  14375. this.morphTargetsRelative = false;
  14376. /**
  14377. * Split the geometry into groups, each of which will be rendered in a
  14378. * separate draw call. This allows an array of materials to be used with the geometry.
  14379. *
  14380. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14381. *
  14382. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14383. * indices, and must not leave vertices or indices unused.
  14384. *
  14385. * @type {Array<Object>}
  14386. */
  14387. this.groups = [];
  14388. /**
  14389. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14390. *
  14391. * @type {?Box3}
  14392. * @default null
  14393. */
  14394. this.boundingBox = null;
  14395. /**
  14396. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14397. *
  14398. * @type {?Sphere}
  14399. * @default null
  14400. */
  14401. this.boundingSphere = null;
  14402. /**
  14403. * Determines the part of the geometry to render. This should not be set directly,
  14404. * instead use `setDrawRange()`.
  14405. *
  14406. * @type {{start:number,count:number}}
  14407. */
  14408. this.drawRange = { start: 0, count: Infinity };
  14409. /**
  14410. * An object that can be used to store custom data about the geometry.
  14411. * It should not hold references to functions as these will not be cloned.
  14412. *
  14413. * @type {Object}
  14414. */
  14415. this.userData = {};
  14416. }
  14417. /**
  14418. * Returns the index of this geometry.
  14419. *
  14420. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14421. */
  14422. getIndex() {
  14423. return this.index;
  14424. }
  14425. /**
  14426. * Sets the given index to this geometry.
  14427. *
  14428. * @param {Array<number>|BufferAttribute} index - The index to set.
  14429. * @return {BufferGeometry} A reference to this instance.
  14430. */
  14431. setIndex( index ) {
  14432. if ( Array.isArray( index ) ) {
  14433. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14434. } else {
  14435. this.index = index;
  14436. }
  14437. return this;
  14438. }
  14439. /**
  14440. * Sets the given indirect attribute to this geometry.
  14441. *
  14442. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14443. * @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.
  14444. * @return {BufferGeometry} A reference to this instance.
  14445. */
  14446. setIndirect( indirect, indirectOffset = 0 ) {
  14447. this.indirect = indirect;
  14448. this.indirectOffset = indirectOffset;
  14449. return this;
  14450. }
  14451. /**
  14452. * Returns the indirect attribute of this geometry.
  14453. *
  14454. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14455. */
  14456. getIndirect() {
  14457. return this.indirect;
  14458. }
  14459. /**
  14460. * Returns the buffer attribute for the given name.
  14461. *
  14462. * @param {string} name - The attribute name.
  14463. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14464. * Returns `undefined` if not attribute has been found.
  14465. */
  14466. getAttribute( name ) {
  14467. return this.attributes[ name ];
  14468. }
  14469. /**
  14470. * Sets the given attribute for the given name.
  14471. *
  14472. * @param {string} name - The attribute name.
  14473. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14474. * @return {BufferGeometry} A reference to this instance.
  14475. */
  14476. setAttribute( name, attribute ) {
  14477. this.attributes[ name ] = attribute;
  14478. return this;
  14479. }
  14480. /**
  14481. * Deletes the attribute for the given name.
  14482. *
  14483. * @param {string} name - The attribute name to delete.
  14484. * @return {BufferGeometry} A reference to this instance.
  14485. */
  14486. deleteAttribute( name ) {
  14487. delete this.attributes[ name ];
  14488. return this;
  14489. }
  14490. /**
  14491. * Returns `true` if this geometry has an attribute for the given name.
  14492. *
  14493. * @param {string} name - The attribute name.
  14494. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14495. */
  14496. hasAttribute( name ) {
  14497. return this.attributes[ name ] !== undefined;
  14498. }
  14499. /**
  14500. * Adds a group to this geometry.
  14501. *
  14502. * @param {number} start - The first element in this draw call. That is the first
  14503. * vertex for non-indexed geometry, otherwise the first triangle index.
  14504. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14505. * @param {number} [materialIndex=0] - The material array index to use.
  14506. */
  14507. addGroup( start, count, materialIndex = 0 ) {
  14508. this.groups.push( {
  14509. start: start,
  14510. count: count,
  14511. materialIndex: materialIndex
  14512. } );
  14513. }
  14514. /**
  14515. * Clears all groups.
  14516. */
  14517. clearGroups() {
  14518. this.groups = [];
  14519. }
  14520. /**
  14521. * Sets the draw range for this geometry.
  14522. *
  14523. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14524. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14525. * For indexed BufferGeometry, `count` is the number of indices to render.
  14526. */
  14527. setDrawRange( start, count ) {
  14528. this.drawRange.start = start;
  14529. this.drawRange.count = count;
  14530. }
  14531. /**
  14532. * Applies the given 4x4 transformation matrix to the geometry.
  14533. *
  14534. * @param {Matrix4} matrix - The matrix to apply.
  14535. * @return {BufferGeometry} A reference to this instance.
  14536. */
  14537. applyMatrix4( matrix ) {
  14538. const position = this.attributes.position;
  14539. if ( position !== undefined ) {
  14540. position.applyMatrix4( matrix );
  14541. position.needsUpdate = true;
  14542. }
  14543. const normal = this.attributes.normal;
  14544. if ( normal !== undefined ) {
  14545. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14546. normal.applyNormalMatrix( normalMatrix );
  14547. normal.needsUpdate = true;
  14548. }
  14549. const tangent = this.attributes.tangent;
  14550. if ( tangent !== undefined ) {
  14551. tangent.transformDirection( matrix );
  14552. tangent.needsUpdate = true;
  14553. }
  14554. if ( this.boundingBox !== null ) {
  14555. this.computeBoundingBox();
  14556. }
  14557. if ( this.boundingSphere !== null ) {
  14558. this.computeBoundingSphere();
  14559. }
  14560. return this;
  14561. }
  14562. /**
  14563. * Applies the rotation represented by the Quaternion to the geometry.
  14564. *
  14565. * @param {Quaternion} q - The Quaternion to apply.
  14566. * @return {BufferGeometry} A reference to this instance.
  14567. */
  14568. applyQuaternion( q ) {
  14569. _m1$2.makeRotationFromQuaternion( q );
  14570. this.applyMatrix4( _m1$2 );
  14571. return this;
  14572. }
  14573. /**
  14574. * Rotates the geometry about the X axis. This is typically done as a one time
  14575. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14576. * real-time mesh rotation.
  14577. *
  14578. * @param {number} angle - The angle in radians.
  14579. * @return {BufferGeometry} A reference to this instance.
  14580. */
  14581. rotateX( angle ) {
  14582. // rotate geometry around world x-axis
  14583. _m1$2.makeRotationX( angle );
  14584. this.applyMatrix4( _m1$2 );
  14585. return this;
  14586. }
  14587. /**
  14588. * Rotates the geometry about the Y axis. This is typically done as a one time
  14589. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14590. * real-time mesh rotation.
  14591. *
  14592. * @param {number} angle - The angle in radians.
  14593. * @return {BufferGeometry} A reference to this instance.
  14594. */
  14595. rotateY( angle ) {
  14596. // rotate geometry around world y-axis
  14597. _m1$2.makeRotationY( angle );
  14598. this.applyMatrix4( _m1$2 );
  14599. return this;
  14600. }
  14601. /**
  14602. * Rotates the geometry about the Z axis. This is typically done as a one time
  14603. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14604. * real-time mesh rotation.
  14605. *
  14606. * @param {number} angle - The angle in radians.
  14607. * @return {BufferGeometry} A reference to this instance.
  14608. */
  14609. rotateZ( angle ) {
  14610. // rotate geometry around world z-axis
  14611. _m1$2.makeRotationZ( angle );
  14612. this.applyMatrix4( _m1$2 );
  14613. return this;
  14614. }
  14615. /**
  14616. * Translates the geometry. This is typically done as a one time
  14617. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14618. * real-time mesh rotation.
  14619. *
  14620. * @param {number} x - The x offset.
  14621. * @param {number} y - The y offset.
  14622. * @param {number} z - The z offset.
  14623. * @return {BufferGeometry} A reference to this instance.
  14624. */
  14625. translate( x, y, z ) {
  14626. // translate geometry
  14627. _m1$2.makeTranslation( x, y, z );
  14628. this.applyMatrix4( _m1$2 );
  14629. return this;
  14630. }
  14631. /**
  14632. * Scales the geometry. This is typically done as a one time
  14633. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14634. * real-time mesh rotation.
  14635. *
  14636. * @param {number} x - The x scale.
  14637. * @param {number} y - The y scale.
  14638. * @param {number} z - The z scale.
  14639. * @return {BufferGeometry} A reference to this instance.
  14640. */
  14641. scale( x, y, z ) {
  14642. // scale geometry
  14643. _m1$2.makeScale( x, y, z );
  14644. this.applyMatrix4( _m1$2 );
  14645. return this;
  14646. }
  14647. /**
  14648. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14649. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14650. * real-time mesh rotation.
  14651. *
  14652. * @param {Vector3} vector - The target point.
  14653. * @return {BufferGeometry} A reference to this instance.
  14654. */
  14655. lookAt( vector ) {
  14656. _obj.lookAt( vector );
  14657. _obj.updateMatrix();
  14658. this.applyMatrix4( _obj.matrix );
  14659. return this;
  14660. }
  14661. /**
  14662. * Center the geometry based on its bounding box.
  14663. *
  14664. * @return {BufferGeometry} A reference to this instance.
  14665. */
  14666. center() {
  14667. this.computeBoundingBox();
  14668. this.boundingBox.getCenter( _offset ).negate();
  14669. this.translate( _offset.x, _offset.y, _offset.z );
  14670. return this;
  14671. }
  14672. /**
  14673. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14674. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14675. * set to `0`.
  14676. *
  14677. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14678. * data from the array. The length of the array must match the vertex count.
  14679. *
  14680. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14681. * @return {BufferGeometry} A reference to this instance.
  14682. */
  14683. setFromPoints( points ) {
  14684. const positionAttribute = this.getAttribute( 'position' );
  14685. if ( positionAttribute === undefined ) {
  14686. const position = [];
  14687. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14688. const point = points[ i ];
  14689. position.push( point.x, point.y, point.z || 0 );
  14690. }
  14691. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14692. } else {
  14693. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14694. for ( let i = 0; i < l; i ++ ) {
  14695. const point = points[ i ];
  14696. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14697. }
  14698. if ( points.length > positionAttribute.count ) {
  14699. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14700. }
  14701. positionAttribute.needsUpdate = true;
  14702. }
  14703. return this;
  14704. }
  14705. /**
  14706. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14707. * The bounding box is not computed by the engine; it must be computed by your app.
  14708. * You may need to recompute the bounding box if the geometry vertices are modified.
  14709. */
  14710. computeBoundingBox() {
  14711. if ( this.boundingBox === null ) {
  14712. this.boundingBox = new Box3();
  14713. }
  14714. const position = this.attributes.position;
  14715. const morphAttributesPosition = this.morphAttributes.position;
  14716. if ( position && position.isGLBufferAttribute ) {
  14717. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14718. this.boundingBox.set(
  14719. new Vector3( - Infinity, - Infinity, - Infinity ),
  14720. new Vector3( + Infinity, + Infinity, + Infinity )
  14721. );
  14722. return;
  14723. }
  14724. if ( position !== undefined ) {
  14725. this.boundingBox.setFromBufferAttribute( position );
  14726. // process morph attributes if present
  14727. if ( morphAttributesPosition ) {
  14728. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14729. const morphAttribute = morphAttributesPosition[ i ];
  14730. _box$2.setFromBufferAttribute( morphAttribute );
  14731. if ( this.morphTargetsRelative ) {
  14732. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14733. this.boundingBox.expandByPoint( _vector$8 );
  14734. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14735. this.boundingBox.expandByPoint( _vector$8 );
  14736. } else {
  14737. this.boundingBox.expandByPoint( _box$2.min );
  14738. this.boundingBox.expandByPoint( _box$2.max );
  14739. }
  14740. }
  14741. }
  14742. } else {
  14743. this.boundingBox.makeEmpty();
  14744. }
  14745. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14746. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14747. }
  14748. }
  14749. /**
  14750. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14751. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14752. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14753. */
  14754. computeBoundingSphere() {
  14755. if ( this.boundingSphere === null ) {
  14756. this.boundingSphere = new Sphere();
  14757. }
  14758. const position = this.attributes.position;
  14759. const morphAttributesPosition = this.morphAttributes.position;
  14760. if ( position && position.isGLBufferAttribute ) {
  14761. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14762. this.boundingSphere.set( new Vector3(), Infinity );
  14763. return;
  14764. }
  14765. if ( position ) {
  14766. // first, find the center of the bounding sphere
  14767. const center = this.boundingSphere.center;
  14768. _box$2.setFromBufferAttribute( position );
  14769. // process morph attributes if present
  14770. if ( morphAttributesPosition ) {
  14771. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14772. const morphAttribute = morphAttributesPosition[ i ];
  14773. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14774. if ( this.morphTargetsRelative ) {
  14775. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14776. _box$2.expandByPoint( _vector$8 );
  14777. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14778. _box$2.expandByPoint( _vector$8 );
  14779. } else {
  14780. _box$2.expandByPoint( _boxMorphTargets.min );
  14781. _box$2.expandByPoint( _boxMorphTargets.max );
  14782. }
  14783. }
  14784. }
  14785. _box$2.getCenter( center );
  14786. // second, try to find a boundingSphere with a radius smaller than the
  14787. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14788. let maxRadiusSq = 0;
  14789. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14790. _vector$8.fromBufferAttribute( position, i );
  14791. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14792. }
  14793. // process morph attributes if present
  14794. if ( morphAttributesPosition ) {
  14795. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14796. const morphAttribute = morphAttributesPosition[ i ];
  14797. const morphTargetsRelative = this.morphTargetsRelative;
  14798. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14799. _vector$8.fromBufferAttribute( morphAttribute, j );
  14800. if ( morphTargetsRelative ) {
  14801. _offset.fromBufferAttribute( position, j );
  14802. _vector$8.add( _offset );
  14803. }
  14804. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14805. }
  14806. }
  14807. }
  14808. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14809. if ( isNaN( this.boundingSphere.radius ) ) {
  14810. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14811. }
  14812. }
  14813. }
  14814. /**
  14815. * Calculates and adds a tangent attribute to this geometry.
  14816. *
  14817. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14818. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14819. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14820. */
  14821. computeTangents() {
  14822. const index = this.index;
  14823. const attributes = this.attributes;
  14824. // based on http://www.terathon.com/code/tangent.html
  14825. // (per vertex tangents)
  14826. if ( index === null ||
  14827. attributes.position === undefined ||
  14828. attributes.normal === undefined ||
  14829. attributes.uv === undefined ) {
  14830. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14831. return;
  14832. }
  14833. const positionAttribute = attributes.position;
  14834. const normalAttribute = attributes.normal;
  14835. const uvAttribute = attributes.uv;
  14836. if ( this.hasAttribute( 'tangent' ) === false ) {
  14837. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14838. }
  14839. const tangentAttribute = this.getAttribute( 'tangent' );
  14840. const tan1 = [], tan2 = [];
  14841. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14842. tan1[ i ] = new Vector3();
  14843. tan2[ i ] = new Vector3();
  14844. }
  14845. const vA = new Vector3(),
  14846. vB = new Vector3(),
  14847. vC = new Vector3(),
  14848. uvA = new Vector2(),
  14849. uvB = new Vector2(),
  14850. uvC = new Vector2(),
  14851. sdir = new Vector3(),
  14852. tdir = new Vector3();
  14853. function handleTriangle( a, b, c ) {
  14854. vA.fromBufferAttribute( positionAttribute, a );
  14855. vB.fromBufferAttribute( positionAttribute, b );
  14856. vC.fromBufferAttribute( positionAttribute, c );
  14857. uvA.fromBufferAttribute( uvAttribute, a );
  14858. uvB.fromBufferAttribute( uvAttribute, b );
  14859. uvC.fromBufferAttribute( uvAttribute, c );
  14860. vB.sub( vA );
  14861. vC.sub( vA );
  14862. uvB.sub( uvA );
  14863. uvC.sub( uvA );
  14864. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14865. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14866. if ( ! isFinite( r ) ) return;
  14867. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14868. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14869. tan1[ a ].add( sdir );
  14870. tan1[ b ].add( sdir );
  14871. tan1[ c ].add( sdir );
  14872. tan2[ a ].add( tdir );
  14873. tan2[ b ].add( tdir );
  14874. tan2[ c ].add( tdir );
  14875. }
  14876. let groups = this.groups;
  14877. if ( groups.length === 0 ) {
  14878. groups = [ {
  14879. start: 0,
  14880. count: index.count
  14881. } ];
  14882. }
  14883. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14884. const group = groups[ i ];
  14885. const start = group.start;
  14886. const count = group.count;
  14887. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14888. handleTriangle(
  14889. index.getX( j + 0 ),
  14890. index.getX( j + 1 ),
  14891. index.getX( j + 2 )
  14892. );
  14893. }
  14894. }
  14895. const tmp = new Vector3(), tmp2 = new Vector3();
  14896. const n = new Vector3(), n2 = new Vector3();
  14897. function handleVertex( v ) {
  14898. n.fromBufferAttribute( normalAttribute, v );
  14899. n2.copy( n );
  14900. const t = tan1[ v ];
  14901. // Gram-Schmidt orthogonalize
  14902. tmp.copy( t );
  14903. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14904. // Calculate handedness
  14905. tmp2.crossVectors( n2, t );
  14906. const test = tmp2.dot( tan2[ v ] );
  14907. const w = ( test < 0.0 ) ? -1 : 1.0;
  14908. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14909. }
  14910. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14911. const group = groups[ i ];
  14912. const start = group.start;
  14913. const count = group.count;
  14914. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14915. handleVertex( index.getX( j + 0 ) );
  14916. handleVertex( index.getX( j + 1 ) );
  14917. handleVertex( index.getX( j + 2 ) );
  14918. }
  14919. }
  14920. }
  14921. /**
  14922. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14923. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14924. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14925. * to be the same as the face normal.
  14926. */
  14927. computeVertexNormals() {
  14928. const index = this.index;
  14929. const positionAttribute = this.getAttribute( 'position' );
  14930. if ( positionAttribute !== undefined ) {
  14931. let normalAttribute = this.getAttribute( 'normal' );
  14932. if ( normalAttribute === undefined ) {
  14933. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14934. this.setAttribute( 'normal', normalAttribute );
  14935. } else {
  14936. // reset existing normals to zero
  14937. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14938. normalAttribute.setXYZ( i, 0, 0, 0 );
  14939. }
  14940. }
  14941. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14942. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14943. const cb = new Vector3(), ab = new Vector3();
  14944. // indexed elements
  14945. if ( index ) {
  14946. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14947. const vA = index.getX( i + 0 );
  14948. const vB = index.getX( i + 1 );
  14949. const vC = index.getX( i + 2 );
  14950. pA.fromBufferAttribute( positionAttribute, vA );
  14951. pB.fromBufferAttribute( positionAttribute, vB );
  14952. pC.fromBufferAttribute( positionAttribute, vC );
  14953. cb.subVectors( pC, pB );
  14954. ab.subVectors( pA, pB );
  14955. cb.cross( ab );
  14956. nA.fromBufferAttribute( normalAttribute, vA );
  14957. nB.fromBufferAttribute( normalAttribute, vB );
  14958. nC.fromBufferAttribute( normalAttribute, vC );
  14959. nA.add( cb );
  14960. nB.add( cb );
  14961. nC.add( cb );
  14962. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14963. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14964. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14965. }
  14966. } else {
  14967. // non-indexed elements (unconnected triangle soup)
  14968. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14969. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14970. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14971. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14972. cb.subVectors( pC, pB );
  14973. ab.subVectors( pA, pB );
  14974. cb.cross( ab );
  14975. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14976. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14977. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14978. }
  14979. }
  14980. this.normalizeNormals();
  14981. normalAttribute.needsUpdate = true;
  14982. }
  14983. }
  14984. /**
  14985. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14986. * correct lighting on the geometry surfaces.
  14987. */
  14988. normalizeNormals() {
  14989. const normals = this.attributes.normal;
  14990. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14991. _vector$8.fromBufferAttribute( normals, i );
  14992. _vector$8.normalize();
  14993. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14994. }
  14995. }
  14996. /**
  14997. * Return a new non-index version of this indexed geometry. If the geometry
  14998. * is already non-indexed, the method is a NOOP.
  14999. *
  15000. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  15001. */
  15002. toNonIndexed() {
  15003. function convertBufferAttribute( attribute, indices ) {
  15004. const array = attribute.array;
  15005. const itemSize = attribute.itemSize;
  15006. const normalized = attribute.normalized;
  15007. const array2 = new array.constructor( indices.length * itemSize );
  15008. let index = 0, index2 = 0;
  15009. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  15010. if ( attribute.isInterleavedBufferAttribute ) {
  15011. index = indices[ i ] * attribute.data.stride + attribute.offset;
  15012. } else {
  15013. index = indices[ i ] * itemSize;
  15014. }
  15015. for ( let j = 0; j < itemSize; j ++ ) {
  15016. array2[ index2 ++ ] = array[ index ++ ];
  15017. }
  15018. }
  15019. return new BufferAttribute( array2, itemSize, normalized );
  15020. }
  15021. //
  15022. if ( this.index === null ) {
  15023. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  15024. return this;
  15025. }
  15026. const geometry2 = new BufferGeometry();
  15027. const indices = this.index.array;
  15028. const attributes = this.attributes;
  15029. // attributes
  15030. for ( const name in attributes ) {
  15031. const attribute = attributes[ name ];
  15032. const newAttribute = convertBufferAttribute( attribute, indices );
  15033. geometry2.setAttribute( name, newAttribute );
  15034. }
  15035. // morph attributes
  15036. const morphAttributes = this.morphAttributes;
  15037. for ( const name in morphAttributes ) {
  15038. const morphArray = [];
  15039. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15040. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  15041. const attribute = morphAttribute[ i ];
  15042. const newAttribute = convertBufferAttribute( attribute, indices );
  15043. morphArray.push( newAttribute );
  15044. }
  15045. geometry2.morphAttributes[ name ] = morphArray;
  15046. }
  15047. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  15048. // groups
  15049. const groups = this.groups;
  15050. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15051. const group = groups[ i ];
  15052. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15053. }
  15054. return geometry2;
  15055. }
  15056. /**
  15057. * Serializes the geometry into JSON.
  15058. *
  15059. * @return {Object} A JSON object representing the serialized geometry.
  15060. */
  15061. toJSON() {
  15062. const data = {
  15063. metadata: {
  15064. version: 4.7,
  15065. type: 'BufferGeometry',
  15066. generator: 'BufferGeometry.toJSON'
  15067. }
  15068. };
  15069. // standard BufferGeometry serialization
  15070. data.uuid = this.uuid;
  15071. data.type = this.type;
  15072. if ( this.name !== '' ) data.name = this.name;
  15073. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15074. if ( this.parameters !== undefined ) {
  15075. const parameters = this.parameters;
  15076. for ( const key in parameters ) {
  15077. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15078. }
  15079. return data;
  15080. }
  15081. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15082. data.data = { attributes: {} };
  15083. const index = this.index;
  15084. if ( index !== null ) {
  15085. data.data.index = {
  15086. type: index.array.constructor.name,
  15087. array: Array.prototype.slice.call( index.array )
  15088. };
  15089. }
  15090. const attributes = this.attributes;
  15091. for ( const key in attributes ) {
  15092. const attribute = attributes[ key ];
  15093. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15094. }
  15095. const morphAttributes = {};
  15096. let hasMorphAttributes = false;
  15097. for ( const key in this.morphAttributes ) {
  15098. const attributeArray = this.morphAttributes[ key ];
  15099. const array = [];
  15100. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15101. const attribute = attributeArray[ i ];
  15102. array.push( attribute.toJSON( data.data ) );
  15103. }
  15104. if ( array.length > 0 ) {
  15105. morphAttributes[ key ] = array;
  15106. hasMorphAttributes = true;
  15107. }
  15108. }
  15109. if ( hasMorphAttributes ) {
  15110. data.data.morphAttributes = morphAttributes;
  15111. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15112. }
  15113. const groups = this.groups;
  15114. if ( groups.length > 0 ) {
  15115. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15116. }
  15117. const boundingSphere = this.boundingSphere;
  15118. if ( boundingSphere !== null ) {
  15119. data.data.boundingSphere = boundingSphere.toJSON();
  15120. }
  15121. return data;
  15122. }
  15123. /**
  15124. * Returns a new geometry with copied values from this instance.
  15125. *
  15126. * @return {BufferGeometry} A clone of this instance.
  15127. */
  15128. clone() {
  15129. return new this.constructor().copy( this );
  15130. }
  15131. /**
  15132. * Copies the values of the given geometry to this instance.
  15133. *
  15134. * @param {BufferGeometry} source - The geometry to copy.
  15135. * @return {BufferGeometry} A reference to this instance.
  15136. */
  15137. copy( source ) {
  15138. // reset
  15139. this.index = null;
  15140. this.attributes = {};
  15141. this.morphAttributes = {};
  15142. this.groups = [];
  15143. this.boundingBox = null;
  15144. this.boundingSphere = null;
  15145. // used for storing cloned, shared data
  15146. const data = {};
  15147. // name
  15148. this.name = source.name;
  15149. // index
  15150. const index = source.index;
  15151. if ( index !== null ) {
  15152. this.setIndex( index.clone() );
  15153. }
  15154. // attributes
  15155. const attributes = source.attributes;
  15156. for ( const name in attributes ) {
  15157. const attribute = attributes[ name ];
  15158. this.setAttribute( name, attribute.clone( data ) );
  15159. }
  15160. // morph attributes
  15161. const morphAttributes = source.morphAttributes;
  15162. for ( const name in morphAttributes ) {
  15163. const array = [];
  15164. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15165. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15166. array.push( morphAttribute[ i ].clone( data ) );
  15167. }
  15168. this.morphAttributes[ name ] = array;
  15169. }
  15170. this.morphTargetsRelative = source.morphTargetsRelative;
  15171. // groups
  15172. const groups = source.groups;
  15173. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15174. const group = groups[ i ];
  15175. this.addGroup( group.start, group.count, group.materialIndex );
  15176. }
  15177. // bounding box
  15178. const boundingBox = source.boundingBox;
  15179. if ( boundingBox !== null ) {
  15180. this.boundingBox = boundingBox.clone();
  15181. }
  15182. // bounding sphere
  15183. const boundingSphere = source.boundingSphere;
  15184. if ( boundingSphere !== null ) {
  15185. this.boundingSphere = boundingSphere.clone();
  15186. }
  15187. // draw range
  15188. this.drawRange.start = source.drawRange.start;
  15189. this.drawRange.count = source.drawRange.count;
  15190. // user data
  15191. this.userData = source.userData;
  15192. return this;
  15193. }
  15194. /**
  15195. * Frees the GPU-related resources allocated by this instance. Call this
  15196. * method whenever this instance is no longer used in your app.
  15197. *
  15198. * @fires BufferGeometry#dispose
  15199. */
  15200. dispose() {
  15201. this.dispatchEvent( { type: 'dispose' } );
  15202. }
  15203. }
  15204. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15205. const _ray$3 = /*@__PURE__*/ new Ray();
  15206. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15207. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15208. const _vA$1 = /*@__PURE__*/ new Vector3();
  15209. const _vB$1 = /*@__PURE__*/ new Vector3();
  15210. const _vC$1 = /*@__PURE__*/ new Vector3();
  15211. const _tempA = /*@__PURE__*/ new Vector3();
  15212. const _morphA = /*@__PURE__*/ new Vector3();
  15213. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15214. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15215. /**
  15216. * Class representing triangular polygon mesh based objects.
  15217. *
  15218. * ```js
  15219. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15220. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15221. * const mesh = new THREE.Mesh( geometry, material );
  15222. * scene.add( mesh );
  15223. * ```
  15224. *
  15225. * @augments Object3D
  15226. */
  15227. class Mesh extends Object3D {
  15228. /**
  15229. * Constructs a new mesh.
  15230. *
  15231. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15232. * @param {Material|Array<Material>} [material] - The mesh material.
  15233. */
  15234. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15235. super();
  15236. /**
  15237. * This flag can be used for type testing.
  15238. *
  15239. * @type {boolean}
  15240. * @readonly
  15241. * @default true
  15242. */
  15243. this.isMesh = true;
  15244. this.type = 'Mesh';
  15245. /**
  15246. * The mesh geometry.
  15247. *
  15248. * @type {BufferGeometry}
  15249. */
  15250. this.geometry = geometry;
  15251. /**
  15252. * The mesh material.
  15253. *
  15254. * @type {Material|Array<Material>}
  15255. * @default MeshBasicMaterial
  15256. */
  15257. this.material = material;
  15258. /**
  15259. * A dictionary representing the morph targets in the geometry. The key is the
  15260. * morph targets name, the value its attribute index. This member is `undefined`
  15261. * by default and only set when morph targets are detected in the geometry.
  15262. *
  15263. * @type {Object<string,number>|undefined}
  15264. * @default undefined
  15265. */
  15266. this.morphTargetDictionary = undefined;
  15267. /**
  15268. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15269. * is applied. This member is `undefined` by default and only set when morph targets are
  15270. * detected in the geometry.
  15271. *
  15272. * @type {Array<number>|undefined}
  15273. * @default undefined
  15274. */
  15275. this.morphTargetInfluences = undefined;
  15276. /**
  15277. * The number of instances of this mesh.
  15278. * Can only be used with {@link WebGPURenderer}.
  15279. *
  15280. * @type {number}
  15281. * @default 1
  15282. */
  15283. this.count = 1;
  15284. this.updateMorphTargets();
  15285. }
  15286. copy( source, recursive ) {
  15287. super.copy( source, recursive );
  15288. if ( source.morphTargetInfluences !== undefined ) {
  15289. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15290. }
  15291. if ( source.morphTargetDictionary !== undefined ) {
  15292. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15293. }
  15294. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15295. this.geometry = source.geometry;
  15296. return this;
  15297. }
  15298. /**
  15299. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15300. * to make sure existing morph targets can influence this 3D object.
  15301. */
  15302. updateMorphTargets() {
  15303. const geometry = this.geometry;
  15304. const morphAttributes = geometry.morphAttributes;
  15305. const keys = Object.keys( morphAttributes );
  15306. if ( keys.length > 0 ) {
  15307. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15308. if ( morphAttribute !== undefined ) {
  15309. this.morphTargetInfluences = [];
  15310. this.morphTargetDictionary = {};
  15311. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15312. const name = morphAttribute[ m ].name || String( m );
  15313. this.morphTargetInfluences.push( 0 );
  15314. this.morphTargetDictionary[ name ] = m;
  15315. }
  15316. }
  15317. }
  15318. }
  15319. /**
  15320. * Returns the local-space position of the vertex at the given index, taking into
  15321. * account the current animation state of both morph targets and skinning.
  15322. *
  15323. * @param {number} index - The vertex index.
  15324. * @param {Vector3} target - The target object that is used to store the method's result.
  15325. * @return {Vector3} The vertex position in local space.
  15326. */
  15327. getVertexPosition( index, target ) {
  15328. const geometry = this.geometry;
  15329. const position = geometry.attributes.position;
  15330. const morphPosition = geometry.morphAttributes.position;
  15331. const morphTargetsRelative = geometry.morphTargetsRelative;
  15332. target.fromBufferAttribute( position, index );
  15333. const morphInfluences = this.morphTargetInfluences;
  15334. if ( morphPosition && morphInfluences ) {
  15335. _morphA.set( 0, 0, 0 );
  15336. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15337. const influence = morphInfluences[ i ];
  15338. const morphAttribute = morphPosition[ i ];
  15339. if ( influence === 0 ) continue;
  15340. _tempA.fromBufferAttribute( morphAttribute, index );
  15341. if ( morphTargetsRelative ) {
  15342. _morphA.addScaledVector( _tempA, influence );
  15343. } else {
  15344. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15345. }
  15346. }
  15347. target.add( _morphA );
  15348. }
  15349. return target;
  15350. }
  15351. /**
  15352. * Computes intersection points between a casted ray and this line.
  15353. *
  15354. * @param {Raycaster} raycaster - The raycaster.
  15355. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15356. */
  15357. raycast( raycaster, intersects ) {
  15358. const geometry = this.geometry;
  15359. const material = this.material;
  15360. const matrixWorld = this.matrixWorld;
  15361. if ( material === undefined ) return;
  15362. // test with bounding sphere in world space
  15363. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15364. _sphere$6.copy( geometry.boundingSphere );
  15365. _sphere$6.applyMatrix4( matrixWorld );
  15366. // check distance from ray origin to bounding sphere
  15367. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15368. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15369. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15370. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15371. }
  15372. // convert ray to local space of mesh
  15373. _inverseMatrix$3.copy( matrixWorld ).invert();
  15374. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15375. // test with bounding box in local space
  15376. if ( geometry.boundingBox !== null ) {
  15377. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15378. }
  15379. // test for intersections with geometry
  15380. this._computeIntersections( raycaster, intersects, _ray$3 );
  15381. }
  15382. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15383. let intersection;
  15384. const geometry = this.geometry;
  15385. const material = this.material;
  15386. const index = geometry.index;
  15387. const position = geometry.attributes.position;
  15388. const uv = geometry.attributes.uv;
  15389. const uv1 = geometry.attributes.uv1;
  15390. const normal = geometry.attributes.normal;
  15391. const groups = geometry.groups;
  15392. const drawRange = geometry.drawRange;
  15393. if ( index !== null ) {
  15394. // indexed buffer geometry
  15395. if ( Array.isArray( material ) ) {
  15396. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15397. const group = groups[ i ];
  15398. const groupMaterial = material[ group.materialIndex ];
  15399. const start = Math.max( group.start, drawRange.start );
  15400. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15401. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15402. const a = index.getX( j );
  15403. const b = index.getX( j + 1 );
  15404. const c = index.getX( j + 2 );
  15405. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15406. if ( intersection ) {
  15407. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15408. intersection.face.materialIndex = group.materialIndex;
  15409. intersects.push( intersection );
  15410. }
  15411. }
  15412. }
  15413. } else {
  15414. const start = Math.max( 0, drawRange.start );
  15415. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15416. for ( let i = start, il = end; i < il; i += 3 ) {
  15417. const a = index.getX( i );
  15418. const b = index.getX( i + 1 );
  15419. const c = index.getX( i + 2 );
  15420. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15421. if ( intersection ) {
  15422. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15423. intersects.push( intersection );
  15424. }
  15425. }
  15426. }
  15427. } else if ( position !== undefined ) {
  15428. // non-indexed buffer geometry
  15429. if ( Array.isArray( material ) ) {
  15430. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15431. const group = groups[ i ];
  15432. const groupMaterial = material[ group.materialIndex ];
  15433. const start = Math.max( group.start, drawRange.start );
  15434. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15435. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15436. const a = j;
  15437. const b = j + 1;
  15438. const c = j + 2;
  15439. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15440. if ( intersection ) {
  15441. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15442. intersection.face.materialIndex = group.materialIndex;
  15443. intersects.push( intersection );
  15444. }
  15445. }
  15446. }
  15447. } else {
  15448. const start = Math.max( 0, drawRange.start );
  15449. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15450. for ( let i = start, il = end; i < il; i += 3 ) {
  15451. const a = i;
  15452. const b = i + 1;
  15453. const c = i + 2;
  15454. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15455. if ( intersection ) {
  15456. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15457. intersects.push( intersection );
  15458. }
  15459. }
  15460. }
  15461. }
  15462. }
  15463. }
  15464. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15465. let intersect;
  15466. if ( material.side === BackSide ) {
  15467. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15468. } else {
  15469. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15470. }
  15471. if ( intersect === null ) return null;
  15472. _intersectionPointWorld.copy( point );
  15473. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15474. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15475. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15476. return {
  15477. distance: distance,
  15478. point: _intersectionPointWorld.clone(),
  15479. object: object
  15480. };
  15481. }
  15482. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15483. object.getVertexPosition( a, _vA$1 );
  15484. object.getVertexPosition( b, _vB$1 );
  15485. object.getVertexPosition( c, _vC$1 );
  15486. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15487. if ( intersection ) {
  15488. const barycoord = new Vector3();
  15489. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15490. if ( uv ) {
  15491. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15492. }
  15493. if ( uv1 ) {
  15494. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15495. }
  15496. if ( normal ) {
  15497. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15498. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15499. intersection.normal.multiplyScalar( -1 );
  15500. }
  15501. }
  15502. const face = {
  15503. a: a,
  15504. b: b,
  15505. c: c,
  15506. normal: new Vector3(),
  15507. materialIndex: 0
  15508. };
  15509. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15510. intersection.face = face;
  15511. intersection.barycoord = barycoord;
  15512. }
  15513. return intersection;
  15514. }
  15515. /**
  15516. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15517. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15518. * of the axes.
  15519. *
  15520. * ```js
  15521. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15522. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15523. * const cube = new THREE.Mesh( geometry, material );
  15524. * scene.add( cube );
  15525. * ```
  15526. *
  15527. * @augments BufferGeometry
  15528. * @demo scenes/geometry-browser.html#BoxGeometry
  15529. */
  15530. class BoxGeometry extends BufferGeometry {
  15531. /**
  15532. * Constructs a new box geometry.
  15533. *
  15534. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15535. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15536. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15537. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15538. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15539. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15540. */
  15541. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15542. super();
  15543. this.type = 'BoxGeometry';
  15544. /**
  15545. * Holds the constructor parameters that have been
  15546. * used to generate the geometry. Any modification
  15547. * after instantiation does not change the geometry.
  15548. *
  15549. * @type {Object}
  15550. */
  15551. this.parameters = {
  15552. width: width,
  15553. height: height,
  15554. depth: depth,
  15555. widthSegments: widthSegments,
  15556. heightSegments: heightSegments,
  15557. depthSegments: depthSegments
  15558. };
  15559. const scope = this;
  15560. // segments
  15561. widthSegments = Math.floor( widthSegments );
  15562. heightSegments = Math.floor( heightSegments );
  15563. depthSegments = Math.floor( depthSegments );
  15564. // buffers
  15565. const indices = [];
  15566. const vertices = [];
  15567. const normals = [];
  15568. const uvs = [];
  15569. // helper variables
  15570. let numberOfVertices = 0;
  15571. let groupStart = 0;
  15572. // build each side of the box geometry
  15573. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15574. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15575. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15576. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15577. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15578. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15579. // build geometry
  15580. this.setIndex( indices );
  15581. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15582. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15583. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15584. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15585. const segmentWidth = width / gridX;
  15586. const segmentHeight = height / gridY;
  15587. const widthHalf = width / 2;
  15588. const heightHalf = height / 2;
  15589. const depthHalf = depth / 2;
  15590. const gridX1 = gridX + 1;
  15591. const gridY1 = gridY + 1;
  15592. let vertexCounter = 0;
  15593. let groupCount = 0;
  15594. const vector = new Vector3();
  15595. // generate vertices, normals and uvs
  15596. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15597. const y = iy * segmentHeight - heightHalf;
  15598. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15599. const x = ix * segmentWidth - widthHalf;
  15600. // set values to correct vector component
  15601. vector[ u ] = x * udir;
  15602. vector[ v ] = y * vdir;
  15603. vector[ w ] = depthHalf;
  15604. // now apply vector to vertex buffer
  15605. vertices.push( vector.x, vector.y, vector.z );
  15606. // set values to correct vector component
  15607. vector[ u ] = 0;
  15608. vector[ v ] = 0;
  15609. vector[ w ] = depth > 0 ? 1 : -1;
  15610. // now apply vector to normal buffer
  15611. normals.push( vector.x, vector.y, vector.z );
  15612. // uvs
  15613. uvs.push( ix / gridX );
  15614. uvs.push( 1 - ( iy / gridY ) );
  15615. // counters
  15616. vertexCounter += 1;
  15617. }
  15618. }
  15619. // indices
  15620. // 1. you need three indices to draw a single face
  15621. // 2. a single segment consists of two faces
  15622. // 3. so we need to generate six (2*3) indices per segment
  15623. for ( let iy = 0; iy < gridY; iy ++ ) {
  15624. for ( let ix = 0; ix < gridX; ix ++ ) {
  15625. const a = numberOfVertices + ix + gridX1 * iy;
  15626. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15627. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15628. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15629. // faces
  15630. indices.push( a, b, d );
  15631. indices.push( b, c, d );
  15632. // increase counter
  15633. groupCount += 6;
  15634. }
  15635. }
  15636. // add a group to the geometry. this will ensure multi material support
  15637. scope.addGroup( groupStart, groupCount, materialIndex );
  15638. // calculate new start value for groups
  15639. groupStart += groupCount;
  15640. // update total number of vertices
  15641. numberOfVertices += vertexCounter;
  15642. }
  15643. }
  15644. copy( source ) {
  15645. super.copy( source );
  15646. this.parameters = Object.assign( {}, source.parameters );
  15647. return this;
  15648. }
  15649. /**
  15650. * Factory method for creating an instance of this class from the given
  15651. * JSON object.
  15652. *
  15653. * @param {Object} data - A JSON object representing the serialized geometry.
  15654. * @return {BoxGeometry} A new instance.
  15655. */
  15656. static fromJSON( data ) {
  15657. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15658. }
  15659. }
  15660. /**
  15661. * Provides utility functions for managing uniforms.
  15662. *
  15663. * @module UniformsUtils
  15664. */
  15665. /**
  15666. * Clones the given uniform definitions by performing a deep-copy. That means
  15667. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15668. * the cloned uniform will refer to a new object reference.
  15669. *
  15670. * @param {Object} src - An object representing uniform definitions.
  15671. * @return {Object} The cloned uniforms.
  15672. */
  15673. function cloneUniforms( src ) {
  15674. const dst = {};
  15675. for ( const u in src ) {
  15676. dst[ u ] = {};
  15677. for ( const p in src[ u ] ) {
  15678. const property = src[ u ][ p ];
  15679. if ( property && ( property.isColor ||
  15680. property.isMatrix3 || property.isMatrix4 ||
  15681. property.isVector2 || property.isVector3 || property.isVector4 ||
  15682. property.isTexture || property.isQuaternion ) ) {
  15683. if ( property.isRenderTargetTexture ) {
  15684. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15685. dst[ u ][ p ] = null;
  15686. } else {
  15687. dst[ u ][ p ] = property.clone();
  15688. }
  15689. } else if ( Array.isArray( property ) ) {
  15690. dst[ u ][ p ] = property.slice();
  15691. } else {
  15692. dst[ u ][ p ] = property;
  15693. }
  15694. }
  15695. }
  15696. return dst;
  15697. }
  15698. /**
  15699. * Merges the given uniform definitions into a single object. Since the
  15700. * method internally uses cloneUniforms(), it performs a deep-copy when
  15701. * producing the merged uniform definitions.
  15702. *
  15703. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15704. * @return {Object} The merged uniforms.
  15705. */
  15706. function mergeUniforms( uniforms ) {
  15707. const merged = {};
  15708. for ( let u = 0; u < uniforms.length; u ++ ) {
  15709. const tmp = cloneUniforms( uniforms[ u ] );
  15710. for ( const p in tmp ) {
  15711. merged[ p ] = tmp[ p ];
  15712. }
  15713. }
  15714. return merged;
  15715. }
  15716. function cloneUniformsGroups( src ) {
  15717. const dst = [];
  15718. for ( let u = 0; u < src.length; u ++ ) {
  15719. dst.push( src[ u ].clone() );
  15720. }
  15721. return dst;
  15722. }
  15723. function getUnlitUniformColorSpace( renderer ) {
  15724. const currentRenderTarget = renderer.getRenderTarget();
  15725. if ( currentRenderTarget === null ) {
  15726. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15727. return renderer.outputColorSpace;
  15728. }
  15729. // https://github.com/mrdoob/three.js/issues/27868
  15730. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15731. return currentRenderTarget.texture.colorSpace;
  15732. }
  15733. return ColorManagement.workingColorSpace;
  15734. }
  15735. // Legacy
  15736. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15737. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15738. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15739. /**
  15740. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15741. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15742. * effect not included with any of the built-in materials.
  15743. *
  15744. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15745. *
  15746. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15747. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15748. * you don't want that, use {@link RawShaderMaterial} instead.
  15749. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15750. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15751. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15752. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15753. * - The loop variable has to be *i*.
  15754. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15755. * value of *i* for the given iteration and can be used in preprocessor
  15756. * statements.
  15757. *
  15758. * ```js
  15759. * const material = new THREE.ShaderMaterial( {
  15760. * uniforms: {
  15761. * time: { value: 1.0 },
  15762. * resolution: { value: new THREE.Vector2() }
  15763. * },
  15764. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15765. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15766. * } );
  15767. * ```
  15768. *
  15769. * @augments Material
  15770. */
  15771. class ShaderMaterial extends Material {
  15772. /**
  15773. * Constructs a new shader material.
  15774. *
  15775. * @param {Object} [parameters] - An object with one or more properties
  15776. * defining the material's appearance. Any property of the material
  15777. * (including any property from inherited materials) can be passed
  15778. * in here. Color values can be passed any type of value accepted
  15779. * by {@link Color#set}.
  15780. */
  15781. constructor( parameters ) {
  15782. super();
  15783. /**
  15784. * This flag can be used for type testing.
  15785. *
  15786. * @type {boolean}
  15787. * @readonly
  15788. * @default true
  15789. */
  15790. this.isShaderMaterial = true;
  15791. this.type = 'ShaderMaterial';
  15792. /**
  15793. * Defines custom constants using `#define` directives within the GLSL code
  15794. * for both the vertex shader and the fragment shader; each key/value pair
  15795. * yields another directive.
  15796. * ```js
  15797. * defines: {
  15798. * FOO: 15,
  15799. * BAR: true
  15800. * }
  15801. * ```
  15802. * Yields the lines:
  15803. * ```
  15804. * #define FOO 15
  15805. * #define BAR true
  15806. * ```
  15807. *
  15808. * @type {Object}
  15809. */
  15810. this.defines = {};
  15811. /**
  15812. * An object of the form:
  15813. * ```js
  15814. * {
  15815. * "uniform1": { value: 1.0 },
  15816. * "uniform2": { value: 2 }
  15817. * }
  15818. * ```
  15819. * specifying the uniforms to be passed to the shader code; keys are uniform
  15820. * names, values are definitions of the form
  15821. * ```
  15822. * {
  15823. * value: 1.0
  15824. * }
  15825. * ```
  15826. * where `value` is the value of the uniform. Names must match the name of
  15827. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15828. * on every frame, so updating the value of the uniform will immediately
  15829. * update the value available to the GLSL code.
  15830. *
  15831. * @type {Object}
  15832. */
  15833. this.uniforms = {};
  15834. /**
  15835. * An array holding uniforms groups for configuring UBOs.
  15836. *
  15837. * @type {Array<UniformsGroup>}
  15838. */
  15839. this.uniformsGroups = [];
  15840. /**
  15841. * Vertex shader GLSL code. This is the actual code for the shader.
  15842. *
  15843. * @type {string}
  15844. */
  15845. this.vertexShader = default_vertex;
  15846. /**
  15847. * Fragment shader GLSL code. This is the actual code for the shader.
  15848. *
  15849. * @type {string}
  15850. */
  15851. this.fragmentShader = default_fragment;
  15852. /**
  15853. * Controls line thickness or lines.
  15854. *
  15855. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15856. * width of one pixel.
  15857. *
  15858. * @type {number}
  15859. * @default 1
  15860. */
  15861. this.linewidth = 1;
  15862. /**
  15863. * Renders the geometry as a wireframe.
  15864. *
  15865. * @type {boolean}
  15866. * @default false
  15867. */
  15868. this.wireframe = false;
  15869. /**
  15870. * Controls the thickness of the wireframe.
  15871. *
  15872. * WebGL and WebGPU ignore this property and always render
  15873. * 1 pixel wide lines.
  15874. *
  15875. * @type {number}
  15876. * @default 1
  15877. */
  15878. this.wireframeLinewidth = 1;
  15879. /**
  15880. * Defines whether the material color is affected by global fog settings; `true`
  15881. * to pass fog uniforms to the shader.
  15882. *
  15883. * Setting this property to `true` requires the definition of fog uniforms. It is
  15884. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  15885. * with predefined fog uniforms.
  15886. *
  15887. * ```js
  15888. * const material = new ShaderMaterial( {
  15889. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  15890. * vertexShader: vertexShader,
  15891. * fragmentShader: fragmentShader,
  15892. * fog: true
  15893. * } );
  15894. * ```
  15895. *
  15896. * @type {boolean}
  15897. * @default false
  15898. */
  15899. this.fog = false;
  15900. /**
  15901. * Defines whether this material uses lighting; `true` to pass uniform data
  15902. * related to lighting to this shader.
  15903. *
  15904. * @type {boolean}
  15905. * @default false
  15906. */
  15907. this.lights = false;
  15908. /**
  15909. * Defines whether this material supports clipping; `true` to let the renderer
  15910. * pass the clippingPlanes uniform.
  15911. *
  15912. * @type {boolean}
  15913. * @default false
  15914. */
  15915. this.clipping = false;
  15916. /**
  15917. * Overwritten and set to `true` by default.
  15918. *
  15919. * @type {boolean}
  15920. * @default true
  15921. */
  15922. this.forceSinglePass = true;
  15923. /**
  15924. * This object allows to enable certain WebGL 2 extensions.
  15925. *
  15926. * - clipCullDistance: set to `true` to use vertex shader clipping
  15927. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15928. *
  15929. * @type {{clipCullDistance:false,multiDraw:false}}
  15930. */
  15931. this.extensions = {
  15932. clipCullDistance: false, // set to use vertex shader clipping
  15933. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15934. };
  15935. /**
  15936. * When the rendered geometry doesn't include these attributes but the
  15937. * material does, these default values will be passed to the shaders. This
  15938. * avoids errors when buffer data is missing.
  15939. *
  15940. * - color: [ 1, 1, 1 ]
  15941. * - uv: [ 0, 0 ]
  15942. * - uv1: [ 0, 0 ]
  15943. *
  15944. * @type {Object}
  15945. */
  15946. this.defaultAttributeValues = {
  15947. 'color': [ 1, 1, 1 ],
  15948. 'uv': [ 0, 0 ],
  15949. 'uv1': [ 0, 0 ]
  15950. };
  15951. /**
  15952. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  15953. * to bind a generic vertex index to an attribute variable.
  15954. *
  15955. * @type {string|undefined}
  15956. * @default undefined
  15957. */
  15958. this.index0AttributeName = undefined;
  15959. /**
  15960. * Can be used to force a uniform update while changing uniforms in
  15961. * {@link Object3D#onBeforeRender}.
  15962. *
  15963. * @type {boolean}
  15964. * @default false
  15965. */
  15966. this.uniformsNeedUpdate = false;
  15967. /**
  15968. * Defines the GLSL version of custom shader code.
  15969. *
  15970. * @type {?(GLSL1|GLSL3)}
  15971. * @default null
  15972. */
  15973. this.glslVersion = null;
  15974. if ( parameters !== undefined ) {
  15975. this.setValues( parameters );
  15976. }
  15977. }
  15978. copy( source ) {
  15979. super.copy( source );
  15980. this.fragmentShader = source.fragmentShader;
  15981. this.vertexShader = source.vertexShader;
  15982. this.uniforms = cloneUniforms( source.uniforms );
  15983. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15984. this.defines = Object.assign( {}, source.defines );
  15985. this.wireframe = source.wireframe;
  15986. this.wireframeLinewidth = source.wireframeLinewidth;
  15987. this.fog = source.fog;
  15988. this.lights = source.lights;
  15989. this.clipping = source.clipping;
  15990. this.extensions = Object.assign( {}, source.extensions );
  15991. this.glslVersion = source.glslVersion;
  15992. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  15993. this.index0AttributeName = source.index0AttributeName;
  15994. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  15995. return this;
  15996. }
  15997. toJSON( meta ) {
  15998. const data = super.toJSON( meta );
  15999. data.glslVersion = this.glslVersion;
  16000. data.uniforms = {};
  16001. for ( const name in this.uniforms ) {
  16002. const uniform = this.uniforms[ name ];
  16003. const value = uniform.value;
  16004. if ( value && value.isTexture ) {
  16005. data.uniforms[ name ] = {
  16006. type: 't',
  16007. value: value.toJSON( meta ).uuid
  16008. };
  16009. } else if ( value && value.isColor ) {
  16010. data.uniforms[ name ] = {
  16011. type: 'c',
  16012. value: value.getHex()
  16013. };
  16014. } else if ( value && value.isVector2 ) {
  16015. data.uniforms[ name ] = {
  16016. type: 'v2',
  16017. value: value.toArray()
  16018. };
  16019. } else if ( value && value.isVector3 ) {
  16020. data.uniforms[ name ] = {
  16021. type: 'v3',
  16022. value: value.toArray()
  16023. };
  16024. } else if ( value && value.isVector4 ) {
  16025. data.uniforms[ name ] = {
  16026. type: 'v4',
  16027. value: value.toArray()
  16028. };
  16029. } else if ( value && value.isMatrix3 ) {
  16030. data.uniforms[ name ] = {
  16031. type: 'm3',
  16032. value: value.toArray()
  16033. };
  16034. } else if ( value && value.isMatrix4 ) {
  16035. data.uniforms[ name ] = {
  16036. type: 'm4',
  16037. value: value.toArray()
  16038. };
  16039. } else {
  16040. data.uniforms[ name ] = {
  16041. value: value
  16042. };
  16043. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  16044. }
  16045. }
  16046. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  16047. data.vertexShader = this.vertexShader;
  16048. data.fragmentShader = this.fragmentShader;
  16049. data.lights = this.lights;
  16050. data.clipping = this.clipping;
  16051. const extensions = {};
  16052. for ( const key in this.extensions ) {
  16053. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16054. }
  16055. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16056. return data;
  16057. }
  16058. }
  16059. /**
  16060. * Abstract base class for cameras. This class should always be inherited
  16061. * when you build a new camera.
  16062. *
  16063. * @abstract
  16064. * @augments Object3D
  16065. */
  16066. class Camera extends Object3D {
  16067. /**
  16068. * Constructs a new camera.
  16069. */
  16070. constructor() {
  16071. super();
  16072. /**
  16073. * This flag can be used for type testing.
  16074. *
  16075. * @type {boolean}
  16076. * @readonly
  16077. * @default true
  16078. */
  16079. this.isCamera = true;
  16080. this.type = 'Camera';
  16081. /**
  16082. * The inverse of the camera's world matrix.
  16083. *
  16084. * @type {Matrix4}
  16085. */
  16086. this.matrixWorldInverse = new Matrix4();
  16087. /**
  16088. * The camera's projection matrix.
  16089. *
  16090. * @type {Matrix4}
  16091. */
  16092. this.projectionMatrix = new Matrix4();
  16093. /**
  16094. * The inverse of the camera's projection matrix.
  16095. *
  16096. * @type {Matrix4}
  16097. */
  16098. this.projectionMatrixInverse = new Matrix4();
  16099. /**
  16100. * The coordinate system in which the camera is used.
  16101. *
  16102. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16103. */
  16104. this.coordinateSystem = WebGLCoordinateSystem;
  16105. this._reversedDepth = false;
  16106. }
  16107. /**
  16108. * The flag that indicates whether the camera uses a reversed depth buffer.
  16109. *
  16110. * @type {boolean}
  16111. * @default false
  16112. */
  16113. get reversedDepth() {
  16114. return this._reversedDepth;
  16115. }
  16116. copy( source, recursive ) {
  16117. super.copy( source, recursive );
  16118. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16119. this.projectionMatrix.copy( source.projectionMatrix );
  16120. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16121. this.coordinateSystem = source.coordinateSystem;
  16122. return this;
  16123. }
  16124. /**
  16125. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16126. *
  16127. * This method is overwritten since cameras have a different forward vector compared to other
  16128. * 3D objects. A camera looks down its local, negative z-axis by default.
  16129. *
  16130. * @param {Vector3} target - The target vector the result is stored to.
  16131. * @return {Vector3} The 3D object's direction in world space.
  16132. */
  16133. getWorldDirection( target ) {
  16134. return super.getWorldDirection( target ).negate();
  16135. }
  16136. updateMatrixWorld( force ) {
  16137. super.updateMatrixWorld( force );
  16138. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16139. }
  16140. updateWorldMatrix( updateParents, updateChildren ) {
  16141. super.updateWorldMatrix( updateParents, updateChildren );
  16142. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16143. }
  16144. clone() {
  16145. return new this.constructor().copy( this );
  16146. }
  16147. }
  16148. const _v3$1 = /*@__PURE__*/ new Vector3();
  16149. const _minTarget = /*@__PURE__*/ new Vector2();
  16150. const _maxTarget = /*@__PURE__*/ new Vector2();
  16151. /**
  16152. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16153. *
  16154. * This projection mode is designed to mimic the way the human eye sees. It
  16155. * is the most common projection mode used for rendering a 3D scene.
  16156. *
  16157. * ```js
  16158. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16159. * scene.add( camera );
  16160. * ```
  16161. *
  16162. * @augments Camera
  16163. */
  16164. class PerspectiveCamera extends Camera {
  16165. /**
  16166. * Constructs a new perspective camera.
  16167. *
  16168. * @param {number} [fov=50] - The vertical field of view.
  16169. * @param {number} [aspect=1] - The aspect ratio.
  16170. * @param {number} [near=0.1] - The camera's near plane.
  16171. * @param {number} [far=2000] - The camera's far plane.
  16172. */
  16173. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16174. super();
  16175. /**
  16176. * This flag can be used for type testing.
  16177. *
  16178. * @type {boolean}
  16179. * @readonly
  16180. * @default true
  16181. */
  16182. this.isPerspectiveCamera = true;
  16183. this.type = 'PerspectiveCamera';
  16184. /**
  16185. * The vertical field of view, from bottom to top of view,
  16186. * in degrees.
  16187. *
  16188. * @type {number}
  16189. * @default 50
  16190. */
  16191. this.fov = fov;
  16192. /**
  16193. * The zoom factor of the camera.
  16194. *
  16195. * @type {number}
  16196. * @default 1
  16197. */
  16198. this.zoom = 1;
  16199. /**
  16200. * The camera's near plane. The valid range is greater than `0`
  16201. * and less than the current value of {@link PerspectiveCamera#far}.
  16202. *
  16203. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16204. * valid value for a perspective camera's near plane.
  16205. *
  16206. * @type {number}
  16207. * @default 0.1
  16208. */
  16209. this.near = near;
  16210. /**
  16211. * The camera's far plane. Must be greater than the
  16212. * current value of {@link PerspectiveCamera#near}.
  16213. *
  16214. * @type {number}
  16215. * @default 2000
  16216. */
  16217. this.far = far;
  16218. /**
  16219. * Object distance used for stereoscopy and depth-of-field effects. This
  16220. * parameter does not influence the projection matrix unless a
  16221. * {@link StereoCamera} is being used.
  16222. *
  16223. * @type {number}
  16224. * @default 10
  16225. */
  16226. this.focus = 10;
  16227. /**
  16228. * The aspect ratio, usually the canvas width / canvas height.
  16229. *
  16230. * @type {number}
  16231. * @default 1
  16232. */
  16233. this.aspect = aspect;
  16234. /**
  16235. * Represents the frustum window specification. This property should not be edited
  16236. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16237. *
  16238. * @type {?Object}
  16239. * @default null
  16240. */
  16241. this.view = null;
  16242. /**
  16243. * Film size used for the larger axis. Default is `35` (millimeters). This
  16244. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16245. * is set to a nonzero value.
  16246. *
  16247. * @type {number}
  16248. * @default 35
  16249. */
  16250. this.filmGauge = 35;
  16251. /**
  16252. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16253. *
  16254. * @type {number}
  16255. * @default 0
  16256. */
  16257. this.filmOffset = 0;
  16258. this.updateProjectionMatrix();
  16259. }
  16260. copy( source, recursive ) {
  16261. super.copy( source, recursive );
  16262. this.fov = source.fov;
  16263. this.zoom = source.zoom;
  16264. this.near = source.near;
  16265. this.far = source.far;
  16266. this.focus = source.focus;
  16267. this.aspect = source.aspect;
  16268. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16269. this.filmGauge = source.filmGauge;
  16270. this.filmOffset = source.filmOffset;
  16271. return this;
  16272. }
  16273. /**
  16274. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16275. *
  16276. * The default film gauge is 35, so that the focal length can be specified for
  16277. * a 35mm (full frame) camera.
  16278. *
  16279. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16280. */
  16281. setFocalLength( focalLength ) {
  16282. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16283. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16284. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16285. this.updateProjectionMatrix();
  16286. }
  16287. /**
  16288. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16289. * {@link PerspectiveCamera#filmGauge}.
  16290. *
  16291. * @return {number} The computed focal length.
  16292. */
  16293. getFocalLength() {
  16294. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16295. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16296. }
  16297. /**
  16298. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16299. *
  16300. * @return {number} The effective FOV.
  16301. */
  16302. getEffectiveFOV() {
  16303. return RAD2DEG * 2 * Math.atan(
  16304. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16305. }
  16306. /**
  16307. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16308. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16309. *
  16310. * @return {number} The film width.
  16311. */
  16312. getFilmWidth() {
  16313. // film not completely covered in portrait format (aspect < 1)
  16314. return this.filmGauge * Math.min( this.aspect, 1 );
  16315. }
  16316. /**
  16317. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16318. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16319. *
  16320. * @return {number} The film width.
  16321. */
  16322. getFilmHeight() {
  16323. // film not completely covered in landscape format (aspect > 1)
  16324. return this.filmGauge / Math.max( this.aspect, 1 );
  16325. }
  16326. /**
  16327. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16328. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16329. *
  16330. * @param {number} distance - The viewing distance.
  16331. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16332. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16333. */
  16334. getViewBounds( distance, minTarget, maxTarget ) {
  16335. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16336. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16337. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16338. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16339. }
  16340. /**
  16341. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16342. *
  16343. * @param {number} distance - The viewing distance.
  16344. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16345. * @returns {Vector2} The view size.
  16346. */
  16347. getViewSize( distance, target ) {
  16348. this.getViewBounds( distance, _minTarget, _maxTarget );
  16349. return target.subVectors( _maxTarget, _minTarget );
  16350. }
  16351. /**
  16352. * Sets an offset in a larger frustum. This is useful for multi-window or
  16353. * multi-monitor/multi-machine setups.
  16354. *
  16355. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16356. * the monitors are in grid like this
  16357. *```
  16358. * +---+---+---+
  16359. * | A | B | C |
  16360. * +---+---+---+
  16361. * | D | E | F |
  16362. * +---+---+---+
  16363. *```
  16364. * then for each monitor you would call it like this:
  16365. *```js
  16366. * const w = 1920;
  16367. * const h = 1080;
  16368. * const fullWidth = w * 3;
  16369. * const fullHeight = h * 2;
  16370. *
  16371. * // --A--
  16372. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16373. * // --B--
  16374. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16375. * // --C--
  16376. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16377. * // --D--
  16378. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16379. * // --E--
  16380. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16381. * // --F--
  16382. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16383. * ```
  16384. *
  16385. * Note there is no reason monitors have to be the same size or in a grid.
  16386. *
  16387. * @param {number} fullWidth - The full width of multiview setup.
  16388. * @param {number} fullHeight - The full height of multiview setup.
  16389. * @param {number} x - The horizontal offset of the subcamera.
  16390. * @param {number} y - The vertical offset of the subcamera.
  16391. * @param {number} width - The width of subcamera.
  16392. * @param {number} height - The height of subcamera.
  16393. */
  16394. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16395. this.aspect = fullWidth / fullHeight;
  16396. if ( this.view === null ) {
  16397. this.view = {
  16398. enabled: true,
  16399. fullWidth: 1,
  16400. fullHeight: 1,
  16401. offsetX: 0,
  16402. offsetY: 0,
  16403. width: 1,
  16404. height: 1
  16405. };
  16406. }
  16407. this.view.enabled = true;
  16408. this.view.fullWidth = fullWidth;
  16409. this.view.fullHeight = fullHeight;
  16410. this.view.offsetX = x;
  16411. this.view.offsetY = y;
  16412. this.view.width = width;
  16413. this.view.height = height;
  16414. this.updateProjectionMatrix();
  16415. }
  16416. /**
  16417. * Removes the view offset from the projection matrix.
  16418. */
  16419. clearViewOffset() {
  16420. if ( this.view !== null ) {
  16421. this.view.enabled = false;
  16422. }
  16423. this.updateProjectionMatrix();
  16424. }
  16425. /**
  16426. * Updates the camera's projection matrix. Must be called after any change of
  16427. * camera properties.
  16428. */
  16429. updateProjectionMatrix() {
  16430. const near = this.near;
  16431. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16432. let height = 2 * top;
  16433. let width = this.aspect * height;
  16434. let left = -0.5 * width;
  16435. const view = this.view;
  16436. if ( this.view !== null && this.view.enabled ) {
  16437. const fullWidth = view.fullWidth,
  16438. fullHeight = view.fullHeight;
  16439. left += view.offsetX * width / fullWidth;
  16440. top -= view.offsetY * height / fullHeight;
  16441. width *= view.width / fullWidth;
  16442. height *= view.height / fullHeight;
  16443. }
  16444. const skew = this.filmOffset;
  16445. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16446. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16447. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16448. }
  16449. toJSON( meta ) {
  16450. const data = super.toJSON( meta );
  16451. data.object.fov = this.fov;
  16452. data.object.zoom = this.zoom;
  16453. data.object.near = this.near;
  16454. data.object.far = this.far;
  16455. data.object.focus = this.focus;
  16456. data.object.aspect = this.aspect;
  16457. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16458. data.object.filmGauge = this.filmGauge;
  16459. data.object.filmOffset = this.filmOffset;
  16460. return data;
  16461. }
  16462. }
  16463. const fov = -90; // negative fov is not an error
  16464. const aspect = 1;
  16465. /**
  16466. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16467. * cube render target. The render target can then be used as an environment map for rendering
  16468. * realtime reflections in your scene.
  16469. *
  16470. * ```js
  16471. * // Create cube render target
  16472. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16473. *
  16474. * // Create cube camera
  16475. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16476. * scene.add( cubeCamera );
  16477. *
  16478. * // Create car
  16479. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16480. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16481. * scene.add( car );
  16482. *
  16483. * // Update the render target cube
  16484. * car.visible = false;
  16485. * cubeCamera.position.copy( car.position );
  16486. * cubeCamera.update( renderer, scene );
  16487. *
  16488. * // Render the scene
  16489. * car.visible = true;
  16490. * renderer.render( scene, camera );
  16491. * ```
  16492. *
  16493. * @augments Object3D
  16494. */
  16495. class CubeCamera extends Object3D {
  16496. /**
  16497. * Constructs a new cube camera.
  16498. *
  16499. * @param {number} near - The camera's near plane.
  16500. * @param {number} far - The camera's far plane.
  16501. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16502. */
  16503. constructor( near, far, renderTarget ) {
  16504. super();
  16505. this.type = 'CubeCamera';
  16506. /**
  16507. * A reference to the cube render target.
  16508. *
  16509. * @type {WebGLCubeRenderTarget}
  16510. */
  16511. this.renderTarget = renderTarget;
  16512. /**
  16513. * The current active coordinate system.
  16514. *
  16515. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16516. * @default null
  16517. */
  16518. this.coordinateSystem = null;
  16519. /**
  16520. * The current active mipmap level
  16521. *
  16522. * @type {number}
  16523. * @default 0
  16524. */
  16525. this.activeMipmapLevel = 0;
  16526. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16527. cameraPX.layers = this.layers;
  16528. this.add( cameraPX );
  16529. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16530. cameraNX.layers = this.layers;
  16531. this.add( cameraNX );
  16532. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16533. cameraPY.layers = this.layers;
  16534. this.add( cameraPY );
  16535. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16536. cameraNY.layers = this.layers;
  16537. this.add( cameraNY );
  16538. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16539. cameraPZ.layers = this.layers;
  16540. this.add( cameraPZ );
  16541. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16542. cameraNZ.layers = this.layers;
  16543. this.add( cameraNZ );
  16544. }
  16545. /**
  16546. * Must be called when the coordinate system of the cube camera is changed.
  16547. */
  16548. updateCoordinateSystem() {
  16549. const coordinateSystem = this.coordinateSystem;
  16550. const cameras = this.children.concat();
  16551. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16552. for ( const camera of cameras ) this.remove( camera );
  16553. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16554. cameraPX.up.set( 0, 1, 0 );
  16555. cameraPX.lookAt( 1, 0, 0 );
  16556. cameraNX.up.set( 0, 1, 0 );
  16557. cameraNX.lookAt( -1, 0, 0 );
  16558. cameraPY.up.set( 0, 0, -1 );
  16559. cameraPY.lookAt( 0, 1, 0 );
  16560. cameraNY.up.set( 0, 0, 1 );
  16561. cameraNY.lookAt( 0, -1, 0 );
  16562. cameraPZ.up.set( 0, 1, 0 );
  16563. cameraPZ.lookAt( 0, 0, 1 );
  16564. cameraNZ.up.set( 0, 1, 0 );
  16565. cameraNZ.lookAt( 0, 0, -1 );
  16566. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16567. cameraPX.up.set( 0, -1, 0 );
  16568. cameraPX.lookAt( -1, 0, 0 );
  16569. cameraNX.up.set( 0, -1, 0 );
  16570. cameraNX.lookAt( 1, 0, 0 );
  16571. cameraPY.up.set( 0, 0, 1 );
  16572. cameraPY.lookAt( 0, 1, 0 );
  16573. cameraNY.up.set( 0, 0, -1 );
  16574. cameraNY.lookAt( 0, -1, 0 );
  16575. cameraPZ.up.set( 0, -1, 0 );
  16576. cameraPZ.lookAt( 0, 0, 1 );
  16577. cameraNZ.up.set( 0, -1, 0 );
  16578. cameraNZ.lookAt( 0, 0, -1 );
  16579. } else {
  16580. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16581. }
  16582. for ( const camera of cameras ) {
  16583. this.add( camera );
  16584. camera.updateMatrixWorld();
  16585. }
  16586. }
  16587. /**
  16588. * Calling this method will render the given scene with the given renderer
  16589. * into the cube render target of the camera.
  16590. *
  16591. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16592. * @param {Scene} scene - The scene to render.
  16593. */
  16594. update( renderer, scene ) {
  16595. if ( this.parent === null ) this.updateMatrixWorld();
  16596. const { renderTarget, activeMipmapLevel } = this;
  16597. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16598. this.coordinateSystem = renderer.coordinateSystem;
  16599. this.updateCoordinateSystem();
  16600. }
  16601. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16602. const currentRenderTarget = renderer.getRenderTarget();
  16603. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16604. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16605. const currentXrEnabled = renderer.xr.enabled;
  16606. renderer.xr.enabled = false;
  16607. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16608. renderTarget.texture.generateMipmaps = false;
  16609. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16610. renderer.render( scene, cameraPX );
  16611. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16612. renderer.render( scene, cameraNX );
  16613. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16614. renderer.render( scene, cameraPY );
  16615. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16616. renderer.render( scene, cameraNY );
  16617. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16618. renderer.render( scene, cameraPZ );
  16619. // mipmaps are generated during the last call of render()
  16620. // at this point, all sides of the cube render target are defined
  16621. renderTarget.texture.generateMipmaps = generateMipmaps;
  16622. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16623. renderer.render( scene, cameraNZ );
  16624. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16625. renderer.xr.enabled = currentXrEnabled;
  16626. renderTarget.texture.needsPMREMUpdate = true;
  16627. }
  16628. }
  16629. /**
  16630. * Creates a cube texture made up of six images.
  16631. *
  16632. * ```js
  16633. * const loader = new THREE.CubeTextureLoader();
  16634. * loader.setPath( 'textures/cube/pisa/' );
  16635. *
  16636. * const textureCube = loader.load( [
  16637. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16638. * ] );
  16639. *
  16640. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16641. * ```
  16642. *
  16643. * @augments Texture
  16644. */
  16645. class CubeTexture extends Texture {
  16646. /**
  16647. * Constructs a new cube texture.
  16648. *
  16649. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16650. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16651. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16652. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16653. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16654. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16655. * @param {number} [format=RGBAFormat] - The texture format.
  16656. * @param {number} [type=UnsignedByteType] - The texture type.
  16657. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16658. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16659. */
  16660. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16661. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16662. /**
  16663. * This flag can be used for type testing.
  16664. *
  16665. * @type {boolean}
  16666. * @readonly
  16667. * @default true
  16668. */
  16669. this.isCubeTexture = true;
  16670. /**
  16671. * If set to `true`, the texture is flipped along the vertical axis when
  16672. * uploaded to the GPU.
  16673. *
  16674. * Overwritten and set to `false` by default.
  16675. *
  16676. * @type {boolean}
  16677. * @default false
  16678. */
  16679. this.flipY = false;
  16680. }
  16681. /**
  16682. * Alias for {@link CubeTexture#image}.
  16683. *
  16684. * @type {Array<Image>}
  16685. */
  16686. get images() {
  16687. return this.image;
  16688. }
  16689. set images( value ) {
  16690. this.image = value;
  16691. }
  16692. }
  16693. /**
  16694. * A cube render target used in context of {@link WebGLRenderer}.
  16695. *
  16696. * @augments WebGLRenderTarget
  16697. */
  16698. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16699. /**
  16700. * Constructs a new cube render target.
  16701. *
  16702. * @param {number} [size=1] - The size of the render target.
  16703. * @param {RenderTarget~Options} [options] - The configuration object.
  16704. */
  16705. constructor( size = 1, options = {} ) {
  16706. super( size, size, options );
  16707. /**
  16708. * This flag can be used for type testing.
  16709. *
  16710. * @type {boolean}
  16711. * @readonly
  16712. * @default true
  16713. */
  16714. this.isWebGLCubeRenderTarget = true;
  16715. const image = { width: size, height: size, depth: 1 };
  16716. const images = [ image, image, image, image, image, image ];
  16717. /**
  16718. * Overwritten with a different texture type.
  16719. *
  16720. * @type {DataArrayTexture}
  16721. */
  16722. this.texture = new CubeTexture( images );
  16723. this._setTextureOptions( options );
  16724. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16725. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16726. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16727. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16728. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16729. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16730. this.texture.isRenderTargetTexture = true;
  16731. }
  16732. /**
  16733. * Converts the given equirectangular texture to a cube map.
  16734. *
  16735. * @param {WebGLRenderer} renderer - The renderer.
  16736. * @param {Texture} texture - The equirectangular texture.
  16737. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16738. */
  16739. fromEquirectangularTexture( renderer, texture ) {
  16740. this.texture.type = texture.type;
  16741. this.texture.colorSpace = texture.colorSpace;
  16742. this.texture.generateMipmaps = texture.generateMipmaps;
  16743. this.texture.minFilter = texture.minFilter;
  16744. this.texture.magFilter = texture.magFilter;
  16745. const shader = {
  16746. uniforms: {
  16747. tEquirect: { value: null },
  16748. },
  16749. vertexShader: /* glsl */`
  16750. varying vec3 vWorldDirection;
  16751. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16752. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16753. }
  16754. void main() {
  16755. vWorldDirection = transformDirection( position, modelMatrix );
  16756. #include <begin_vertex>
  16757. #include <project_vertex>
  16758. }
  16759. `,
  16760. fragmentShader: /* glsl */`
  16761. uniform sampler2D tEquirect;
  16762. varying vec3 vWorldDirection;
  16763. #include <common>
  16764. void main() {
  16765. vec3 direction = normalize( vWorldDirection );
  16766. vec2 sampleUV = equirectUv( direction );
  16767. gl_FragColor = texture2D( tEquirect, sampleUV );
  16768. }
  16769. `
  16770. };
  16771. const geometry = new BoxGeometry( 5, 5, 5 );
  16772. const material = new ShaderMaterial( {
  16773. name: 'CubemapFromEquirect',
  16774. uniforms: cloneUniforms( shader.uniforms ),
  16775. vertexShader: shader.vertexShader,
  16776. fragmentShader: shader.fragmentShader,
  16777. side: BackSide,
  16778. blending: NoBlending
  16779. } );
  16780. material.uniforms.tEquirect.value = texture;
  16781. const mesh = new Mesh( geometry, material );
  16782. const currentMinFilter = texture.minFilter;
  16783. // Avoid blurred poles
  16784. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16785. const camera = new CubeCamera( 1, 10, this );
  16786. camera.update( renderer, mesh );
  16787. texture.minFilter = currentMinFilter;
  16788. mesh.geometry.dispose();
  16789. mesh.material.dispose();
  16790. return this;
  16791. }
  16792. /**
  16793. * Clears this cube render target.
  16794. *
  16795. * @param {WebGLRenderer} renderer - The renderer.
  16796. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16797. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16798. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16799. */
  16800. clear( renderer, color = true, depth = true, stencil = true ) {
  16801. const currentRenderTarget = renderer.getRenderTarget();
  16802. for ( let i = 0; i < 6; i ++ ) {
  16803. renderer.setRenderTarget( this, i );
  16804. renderer.clear( color, depth, stencil );
  16805. }
  16806. renderer.setRenderTarget( currentRenderTarget );
  16807. }
  16808. }
  16809. /**
  16810. * This is almost identical to an {@link Object3D}. Its purpose is to
  16811. * make working with groups of objects syntactically clearer.
  16812. *
  16813. * ```js
  16814. * // Create a group and add the two cubes.
  16815. * // These cubes can now be rotated / scaled etc as a group.
  16816. * const group = new THREE.Group();
  16817. *
  16818. * group.add( meshA );
  16819. * group.add( meshB );
  16820. *
  16821. * scene.add( group );
  16822. * ```
  16823. *
  16824. * @augments Object3D
  16825. */
  16826. class Group extends Object3D {
  16827. constructor() {
  16828. super();
  16829. /**
  16830. * This flag can be used for type testing.
  16831. *
  16832. * @type {boolean}
  16833. * @readonly
  16834. * @default true
  16835. */
  16836. this.isGroup = true;
  16837. this.type = 'Group';
  16838. }
  16839. }
  16840. const _moveEvent = { type: 'move' };
  16841. /**
  16842. * Class for representing a XR controller with its
  16843. * different coordinate systems.
  16844. *
  16845. * @private
  16846. */
  16847. class WebXRController {
  16848. /**
  16849. * Constructs a new XR controller.
  16850. */
  16851. constructor() {
  16852. /**
  16853. * A group representing the target ray space
  16854. * of the XR controller.
  16855. *
  16856. * @private
  16857. * @type {?Group}
  16858. * @default null
  16859. */
  16860. this._targetRay = null;
  16861. /**
  16862. * A group representing the grip space
  16863. * of the XR controller.
  16864. *
  16865. * @private
  16866. * @type {?Group}
  16867. * @default null
  16868. */
  16869. this._grip = null;
  16870. /**
  16871. * A group representing the hand space
  16872. * of the XR controller.
  16873. *
  16874. * @private
  16875. * @type {?Group}
  16876. * @default null
  16877. */
  16878. this._hand = null;
  16879. }
  16880. /**
  16881. * Returns a group representing the hand space of the XR controller.
  16882. *
  16883. * @return {Group} A group representing the hand space of the XR controller.
  16884. */
  16885. getHandSpace() {
  16886. if ( this._hand === null ) {
  16887. this._hand = new Group();
  16888. this._hand.matrixAutoUpdate = false;
  16889. this._hand.visible = false;
  16890. this._hand.joints = {};
  16891. this._hand.inputState = { pinching: false };
  16892. }
  16893. return this._hand;
  16894. }
  16895. /**
  16896. * Returns a group representing the target ray space of the XR controller.
  16897. *
  16898. * @return {Group} A group representing the target ray space of the XR controller.
  16899. */
  16900. getTargetRaySpace() {
  16901. if ( this._targetRay === null ) {
  16902. this._targetRay = new Group();
  16903. this._targetRay.matrixAutoUpdate = false;
  16904. this._targetRay.visible = false;
  16905. this._targetRay.hasLinearVelocity = false;
  16906. this._targetRay.linearVelocity = new Vector3();
  16907. this._targetRay.hasAngularVelocity = false;
  16908. this._targetRay.angularVelocity = new Vector3();
  16909. }
  16910. return this._targetRay;
  16911. }
  16912. /**
  16913. * Returns a group representing the grip space of the XR controller.
  16914. *
  16915. * @return {Group} A group representing the grip space of the XR controller.
  16916. */
  16917. getGripSpace() {
  16918. if ( this._grip === null ) {
  16919. this._grip = new Group();
  16920. this._grip.matrixAutoUpdate = false;
  16921. this._grip.visible = false;
  16922. this._grip.hasLinearVelocity = false;
  16923. this._grip.linearVelocity = new Vector3();
  16924. this._grip.hasAngularVelocity = false;
  16925. this._grip.angularVelocity = new Vector3();
  16926. }
  16927. return this._grip;
  16928. }
  16929. /**
  16930. * Dispatches the given event to the groups representing
  16931. * the different coordinate spaces of the XR controller.
  16932. *
  16933. * @param {Object} event - The event to dispatch.
  16934. * @return {WebXRController} A reference to this instance.
  16935. */
  16936. dispatchEvent( event ) {
  16937. if ( this._targetRay !== null ) {
  16938. this._targetRay.dispatchEvent( event );
  16939. }
  16940. if ( this._grip !== null ) {
  16941. this._grip.dispatchEvent( event );
  16942. }
  16943. if ( this._hand !== null ) {
  16944. this._hand.dispatchEvent( event );
  16945. }
  16946. return this;
  16947. }
  16948. /**
  16949. * Connects the controller with the given XR input source.
  16950. *
  16951. * @param {XRInputSource} inputSource - The input source.
  16952. * @return {WebXRController} A reference to this instance.
  16953. */
  16954. connect( inputSource ) {
  16955. if ( inputSource && inputSource.hand ) {
  16956. const hand = this._hand;
  16957. if ( hand ) {
  16958. for ( const inputjoint of inputSource.hand.values() ) {
  16959. // Initialize hand with joints when connected
  16960. this._getHandJoint( hand, inputjoint );
  16961. }
  16962. }
  16963. }
  16964. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16965. return this;
  16966. }
  16967. /**
  16968. * Disconnects the controller from the given XR input source.
  16969. *
  16970. * @param {XRInputSource} inputSource - The input source.
  16971. * @return {WebXRController} A reference to this instance.
  16972. */
  16973. disconnect( inputSource ) {
  16974. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16975. if ( this._targetRay !== null ) {
  16976. this._targetRay.visible = false;
  16977. }
  16978. if ( this._grip !== null ) {
  16979. this._grip.visible = false;
  16980. }
  16981. if ( this._hand !== null ) {
  16982. this._hand.visible = false;
  16983. }
  16984. return this;
  16985. }
  16986. /**
  16987. * Updates the controller with the given input source, XR frame and reference space.
  16988. * This updates the transformations of the groups that represent the different
  16989. * coordinate systems of the controller.
  16990. *
  16991. * @param {XRInputSource} inputSource - The input source.
  16992. * @param {XRFrame} frame - The XR frame.
  16993. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16994. * @return {WebXRController} A reference to this instance.
  16995. */
  16996. update( inputSource, frame, referenceSpace ) {
  16997. let inputPose = null;
  16998. let gripPose = null;
  16999. let handPose = null;
  17000. const targetRay = this._targetRay;
  17001. const grip = this._grip;
  17002. const hand = this._hand;
  17003. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  17004. if ( hand && inputSource.hand ) {
  17005. handPose = true;
  17006. for ( const inputjoint of inputSource.hand.values() ) {
  17007. // Update the joints groups with the XRJoint poses
  17008. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  17009. // The transform of this joint will be updated with the joint pose on each frame
  17010. const joint = this._getHandJoint( hand, inputjoint );
  17011. if ( jointPose !== null ) {
  17012. joint.matrix.fromArray( jointPose.transform.matrix );
  17013. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  17014. joint.matrixWorldNeedsUpdate = true;
  17015. joint.jointRadius = jointPose.radius;
  17016. }
  17017. joint.visible = jointPose !== null;
  17018. }
  17019. // Custom events
  17020. // Check pinchz
  17021. const indexTip = hand.joints[ 'index-finger-tip' ];
  17022. const thumbTip = hand.joints[ 'thumb-tip' ];
  17023. const distance = indexTip.position.distanceTo( thumbTip.position );
  17024. const distanceToPinch = 0.02;
  17025. const threshold = 0.005;
  17026. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  17027. hand.inputState.pinching = false;
  17028. this.dispatchEvent( {
  17029. type: 'pinchend',
  17030. handedness: inputSource.handedness,
  17031. target: this
  17032. } );
  17033. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  17034. hand.inputState.pinching = true;
  17035. this.dispatchEvent( {
  17036. type: 'pinchstart',
  17037. handedness: inputSource.handedness,
  17038. target: this
  17039. } );
  17040. }
  17041. } else {
  17042. if ( grip !== null && inputSource.gripSpace ) {
  17043. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  17044. if ( gripPose !== null ) {
  17045. grip.matrix.fromArray( gripPose.transform.matrix );
  17046. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  17047. grip.matrixWorldNeedsUpdate = true;
  17048. if ( gripPose.linearVelocity ) {
  17049. grip.hasLinearVelocity = true;
  17050. grip.linearVelocity.copy( gripPose.linearVelocity );
  17051. } else {
  17052. grip.hasLinearVelocity = false;
  17053. }
  17054. if ( gripPose.angularVelocity ) {
  17055. grip.hasAngularVelocity = true;
  17056. grip.angularVelocity.copy( gripPose.angularVelocity );
  17057. } else {
  17058. grip.hasAngularVelocity = false;
  17059. }
  17060. }
  17061. }
  17062. }
  17063. if ( targetRay !== null ) {
  17064. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17065. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17066. if ( inputPose === null && gripPose !== null ) {
  17067. inputPose = gripPose;
  17068. }
  17069. if ( inputPose !== null ) {
  17070. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17071. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17072. targetRay.matrixWorldNeedsUpdate = true;
  17073. if ( inputPose.linearVelocity ) {
  17074. targetRay.hasLinearVelocity = true;
  17075. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17076. } else {
  17077. targetRay.hasLinearVelocity = false;
  17078. }
  17079. if ( inputPose.angularVelocity ) {
  17080. targetRay.hasAngularVelocity = true;
  17081. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17082. } else {
  17083. targetRay.hasAngularVelocity = false;
  17084. }
  17085. this.dispatchEvent( _moveEvent );
  17086. }
  17087. }
  17088. }
  17089. if ( targetRay !== null ) {
  17090. targetRay.visible = ( inputPose !== null );
  17091. }
  17092. if ( grip !== null ) {
  17093. grip.visible = ( gripPose !== null );
  17094. }
  17095. if ( hand !== null ) {
  17096. hand.visible = ( handPose !== null );
  17097. }
  17098. return this;
  17099. }
  17100. /**
  17101. * Returns a group representing the hand joint for the given input joint.
  17102. *
  17103. * @private
  17104. * @param {Group} hand - The group representing the hand space.
  17105. * @param {XRJointSpace} inputjoint - The hand joint data.
  17106. * @return {Group} A group representing the hand joint for the given input joint.
  17107. */
  17108. _getHandJoint( hand, inputjoint ) {
  17109. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17110. const joint = new Group();
  17111. joint.matrixAutoUpdate = false;
  17112. joint.visible = false;
  17113. hand.joints[ inputjoint.jointName ] = joint;
  17114. hand.add( joint );
  17115. }
  17116. return hand.joints[ inputjoint.jointName ];
  17117. }
  17118. }
  17119. /**
  17120. * This class can be used to define an exponential squared fog,
  17121. * which gives a clear view near the camera and a faster than exponentially
  17122. * densening fog farther from the camera.
  17123. *
  17124. * ```js
  17125. * const scene = new THREE.Scene();
  17126. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17127. * ```
  17128. */
  17129. class FogExp2 {
  17130. /**
  17131. * Constructs a new fog.
  17132. *
  17133. * @param {number|Color} color - The fog's color.
  17134. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17135. */
  17136. constructor( color, density = 0.00025 ) {
  17137. /**
  17138. * This flag can be used for type testing.
  17139. *
  17140. * @type {boolean}
  17141. * @readonly
  17142. * @default true
  17143. */
  17144. this.isFogExp2 = true;
  17145. /**
  17146. * The name of the fog.
  17147. *
  17148. * @type {string}
  17149. */
  17150. this.name = '';
  17151. /**
  17152. * The fog's color.
  17153. *
  17154. * @type {Color}
  17155. */
  17156. this.color = new Color( color );
  17157. /**
  17158. * Defines how fast the fog will grow dense.
  17159. *
  17160. * @type {number}
  17161. * @default 0.00025
  17162. */
  17163. this.density = density;
  17164. }
  17165. /**
  17166. * Returns a new fog with copied values from this instance.
  17167. *
  17168. * @return {FogExp2} A clone of this instance.
  17169. */
  17170. clone() {
  17171. return new FogExp2( this.color, this.density );
  17172. }
  17173. /**
  17174. * Serializes the fog into JSON.
  17175. *
  17176. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17177. * @return {Object} A JSON object representing the serialized fog
  17178. */
  17179. toJSON( /* meta */ ) {
  17180. return {
  17181. type: 'FogExp2',
  17182. name: this.name,
  17183. color: this.color.getHex(),
  17184. density: this.density
  17185. };
  17186. }
  17187. }
  17188. /**
  17189. * This class can be used to define a linear fog that grows linearly denser
  17190. * with the distance.
  17191. *
  17192. * ```js
  17193. * const scene = new THREE.Scene();
  17194. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17195. * ```
  17196. */
  17197. class Fog {
  17198. /**
  17199. * Constructs a new fog.
  17200. *
  17201. * @param {number|Color} color - The fog's color.
  17202. * @param {number} [near=1] - The minimum distance to start applying fog.
  17203. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17204. */
  17205. constructor( color, near = 1, far = 1000 ) {
  17206. /**
  17207. * This flag can be used for type testing.
  17208. *
  17209. * @type {boolean}
  17210. * @readonly
  17211. * @default true
  17212. */
  17213. this.isFog = true;
  17214. /**
  17215. * The name of the fog.
  17216. *
  17217. * @type {string}
  17218. */
  17219. this.name = '';
  17220. /**
  17221. * The fog's color.
  17222. *
  17223. * @type {Color}
  17224. */
  17225. this.color = new Color( color );
  17226. /**
  17227. * The minimum distance to start applying fog. Objects that are less than
  17228. * `near` units from the active camera won't be affected by fog.
  17229. *
  17230. * @type {number}
  17231. * @default 1
  17232. */
  17233. this.near = near;
  17234. /**
  17235. * The maximum distance at which fog stops being calculated and applied.
  17236. * Objects that are more than `far` units away from the active camera won't
  17237. * be affected by fog.
  17238. *
  17239. * @type {number}
  17240. * @default 1000
  17241. */
  17242. this.far = far;
  17243. }
  17244. /**
  17245. * Returns a new fog with copied values from this instance.
  17246. *
  17247. * @return {Fog} A clone of this instance.
  17248. */
  17249. clone() {
  17250. return new Fog( this.color, this.near, this.far );
  17251. }
  17252. /**
  17253. * Serializes the fog into JSON.
  17254. *
  17255. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17256. * @return {Object} A JSON object representing the serialized fog
  17257. */
  17258. toJSON( /* meta */ ) {
  17259. return {
  17260. type: 'Fog',
  17261. name: this.name,
  17262. color: this.color.getHex(),
  17263. near: this.near,
  17264. far: this.far
  17265. };
  17266. }
  17267. }
  17268. /**
  17269. * Scenes allow you to set up what is to be rendered and where by three.js.
  17270. * This is where you place 3D objects like meshes, lines or lights.
  17271. *
  17272. * @augments Object3D
  17273. */
  17274. class Scene extends Object3D {
  17275. /**
  17276. * Constructs a new scene.
  17277. */
  17278. constructor() {
  17279. super();
  17280. /**
  17281. * This flag can be used for type testing.
  17282. *
  17283. * @type {boolean}
  17284. * @readonly
  17285. * @default true
  17286. */
  17287. this.isScene = true;
  17288. this.type = 'Scene';
  17289. /**
  17290. * Defines the background of the scene. Valid inputs are:
  17291. *
  17292. * - A color for defining a uniform colored background.
  17293. * - A texture for defining a (flat) textured background.
  17294. * - Cube textures or equirectangular textures for defining a skybox.
  17295. *
  17296. * @type {?(Color|Texture)}
  17297. * @default null
  17298. */
  17299. this.background = null;
  17300. /**
  17301. * Sets the environment map for all physical materials in the scene. However,
  17302. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17303. * material property.
  17304. *
  17305. * @type {?Texture}
  17306. * @default null
  17307. */
  17308. this.environment = null;
  17309. /**
  17310. * A fog instance defining the type of fog that affects everything
  17311. * rendered in the scene.
  17312. *
  17313. * @type {?(Fog|FogExp2)}
  17314. * @default null
  17315. */
  17316. this.fog = null;
  17317. /**
  17318. * Sets the blurriness of the background. Only influences environment maps
  17319. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17320. * and `1`.
  17321. *
  17322. * @type {number}
  17323. * @default 0
  17324. */
  17325. this.backgroundBlurriness = 0;
  17326. /**
  17327. * Attenuates the color of the background. Only applies to background textures.
  17328. *
  17329. * @type {number}
  17330. * @default 1
  17331. */
  17332. this.backgroundIntensity = 1;
  17333. /**
  17334. * The rotation of the background in radians. Only influences environment maps
  17335. * assigned to {@link Scene#background}.
  17336. *
  17337. * @type {Euler}
  17338. * @default (0,0,0)
  17339. */
  17340. this.backgroundRotation = new Euler();
  17341. /**
  17342. * Attenuates the color of the environment. Only influences environment maps
  17343. * assigned to {@link Scene#environment}.
  17344. *
  17345. * @type {number}
  17346. * @default 1
  17347. */
  17348. this.environmentIntensity = 1;
  17349. /**
  17350. * The rotation of the environment map in radians. Only influences physical materials
  17351. * in the scene when {@link Scene#environment} is used.
  17352. *
  17353. * @type {Euler}
  17354. * @default (0,0,0)
  17355. */
  17356. this.environmentRotation = new Euler();
  17357. /**
  17358. * Forces everything in the scene to be rendered with the defined material. It is possible
  17359. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17360. *
  17361. * @type {?Material}
  17362. * @default null
  17363. */
  17364. this.overrideMaterial = null;
  17365. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17366. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17367. }
  17368. }
  17369. copy( source, recursive ) {
  17370. super.copy( source, recursive );
  17371. if ( source.background !== null ) this.background = source.background.clone();
  17372. if ( source.environment !== null ) this.environment = source.environment.clone();
  17373. if ( source.fog !== null ) this.fog = source.fog.clone();
  17374. this.backgroundBlurriness = source.backgroundBlurriness;
  17375. this.backgroundIntensity = source.backgroundIntensity;
  17376. this.backgroundRotation.copy( source.backgroundRotation );
  17377. this.environmentIntensity = source.environmentIntensity;
  17378. this.environmentRotation.copy( source.environmentRotation );
  17379. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17380. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17381. return this;
  17382. }
  17383. toJSON( meta ) {
  17384. const data = super.toJSON( meta );
  17385. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17386. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17387. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17388. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17389. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17390. data.object.environmentRotation = this.environmentRotation.toArray();
  17391. return data;
  17392. }
  17393. }
  17394. /**
  17395. * "Interleaved" means that multiple attributes, possibly of different types,
  17396. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17397. *
  17398. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17399. */
  17400. class InterleavedBuffer {
  17401. /**
  17402. * Constructs a new interleaved buffer.
  17403. *
  17404. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17405. * @param {number} stride - The number of typed-array elements per vertex.
  17406. */
  17407. constructor( array, stride ) {
  17408. /**
  17409. * This flag can be used for type testing.
  17410. *
  17411. * @type {boolean}
  17412. * @readonly
  17413. * @default true
  17414. */
  17415. this.isInterleavedBuffer = true;
  17416. /**
  17417. * A typed array with a shared buffer storing attribute data.
  17418. *
  17419. * @type {TypedArray}
  17420. */
  17421. this.array = array;
  17422. /**
  17423. * The number of typed-array elements per vertex.
  17424. *
  17425. * @type {number}
  17426. */
  17427. this.stride = stride;
  17428. /**
  17429. * The total number of elements in the array
  17430. *
  17431. * @type {number}
  17432. * @readonly
  17433. */
  17434. this.count = array !== undefined ? array.length / stride : 0;
  17435. /**
  17436. * Defines the intended usage pattern of the data store for optimization purposes.
  17437. *
  17438. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17439. * instantiate a new one and set the desired usage before the next render.
  17440. *
  17441. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17442. * @default StaticDrawUsage
  17443. */
  17444. this.usage = StaticDrawUsage;
  17445. /**
  17446. * This can be used to only update some components of stored vectors (for example, just the
  17447. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17448. *
  17449. * @type {Array<Object>}
  17450. */
  17451. this.updateRanges = [];
  17452. /**
  17453. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17454. *
  17455. * @type {number}
  17456. */
  17457. this.version = 0;
  17458. /**
  17459. * The UUID of the interleaved buffer.
  17460. *
  17461. * @type {string}
  17462. * @readonly
  17463. */
  17464. this.uuid = generateUUID();
  17465. }
  17466. /**
  17467. * A callback function that is executed after the renderer has transferred the attribute array
  17468. * data to the GPU.
  17469. */
  17470. onUploadCallback() {}
  17471. /**
  17472. * Flag to indicate that this attribute has changed and should be re-sent to
  17473. * the GPU. Set this to `true` when you modify the value of the array.
  17474. *
  17475. * @type {number}
  17476. * @default false
  17477. * @param {boolean} value
  17478. */
  17479. set needsUpdate( value ) {
  17480. if ( value === true ) this.version ++;
  17481. }
  17482. /**
  17483. * Sets the usage of this interleaved buffer.
  17484. *
  17485. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17486. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17487. */
  17488. setUsage( value ) {
  17489. this.usage = value;
  17490. return this;
  17491. }
  17492. /**
  17493. * Adds a range of data in the data array to be updated on the GPU.
  17494. *
  17495. * @param {number} start - Position at which to start update.
  17496. * @param {number} count - The number of components to update.
  17497. */
  17498. addUpdateRange( start, count ) {
  17499. this.updateRanges.push( { start, count } );
  17500. }
  17501. /**
  17502. * Clears the update ranges.
  17503. */
  17504. clearUpdateRanges() {
  17505. this.updateRanges.length = 0;
  17506. }
  17507. /**
  17508. * Copies the values of the given interleaved buffer to this instance.
  17509. *
  17510. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17511. * @return {InterleavedBuffer} A reference to this instance.
  17512. */
  17513. copy( source ) {
  17514. this.array = new source.array.constructor( source.array );
  17515. this.count = source.count;
  17516. this.stride = source.stride;
  17517. this.usage = source.usage;
  17518. return this;
  17519. }
  17520. /**
  17521. * Copies a vector from the given interleaved buffer to this one. The start
  17522. * and destination position in the attribute buffers are represented by the
  17523. * given indices.
  17524. *
  17525. * @param {number} index1 - The destination index into this interleaved buffer.
  17526. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17527. * @param {number} index2 - The source index into the given interleaved buffer.
  17528. * @return {InterleavedBuffer} A reference to this instance.
  17529. */
  17530. copyAt( index1, interleavedBuffer, index2 ) {
  17531. index1 *= this.stride;
  17532. index2 *= interleavedBuffer.stride;
  17533. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17534. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17535. }
  17536. return this;
  17537. }
  17538. /**
  17539. * Sets the given array data in the interleaved buffer.
  17540. *
  17541. * @param {(TypedArray|Array)} value - The array data to set.
  17542. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17543. * @return {InterleavedBuffer} A reference to this instance.
  17544. */
  17545. set( value, offset = 0 ) {
  17546. this.array.set( value, offset );
  17547. return this;
  17548. }
  17549. /**
  17550. * Returns a new interleaved buffer with copied values from this instance.
  17551. *
  17552. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17553. * @return {InterleavedBuffer} A clone of this instance.
  17554. */
  17555. clone( data ) {
  17556. if ( data.arrayBuffers === undefined ) {
  17557. data.arrayBuffers = {};
  17558. }
  17559. if ( this.array.buffer._uuid === undefined ) {
  17560. this.array.buffer._uuid = generateUUID();
  17561. }
  17562. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17563. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17564. }
  17565. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17566. const ib = new this.constructor( array, this.stride );
  17567. ib.setUsage( this.usage );
  17568. return ib;
  17569. }
  17570. /**
  17571. * Sets the given callback function that is executed after the Renderer has transferred
  17572. * the array data to the GPU. Can be used to perform clean-up operations after
  17573. * the upload when data are not needed anymore on the CPU side.
  17574. *
  17575. * @param {Function} callback - The `onUpload()` callback.
  17576. * @return {InterleavedBuffer} A reference to this instance.
  17577. */
  17578. onUpload( callback ) {
  17579. this.onUploadCallback = callback;
  17580. return this;
  17581. }
  17582. /**
  17583. * Serializes the interleaved buffer into JSON.
  17584. *
  17585. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17586. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17587. */
  17588. toJSON( data ) {
  17589. if ( data.arrayBuffers === undefined ) {
  17590. data.arrayBuffers = {};
  17591. }
  17592. // generate UUID for array buffer if necessary
  17593. if ( this.array.buffer._uuid === undefined ) {
  17594. this.array.buffer._uuid = generateUUID();
  17595. }
  17596. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17597. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17598. }
  17599. //
  17600. return {
  17601. uuid: this.uuid,
  17602. buffer: this.array.buffer._uuid,
  17603. type: this.array.constructor.name,
  17604. stride: this.stride
  17605. };
  17606. }
  17607. }
  17608. const _vector$7 = /*@__PURE__*/ new Vector3();
  17609. /**
  17610. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17611. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17612. * different offsets into the buffer.
  17613. */
  17614. class InterleavedBufferAttribute {
  17615. /**
  17616. * Constructs a new interleaved buffer attribute.
  17617. *
  17618. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17619. * @param {number} itemSize - The item size.
  17620. * @param {number} offset - The attribute offset into the buffer.
  17621. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17622. */
  17623. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17624. /**
  17625. * This flag can be used for type testing.
  17626. *
  17627. * @type {boolean}
  17628. * @readonly
  17629. * @default true
  17630. */
  17631. this.isInterleavedBufferAttribute = true;
  17632. /**
  17633. * The name of the buffer attribute.
  17634. *
  17635. * @type {string}
  17636. */
  17637. this.name = '';
  17638. /**
  17639. * The buffer holding the interleaved data.
  17640. *
  17641. * @type {InterleavedBuffer}
  17642. */
  17643. this.data = interleavedBuffer;
  17644. /**
  17645. * The item size, see {@link BufferAttribute#itemSize}.
  17646. *
  17647. * @type {number}
  17648. */
  17649. this.itemSize = itemSize;
  17650. /**
  17651. * The attribute offset into the buffer.
  17652. *
  17653. * @type {number}
  17654. */
  17655. this.offset = offset;
  17656. /**
  17657. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17658. *
  17659. * @type {InterleavedBuffer}
  17660. */
  17661. this.normalized = normalized;
  17662. }
  17663. /**
  17664. * The item count of this buffer attribute.
  17665. *
  17666. * @type {number}
  17667. * @readonly
  17668. */
  17669. get count() {
  17670. return this.data.count;
  17671. }
  17672. /**
  17673. * The array holding the interleaved buffer attribute data.
  17674. *
  17675. * @type {TypedArray}
  17676. */
  17677. get array() {
  17678. return this.data.array;
  17679. }
  17680. /**
  17681. * Flag to indicate that this attribute has changed and should be re-sent to
  17682. * the GPU. Set this to `true` when you modify the value of the array.
  17683. *
  17684. * @type {number}
  17685. * @default false
  17686. * @param {boolean} value
  17687. */
  17688. set needsUpdate( value ) {
  17689. this.data.needsUpdate = value;
  17690. }
  17691. /**
  17692. * Applies the given 4x4 matrix to the given attribute. Only works with
  17693. * item size `3`.
  17694. *
  17695. * @param {Matrix4} m - The matrix to apply.
  17696. * @return {InterleavedBufferAttribute} A reference to this instance.
  17697. */
  17698. applyMatrix4( m ) {
  17699. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17700. _vector$7.fromBufferAttribute( this, i );
  17701. _vector$7.applyMatrix4( m );
  17702. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17703. }
  17704. return this;
  17705. }
  17706. /**
  17707. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17708. * item size `3`.
  17709. *
  17710. * @param {Matrix3} m - The normal matrix to apply.
  17711. * @return {InterleavedBufferAttribute} A reference to this instance.
  17712. */
  17713. applyNormalMatrix( m ) {
  17714. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17715. _vector$7.fromBufferAttribute( this, i );
  17716. _vector$7.applyNormalMatrix( m );
  17717. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17718. }
  17719. return this;
  17720. }
  17721. /**
  17722. * Applies the given 4x4 matrix to the given attribute. Only works with
  17723. * item size `3` and with direction vectors.
  17724. *
  17725. * @param {Matrix4} m - The matrix to apply.
  17726. * @return {InterleavedBufferAttribute} A reference to this instance.
  17727. */
  17728. transformDirection( m ) {
  17729. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17730. _vector$7.fromBufferAttribute( this, i );
  17731. _vector$7.transformDirection( m );
  17732. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17733. }
  17734. return this;
  17735. }
  17736. /**
  17737. * Returns the given component of the vector at the given index.
  17738. *
  17739. * @param {number} index - The index into the buffer attribute.
  17740. * @param {number} component - The component index.
  17741. * @return {number} The returned value.
  17742. */
  17743. getComponent( index, component ) {
  17744. let value = this.array[ index * this.data.stride + this.offset + component ];
  17745. if ( this.normalized ) value = denormalize( value, this.array );
  17746. return value;
  17747. }
  17748. /**
  17749. * Sets the given value to the given component of the vector at the given index.
  17750. *
  17751. * @param {number} index - The index into the buffer attribute.
  17752. * @param {number} component - The component index.
  17753. * @param {number} value - The value to set.
  17754. * @return {InterleavedBufferAttribute} A reference to this instance.
  17755. */
  17756. setComponent( index, component, value ) {
  17757. if ( this.normalized ) value = normalize( value, this.array );
  17758. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17759. return this;
  17760. }
  17761. /**
  17762. * Sets the x component of the vector at the given index.
  17763. *
  17764. * @param {number} index - The index into the buffer attribute.
  17765. * @param {number} x - The value to set.
  17766. * @return {InterleavedBufferAttribute} A reference to this instance.
  17767. */
  17768. setX( index, x ) {
  17769. if ( this.normalized ) x = normalize( x, this.array );
  17770. this.data.array[ index * this.data.stride + this.offset ] = x;
  17771. return this;
  17772. }
  17773. /**
  17774. * Sets the y component of the vector at the given index.
  17775. *
  17776. * @param {number} index - The index into the buffer attribute.
  17777. * @param {number} y - The value to set.
  17778. * @return {InterleavedBufferAttribute} A reference to this instance.
  17779. */
  17780. setY( index, y ) {
  17781. if ( this.normalized ) y = normalize( y, this.array );
  17782. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17783. return this;
  17784. }
  17785. /**
  17786. * Sets the z component of the vector at the given index.
  17787. *
  17788. * @param {number} index - The index into the buffer attribute.
  17789. * @param {number} z - The value to set.
  17790. * @return {InterleavedBufferAttribute} A reference to this instance.
  17791. */
  17792. setZ( index, z ) {
  17793. if ( this.normalized ) z = normalize( z, this.array );
  17794. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17795. return this;
  17796. }
  17797. /**
  17798. * Sets the w component of the vector at the given index.
  17799. *
  17800. * @param {number} index - The index into the buffer attribute.
  17801. * @param {number} w - The value to set.
  17802. * @return {InterleavedBufferAttribute} A reference to this instance.
  17803. */
  17804. setW( index, w ) {
  17805. if ( this.normalized ) w = normalize( w, this.array );
  17806. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17807. return this;
  17808. }
  17809. /**
  17810. * Returns the x component of the vector at the given index.
  17811. *
  17812. * @param {number} index - The index into the buffer attribute.
  17813. * @return {number} The x component.
  17814. */
  17815. getX( index ) {
  17816. let x = this.data.array[ index * this.data.stride + this.offset ];
  17817. if ( this.normalized ) x = denormalize( x, this.array );
  17818. return x;
  17819. }
  17820. /**
  17821. * Returns the y component of the vector at the given index.
  17822. *
  17823. * @param {number} index - The index into the buffer attribute.
  17824. * @return {number} The y component.
  17825. */
  17826. getY( index ) {
  17827. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17828. if ( this.normalized ) y = denormalize( y, this.array );
  17829. return y;
  17830. }
  17831. /**
  17832. * Returns the z component of the vector at the given index.
  17833. *
  17834. * @param {number} index - The index into the buffer attribute.
  17835. * @return {number} The z component.
  17836. */
  17837. getZ( index ) {
  17838. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17839. if ( this.normalized ) z = denormalize( z, this.array );
  17840. return z;
  17841. }
  17842. /**
  17843. * Returns the w component of the vector at the given index.
  17844. *
  17845. * @param {number} index - The index into the buffer attribute.
  17846. * @return {number} The w component.
  17847. */
  17848. getW( index ) {
  17849. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17850. if ( this.normalized ) w = denormalize( w, this.array );
  17851. return w;
  17852. }
  17853. /**
  17854. * Sets the x and y component of the vector at the given index.
  17855. *
  17856. * @param {number} index - The index into the buffer attribute.
  17857. * @param {number} x - The value for the x component to set.
  17858. * @param {number} y - The value for the y component to set.
  17859. * @return {InterleavedBufferAttribute} A reference to this instance.
  17860. */
  17861. setXY( index, x, y ) {
  17862. index = index * this.data.stride + this.offset;
  17863. if ( this.normalized ) {
  17864. x = normalize( x, this.array );
  17865. y = normalize( y, this.array );
  17866. }
  17867. this.data.array[ index + 0 ] = x;
  17868. this.data.array[ index + 1 ] = y;
  17869. return this;
  17870. }
  17871. /**
  17872. * Sets the x, y and z component of the vector at the given index.
  17873. *
  17874. * @param {number} index - The index into the buffer attribute.
  17875. * @param {number} x - The value for the x component to set.
  17876. * @param {number} y - The value for the y component to set.
  17877. * @param {number} z - The value for the z component to set.
  17878. * @return {InterleavedBufferAttribute} A reference to this instance.
  17879. */
  17880. setXYZ( index, x, y, z ) {
  17881. index = index * this.data.stride + this.offset;
  17882. if ( this.normalized ) {
  17883. x = normalize( x, this.array );
  17884. y = normalize( y, this.array );
  17885. z = normalize( z, this.array );
  17886. }
  17887. this.data.array[ index + 0 ] = x;
  17888. this.data.array[ index + 1 ] = y;
  17889. this.data.array[ index + 2 ] = z;
  17890. return this;
  17891. }
  17892. /**
  17893. * Sets the x, y, z and w component of the vector at the given index.
  17894. *
  17895. * @param {number} index - The index into the buffer attribute.
  17896. * @param {number} x - The value for the x component to set.
  17897. * @param {number} y - The value for the y component to set.
  17898. * @param {number} z - The value for the z component to set.
  17899. * @param {number} w - The value for the w component to set.
  17900. * @return {InterleavedBufferAttribute} A reference to this instance.
  17901. */
  17902. setXYZW( index, x, y, z, w ) {
  17903. index = index * this.data.stride + this.offset;
  17904. if ( this.normalized ) {
  17905. x = normalize( x, this.array );
  17906. y = normalize( y, this.array );
  17907. z = normalize( z, this.array );
  17908. w = normalize( w, this.array );
  17909. }
  17910. this.data.array[ index + 0 ] = x;
  17911. this.data.array[ index + 1 ] = y;
  17912. this.data.array[ index + 2 ] = z;
  17913. this.data.array[ index + 3 ] = w;
  17914. return this;
  17915. }
  17916. /**
  17917. * Returns a new buffer attribute with copied values from this instance.
  17918. *
  17919. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17920. *
  17921. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17922. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17923. */
  17924. clone( data ) {
  17925. if ( data === undefined ) {
  17926. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17927. const array = [];
  17928. for ( let i = 0; i < this.count; i ++ ) {
  17929. const index = i * this.data.stride + this.offset;
  17930. for ( let j = 0; j < this.itemSize; j ++ ) {
  17931. array.push( this.data.array[ index + j ] );
  17932. }
  17933. }
  17934. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17935. } else {
  17936. if ( data.interleavedBuffers === undefined ) {
  17937. data.interleavedBuffers = {};
  17938. }
  17939. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17940. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17941. }
  17942. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17943. }
  17944. }
  17945. /**
  17946. * Serializes the buffer attribute into JSON.
  17947. *
  17948. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17949. *
  17950. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17951. * @return {Object} A JSON object representing the serialized buffer attribute.
  17952. */
  17953. toJSON( data ) {
  17954. if ( data === undefined ) {
  17955. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17956. const array = [];
  17957. for ( let i = 0; i < this.count; i ++ ) {
  17958. const index = i * this.data.stride + this.offset;
  17959. for ( let j = 0; j < this.itemSize; j ++ ) {
  17960. array.push( this.data.array[ index + j ] );
  17961. }
  17962. }
  17963. // de-interleave data and save it as an ordinary buffer attribute for now
  17964. return {
  17965. itemSize: this.itemSize,
  17966. type: this.array.constructor.name,
  17967. array: array,
  17968. normalized: this.normalized
  17969. };
  17970. } else {
  17971. // save as true interleaved attribute
  17972. if ( data.interleavedBuffers === undefined ) {
  17973. data.interleavedBuffers = {};
  17974. }
  17975. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17976. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17977. }
  17978. return {
  17979. isInterleavedBufferAttribute: true,
  17980. itemSize: this.itemSize,
  17981. data: this.data.uuid,
  17982. offset: this.offset,
  17983. normalized: this.normalized
  17984. };
  17985. }
  17986. }
  17987. }
  17988. /**
  17989. * A material for rendering instances of {@link Sprite}.
  17990. *
  17991. * ```js
  17992. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17993. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17994. *
  17995. * const sprite = new THREE.Sprite( material );
  17996. * sprite.scale.set(200, 200, 1)
  17997. * scene.add( sprite );
  17998. * ```
  17999. *
  18000. * @augments Material
  18001. */
  18002. class SpriteMaterial extends Material {
  18003. /**
  18004. * Constructs a new sprite material.
  18005. *
  18006. * @param {Object} [parameters] - An object with one or more properties
  18007. * defining the material's appearance. Any property of the material
  18008. * (including any property from inherited materials) can be passed
  18009. * in here. Color values can be passed any type of value accepted
  18010. * by {@link Color#set}.
  18011. */
  18012. constructor( parameters ) {
  18013. super();
  18014. /**
  18015. * This flag can be used for type testing.
  18016. *
  18017. * @type {boolean}
  18018. * @readonly
  18019. * @default true
  18020. */
  18021. this.isSpriteMaterial = true;
  18022. this.type = 'SpriteMaterial';
  18023. /**
  18024. * Color of the material.
  18025. *
  18026. * @type {Color}
  18027. * @default (1,1,1)
  18028. */
  18029. this.color = new Color( 0xffffff );
  18030. /**
  18031. * The color map. May optionally include an alpha channel, typically combined
  18032. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  18033. * color is modulated by the diffuse `color`.
  18034. *
  18035. * @type {?Texture}
  18036. * @default null
  18037. */
  18038. this.map = null;
  18039. /**
  18040. * The alpha map is a grayscale texture that controls the opacity across the
  18041. * surface (black: fully transparent; white: fully opaque).
  18042. *
  18043. * Only the color of the texture is used, ignoring the alpha channel if one
  18044. * exists. For RGB and RGBA textures, the renderer will use the green channel
  18045. * when sampling this texture due to the extra bit of precision provided for
  18046. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  18047. * luminance/alpha textures will also still work as expected.
  18048. *
  18049. * @type {?Texture}
  18050. * @default null
  18051. */
  18052. this.alphaMap = null;
  18053. /**
  18054. * The rotation of the sprite in radians.
  18055. *
  18056. * @type {number}
  18057. * @default 0
  18058. */
  18059. this.rotation = 0;
  18060. /**
  18061. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18062. *
  18063. * @type {boolean}
  18064. * @default true
  18065. */
  18066. this.sizeAttenuation = true;
  18067. /**
  18068. * Overwritten since sprite materials are transparent
  18069. * by default.
  18070. *
  18071. * @type {boolean}
  18072. * @default true
  18073. */
  18074. this.transparent = true;
  18075. /**
  18076. * Whether the material is affected by fog or not.
  18077. *
  18078. * @type {boolean}
  18079. * @default true
  18080. */
  18081. this.fog = true;
  18082. this.setValues( parameters );
  18083. }
  18084. copy( source ) {
  18085. super.copy( source );
  18086. this.color.copy( source.color );
  18087. this.map = source.map;
  18088. this.alphaMap = source.alphaMap;
  18089. this.rotation = source.rotation;
  18090. this.sizeAttenuation = source.sizeAttenuation;
  18091. this.fog = source.fog;
  18092. return this;
  18093. }
  18094. }
  18095. let _geometry;
  18096. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18097. const _worldScale = /*@__PURE__*/ new Vector3();
  18098. const _mvPosition = /*@__PURE__*/ new Vector3();
  18099. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18100. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18101. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18102. const _vA = /*@__PURE__*/ new Vector3();
  18103. const _vB = /*@__PURE__*/ new Vector3();
  18104. const _vC = /*@__PURE__*/ new Vector3();
  18105. const _uvA = /*@__PURE__*/ new Vector2();
  18106. const _uvB = /*@__PURE__*/ new Vector2();
  18107. const _uvC = /*@__PURE__*/ new Vector2();
  18108. /**
  18109. * A sprite is a plane that always faces towards the camera, generally with a
  18110. * partially transparent texture applied.
  18111. *
  18112. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18113. * have no effect.
  18114. *
  18115. * ```js
  18116. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18117. * const material = new THREE.SpriteMaterial( { map: map } );
  18118. *
  18119. * const sprite = new THREE.Sprite( material );
  18120. * scene.add( sprite );
  18121. * ```
  18122. *
  18123. * @augments Object3D
  18124. */
  18125. class Sprite extends Object3D {
  18126. /**
  18127. * Constructs a new sprite.
  18128. *
  18129. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18130. */
  18131. constructor( material = new SpriteMaterial() ) {
  18132. super();
  18133. /**
  18134. * This flag can be used for type testing.
  18135. *
  18136. * @type {boolean}
  18137. * @readonly
  18138. * @default true
  18139. */
  18140. this.isSprite = true;
  18141. this.type = 'Sprite';
  18142. if ( _geometry === undefined ) {
  18143. _geometry = new BufferGeometry();
  18144. const float32Array = new Float32Array( [
  18145. -0.5, -0.5, 0, 0, 0,
  18146. 0.5, -0.5, 0, 1, 0,
  18147. 0.5, 0.5, 0, 1, 1,
  18148. -0.5, 0.5, 0, 0, 1
  18149. ] );
  18150. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18151. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18152. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18153. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18154. }
  18155. /**
  18156. * The sprite geometry.
  18157. *
  18158. * @type {BufferGeometry}
  18159. */
  18160. this.geometry = _geometry;
  18161. /**
  18162. * The sprite material.
  18163. *
  18164. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18165. */
  18166. this.material = material;
  18167. /**
  18168. * The sprite's anchor point, and the point around which the sprite rotates.
  18169. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18170. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18171. *
  18172. * @type {Vector2}
  18173. * @default (0.5,0.5)
  18174. */
  18175. this.center = new Vector2( 0.5, 0.5 );
  18176. /**
  18177. * The number of instances of this sprite.
  18178. * Can only be used with {@link WebGPURenderer}.
  18179. *
  18180. * @type {number}
  18181. * @default 1
  18182. */
  18183. this.count = 1;
  18184. }
  18185. /**
  18186. * Computes intersection points between a casted ray and this sprite.
  18187. *
  18188. * @param {Raycaster} raycaster - The raycaster.
  18189. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18190. */
  18191. raycast( raycaster, intersects ) {
  18192. if ( raycaster.camera === null ) {
  18193. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18194. }
  18195. _worldScale.setFromMatrixScale( this.matrixWorld );
  18196. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18197. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18198. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18199. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18200. _worldScale.multiplyScalar( - _mvPosition.z );
  18201. }
  18202. const rotation = this.material.rotation;
  18203. let sin, cos;
  18204. if ( rotation !== 0 ) {
  18205. cos = Math.cos( rotation );
  18206. sin = Math.sin( rotation );
  18207. }
  18208. const center = this.center;
  18209. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18210. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18211. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18212. _uvA.set( 0, 0 );
  18213. _uvB.set( 1, 0 );
  18214. _uvC.set( 1, 1 );
  18215. // check first triangle
  18216. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18217. if ( intersect === null ) {
  18218. // check second triangle
  18219. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18220. _uvB.set( 0, 1 );
  18221. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18222. if ( intersect === null ) {
  18223. return;
  18224. }
  18225. }
  18226. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18227. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18228. intersects.push( {
  18229. distance: distance,
  18230. point: _intersectPoint.clone(),
  18231. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18232. face: null,
  18233. object: this
  18234. } );
  18235. }
  18236. copy( source, recursive ) {
  18237. super.copy( source, recursive );
  18238. if ( source.center !== undefined ) this.center.copy( source.center );
  18239. this.material = source.material;
  18240. return this;
  18241. }
  18242. }
  18243. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18244. // compute position in camera space
  18245. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18246. // to check if rotation is not zero
  18247. if ( sin !== undefined ) {
  18248. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18249. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18250. } else {
  18251. _rotatedPosition.copy( _alignedPosition );
  18252. }
  18253. vertexPosition.copy( mvPosition );
  18254. vertexPosition.x += _rotatedPosition.x;
  18255. vertexPosition.y += _rotatedPosition.y;
  18256. // transform to world space
  18257. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18258. }
  18259. const _v1$2 = /*@__PURE__*/ new Vector3();
  18260. const _v2$1 = /*@__PURE__*/ new Vector3();
  18261. /**
  18262. * A component for providing a basic Level of Detail (LOD) mechanism.
  18263. *
  18264. * Every LOD level is associated with an object, and rendering can be switched
  18265. * between them at the distances specified. Typically you would create, say,
  18266. * three meshes, one for far away (low detail), one for mid range (medium
  18267. * detail) and one for close up (high detail).
  18268. *
  18269. * ```js
  18270. * const lod = new THREE.LOD();
  18271. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18272. *
  18273. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18274. * for( let i = 0; i < 3; i++ ) {
  18275. *
  18276. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18277. * const mesh = new THREE.Mesh( geometry, material );
  18278. * lod.addLevel( mesh, i * 75 );
  18279. *
  18280. * }
  18281. *
  18282. * scene.add( lod );
  18283. * ```
  18284. *
  18285. * @augments Object3D
  18286. */
  18287. class LOD extends Object3D {
  18288. /**
  18289. * Constructs a new LOD.
  18290. */
  18291. constructor() {
  18292. super();
  18293. /**
  18294. * This flag can be used for type testing.
  18295. *
  18296. * @type {boolean}
  18297. * @readonly
  18298. * @default true
  18299. */
  18300. this.isLOD = true;
  18301. /**
  18302. * The current LOD index.
  18303. *
  18304. * @private
  18305. * @type {number}
  18306. * @default 0
  18307. */
  18308. this._currentLevel = 0;
  18309. this.type = 'LOD';
  18310. Object.defineProperties( this, {
  18311. /**
  18312. * This array holds the LOD levels.
  18313. *
  18314. * @name LOD#levels
  18315. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18316. */
  18317. levels: {
  18318. enumerable: true,
  18319. value: []
  18320. }
  18321. } );
  18322. /**
  18323. * Whether the LOD object is updated automatically by the renderer per frame
  18324. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18325. * render loop by yourself.
  18326. *
  18327. * @type {boolean}
  18328. * @default true
  18329. */
  18330. this.autoUpdate = true;
  18331. }
  18332. copy( source ) {
  18333. super.copy( source, false );
  18334. const levels = source.levels;
  18335. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18336. const level = levels[ i ];
  18337. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18338. }
  18339. this.autoUpdate = source.autoUpdate;
  18340. return this;
  18341. }
  18342. /**
  18343. * Adds a mesh that will display at a certain distance and greater. Typically
  18344. * the further away the distance, the lower the detail on the mesh.
  18345. *
  18346. * @param {Object3D} object - The 3D object to display at this level.
  18347. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18348. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18349. * @return {LOD} A reference to this instance.
  18350. */
  18351. addLevel( object, distance = 0, hysteresis = 0 ) {
  18352. distance = Math.abs( distance );
  18353. const levels = this.levels;
  18354. let l;
  18355. for ( l = 0; l < levels.length; l ++ ) {
  18356. if ( distance < levels[ l ].distance ) {
  18357. break;
  18358. }
  18359. }
  18360. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18361. this.add( object );
  18362. return this;
  18363. }
  18364. /**
  18365. * Removes an existing level, based on the distance from the camera.
  18366. * Returns `true` when the level has been removed. Otherwise `false`.
  18367. *
  18368. * @param {number} distance - Distance of the level to remove.
  18369. * @return {boolean} Whether the level has been removed or not.
  18370. */
  18371. removeLevel( distance ) {
  18372. const levels = this.levels;
  18373. for ( let i = 0; i < levels.length; i ++ ) {
  18374. if ( levels[ i ].distance === distance ) {
  18375. const removedElements = levels.splice( i, 1 );
  18376. this.remove( removedElements[ 0 ].object );
  18377. return true;
  18378. }
  18379. }
  18380. return false;
  18381. }
  18382. /**
  18383. * Returns the currently active LOD level index.
  18384. *
  18385. * @return {number} The current active LOD level index.
  18386. */
  18387. getCurrentLevel() {
  18388. return this._currentLevel;
  18389. }
  18390. /**
  18391. * Returns a reference to the first 3D object that is greater than
  18392. * the given distance.
  18393. *
  18394. * @param {number} distance - The LOD distance.
  18395. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18396. */
  18397. getObjectForDistance( distance ) {
  18398. const levels = this.levels;
  18399. if ( levels.length > 0 ) {
  18400. let i, l;
  18401. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18402. let levelDistance = levels[ i ].distance;
  18403. if ( levels[ i ].object.visible ) {
  18404. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18405. }
  18406. if ( distance < levelDistance ) {
  18407. break;
  18408. }
  18409. }
  18410. return levels[ i - 1 ].object;
  18411. }
  18412. return null;
  18413. }
  18414. /**
  18415. * Computes intersection points between a casted ray and this LOD.
  18416. *
  18417. * @param {Raycaster} raycaster - The raycaster.
  18418. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18419. */
  18420. raycast( raycaster, intersects ) {
  18421. const levels = this.levels;
  18422. if ( levels.length > 0 ) {
  18423. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18424. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18425. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18426. }
  18427. }
  18428. /**
  18429. * Updates the LOD by computing which LOD level should be visible according
  18430. * to the current distance of the given camera.
  18431. *
  18432. * @param {Camera} camera - The camera the scene is rendered with.
  18433. */
  18434. update( camera ) {
  18435. const levels = this.levels;
  18436. if ( levels.length > 1 ) {
  18437. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18438. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18439. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18440. levels[ 0 ].object.visible = true;
  18441. let i, l;
  18442. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18443. let levelDistance = levels[ i ].distance;
  18444. if ( levels[ i ].object.visible ) {
  18445. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18446. }
  18447. if ( distance >= levelDistance ) {
  18448. levels[ i - 1 ].object.visible = false;
  18449. levels[ i ].object.visible = true;
  18450. } else {
  18451. break;
  18452. }
  18453. }
  18454. this._currentLevel = i - 1;
  18455. for ( ; i < l; i ++ ) {
  18456. levels[ i ].object.visible = false;
  18457. }
  18458. }
  18459. }
  18460. toJSON( meta ) {
  18461. const data = super.toJSON( meta );
  18462. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18463. data.object.levels = [];
  18464. const levels = this.levels;
  18465. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18466. const level = levels[ i ];
  18467. data.object.levels.push( {
  18468. object: level.object.uuid,
  18469. distance: level.distance,
  18470. hysteresis: level.hysteresis
  18471. } );
  18472. }
  18473. return data;
  18474. }
  18475. }
  18476. const _basePosition = /*@__PURE__*/ new Vector3();
  18477. const _skinIndex = /*@__PURE__*/ new Vector4();
  18478. const _skinWeight = /*@__PURE__*/ new Vector4();
  18479. const _vector3 = /*@__PURE__*/ new Vector3();
  18480. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18481. const _vertex = /*@__PURE__*/ new Vector3();
  18482. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18483. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18484. const _ray$2 = /*@__PURE__*/ new Ray();
  18485. /**
  18486. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18487. * vertices of the geometry with skinning/skeleton animation.
  18488. *
  18489. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18490. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18491. * vertex to a certain extend.
  18492. *
  18493. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18494. * or {@link FBXLoader } import respective models.
  18495. *
  18496. * @augments Mesh
  18497. * @demo scenes/bones-browser.html
  18498. */
  18499. class SkinnedMesh extends Mesh {
  18500. /**
  18501. * Constructs a new skinned mesh.
  18502. *
  18503. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18504. * @param {Material|Array<Material>} [material] - The mesh material.
  18505. */
  18506. constructor( geometry, material ) {
  18507. super( geometry, material );
  18508. /**
  18509. * This flag can be used for type testing.
  18510. *
  18511. * @type {boolean}
  18512. * @readonly
  18513. * @default true
  18514. */
  18515. this.isSkinnedMesh = true;
  18516. this.type = 'SkinnedMesh';
  18517. /**
  18518. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18519. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18520. * across multiple skinned meshes.
  18521. *
  18522. * @type {(AttachedBindMode|DetachedBindMode)}
  18523. * @default AttachedBindMode
  18524. */
  18525. this.bindMode = AttachedBindMode;
  18526. /**
  18527. * The base matrix that is used for the bound bone transforms.
  18528. *
  18529. * @type {Matrix4}
  18530. */
  18531. this.bindMatrix = new Matrix4();
  18532. /**
  18533. * The base matrix that is used for resetting the bound bone transforms.
  18534. *
  18535. * @type {Matrix4}
  18536. */
  18537. this.bindMatrixInverse = new Matrix4();
  18538. /**
  18539. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18540. *
  18541. * @type {?Box3}
  18542. * @default null
  18543. */
  18544. this.boundingBox = null;
  18545. /**
  18546. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18547. *
  18548. * @type {?Sphere}
  18549. * @default null
  18550. */
  18551. this.boundingSphere = null;
  18552. }
  18553. /**
  18554. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18555. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18556. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18557. * the current animation state.
  18558. */
  18559. computeBoundingBox() {
  18560. const geometry = this.geometry;
  18561. if ( this.boundingBox === null ) {
  18562. this.boundingBox = new Box3();
  18563. }
  18564. this.boundingBox.makeEmpty();
  18565. const positionAttribute = geometry.getAttribute( 'position' );
  18566. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18567. this.getVertexPosition( i, _vertex );
  18568. this.boundingBox.expandByPoint( _vertex );
  18569. }
  18570. }
  18571. /**
  18572. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18573. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18574. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18575. * per frame in order to reflect the current animation state.
  18576. */
  18577. computeBoundingSphere() {
  18578. const geometry = this.geometry;
  18579. if ( this.boundingSphere === null ) {
  18580. this.boundingSphere = new Sphere();
  18581. }
  18582. this.boundingSphere.makeEmpty();
  18583. const positionAttribute = geometry.getAttribute( 'position' );
  18584. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18585. this.getVertexPosition( i, _vertex );
  18586. this.boundingSphere.expandByPoint( _vertex );
  18587. }
  18588. }
  18589. copy( source, recursive ) {
  18590. super.copy( source, recursive );
  18591. this.bindMode = source.bindMode;
  18592. this.bindMatrix.copy( source.bindMatrix );
  18593. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18594. this.skeleton = source.skeleton;
  18595. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18596. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18597. return this;
  18598. }
  18599. raycast( raycaster, intersects ) {
  18600. const material = this.material;
  18601. const matrixWorld = this.matrixWorld;
  18602. if ( material === undefined ) return;
  18603. // test with bounding sphere in world space
  18604. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18605. _sphere$5.copy( this.boundingSphere );
  18606. _sphere$5.applyMatrix4( matrixWorld );
  18607. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18608. // convert ray to local space of skinned mesh
  18609. _inverseMatrix$2.copy( matrixWorld ).invert();
  18610. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18611. // test with bounding box in local space
  18612. if ( this.boundingBox !== null ) {
  18613. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18614. }
  18615. // test for intersections with geometry
  18616. this._computeIntersections( raycaster, intersects, _ray$2 );
  18617. }
  18618. getVertexPosition( index, target ) {
  18619. super.getVertexPosition( index, target );
  18620. this.applyBoneTransform( index, target );
  18621. return target;
  18622. }
  18623. /**
  18624. * Binds the given skeleton to the skinned mesh.
  18625. *
  18626. * @param {Skeleton} skeleton - The skeleton to bind.
  18627. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18628. * the skinned mesh's world matrix will be used instead.
  18629. */
  18630. bind( skeleton, bindMatrix ) {
  18631. this.skeleton = skeleton;
  18632. if ( bindMatrix === undefined ) {
  18633. this.updateMatrixWorld( true );
  18634. this.skeleton.calculateInverses();
  18635. bindMatrix = this.matrixWorld;
  18636. }
  18637. this.bindMatrix.copy( bindMatrix );
  18638. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18639. }
  18640. /**
  18641. * This method sets the skinned mesh in the rest pose).
  18642. */
  18643. pose() {
  18644. this.skeleton.pose();
  18645. }
  18646. /**
  18647. * Normalizes the skin weights which are defined as a buffer attribute
  18648. * in the skinned mesh's geometry.
  18649. */
  18650. normalizeSkinWeights() {
  18651. const vector = new Vector4();
  18652. const skinWeight = this.geometry.attributes.skinWeight;
  18653. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18654. vector.fromBufferAttribute( skinWeight, i );
  18655. const scale = 1.0 / vector.manhattanLength();
  18656. if ( scale !== Infinity ) {
  18657. vector.multiplyScalar( scale );
  18658. } else {
  18659. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18660. }
  18661. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18662. }
  18663. }
  18664. updateMatrixWorld( force ) {
  18665. super.updateMatrixWorld( force );
  18666. if ( this.bindMode === AttachedBindMode ) {
  18667. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18668. } else if ( this.bindMode === DetachedBindMode ) {
  18669. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18670. } else {
  18671. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18672. }
  18673. }
  18674. /**
  18675. * Applies the bone transform associated with the given index to the given
  18676. * vertex position. Returns the updated vector.
  18677. *
  18678. * @param {number} index - The vertex index.
  18679. * @param {Vector3} target - The target object that is used to store the method's result.
  18680. * the skinned mesh's world matrix will be used instead.
  18681. * @return {Vector3} The updated vertex position.
  18682. */
  18683. applyBoneTransform( index, target ) {
  18684. const skeleton = this.skeleton;
  18685. const geometry = this.geometry;
  18686. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18687. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18688. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18689. target.set( 0, 0, 0 );
  18690. for ( let i = 0; i < 4; i ++ ) {
  18691. const weight = _skinWeight.getComponent( i );
  18692. if ( weight !== 0 ) {
  18693. const boneIndex = _skinIndex.getComponent( i );
  18694. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18695. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18696. }
  18697. }
  18698. return target.applyMatrix4( this.bindMatrixInverse );
  18699. }
  18700. }
  18701. /**
  18702. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18703. * the {@link SkinnedMesh}.
  18704. *
  18705. * ```js
  18706. * const root = new THREE.Bone();
  18707. * const child = new THREE.Bone();
  18708. *
  18709. * root.add( child );
  18710. * child.position.y = 5;
  18711. * ```
  18712. *
  18713. * @augments Object3D
  18714. */
  18715. class Bone extends Object3D {
  18716. /**
  18717. * Constructs a new bone.
  18718. */
  18719. constructor() {
  18720. super();
  18721. /**
  18722. * This flag can be used for type testing.
  18723. *
  18724. * @type {boolean}
  18725. * @readonly
  18726. * @default true
  18727. */
  18728. this.isBone = true;
  18729. this.type = 'Bone';
  18730. }
  18731. }
  18732. /**
  18733. * Creates a texture directly from raw buffer data.
  18734. *
  18735. * The interpretation of the data depends on type and format: If the type is
  18736. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18737. * texel data. If the format is `RGBAFormat`, data needs four values for
  18738. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18739. *
  18740. * @augments Texture
  18741. */
  18742. class DataTexture extends Texture {
  18743. /**
  18744. * Constructs a new data texture.
  18745. *
  18746. * @param {?TypedArray} [data=null] - The buffer data.
  18747. * @param {number} [width=1] - The width of the texture.
  18748. * @param {number} [height=1] - The height of the texture.
  18749. * @param {number} [format=RGBAFormat] - The texture format.
  18750. * @param {number} [type=UnsignedByteType] - The texture type.
  18751. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18752. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18753. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18754. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18755. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18756. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18757. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18758. */
  18759. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18760. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18761. /**
  18762. * This flag can be used for type testing.
  18763. *
  18764. * @type {boolean}
  18765. * @readonly
  18766. * @default true
  18767. */
  18768. this.isDataTexture = true;
  18769. /**
  18770. * The image definition of a data texture.
  18771. *
  18772. * @type {{data:TypedArray,width:number,height:number}}
  18773. */
  18774. this.image = { data: data, width: width, height: height };
  18775. /**
  18776. * Whether to generate mipmaps (if possible) for a texture.
  18777. *
  18778. * Overwritten and set to `false` by default.
  18779. *
  18780. * @type {boolean}
  18781. * @default false
  18782. */
  18783. this.generateMipmaps = false;
  18784. /**
  18785. * If set to `true`, the texture is flipped along the vertical axis when
  18786. * uploaded to the GPU.
  18787. *
  18788. * Overwritten and set to `false` by default.
  18789. *
  18790. * @type {boolean}
  18791. * @default false
  18792. */
  18793. this.flipY = false;
  18794. /**
  18795. * Specifies the alignment requirements for the start of each pixel row in memory.
  18796. *
  18797. * Overwritten and set to `1` by default.
  18798. *
  18799. * @type {boolean}
  18800. * @default 1
  18801. */
  18802. this.unpackAlignment = 1;
  18803. }
  18804. }
  18805. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18806. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18807. /**
  18808. * Class for representing the armatures in `three.js`. The skeleton
  18809. * is defined by a hierarchy of bones.
  18810. *
  18811. * ```js
  18812. * const bones = [];
  18813. *
  18814. * const shoulder = new THREE.Bone();
  18815. * const elbow = new THREE.Bone();
  18816. * const hand = new THREE.Bone();
  18817. *
  18818. * shoulder.add( elbow );
  18819. * elbow.add( hand );
  18820. *
  18821. * bones.push( shoulder , elbow, hand);
  18822. *
  18823. * shoulder.position.y = -5;
  18824. * elbow.position.y = 0;
  18825. * hand.position.y = 5;
  18826. *
  18827. * const armSkeleton = new THREE.Skeleton( bones );
  18828. * ```
  18829. */
  18830. class Skeleton {
  18831. /**
  18832. * Constructs a new skeleton.
  18833. *
  18834. * @param {Array<Bone>} [bones] - An array of bones.
  18835. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18836. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18837. */
  18838. constructor( bones = [], boneInverses = [] ) {
  18839. this.uuid = generateUUID();
  18840. /**
  18841. * An array of bones defining the skeleton.
  18842. *
  18843. * @type {Array<Bone>}
  18844. */
  18845. this.bones = bones.slice( 0 );
  18846. /**
  18847. * An array of bone inverse matrices.
  18848. *
  18849. * @type {Array<Matrix4>}
  18850. */
  18851. this.boneInverses = boneInverses;
  18852. /**
  18853. * An array buffer holding the bone data.
  18854. * Input data for {@link Skeleton#boneTexture}.
  18855. *
  18856. * @type {?Float32Array}
  18857. * @default null
  18858. */
  18859. this.boneMatrices = null;
  18860. /**
  18861. * An array buffer holding the bone data of the previous frame.
  18862. * Required for computing velocity. Maintained in {@link SkinningNode}.
  18863. *
  18864. * @type {?Float32Array}
  18865. * @default null
  18866. */
  18867. this.previousBoneMatrices = null;
  18868. /**
  18869. * A texture holding the bone data for use
  18870. * in the vertex shader.
  18871. *
  18872. * @type {?DataTexture}
  18873. * @default null
  18874. */
  18875. this.boneTexture = null;
  18876. this.init();
  18877. }
  18878. /**
  18879. * Initializes the skeleton. This method gets automatically called by the constructor
  18880. * but depending on how the skeleton is created it might be necessary to call this method
  18881. * manually.
  18882. */
  18883. init() {
  18884. const bones = this.bones;
  18885. const boneInverses = this.boneInverses;
  18886. this.boneMatrices = new Float32Array( bones.length * 16 );
  18887. // calculate inverse bone matrices if necessary
  18888. if ( boneInverses.length === 0 ) {
  18889. this.calculateInverses();
  18890. } else {
  18891. // handle special case
  18892. if ( bones.length !== boneInverses.length ) {
  18893. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18894. this.boneInverses = [];
  18895. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18896. this.boneInverses.push( new Matrix4() );
  18897. }
  18898. }
  18899. }
  18900. }
  18901. /**
  18902. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18903. * and fills it with new matrices.
  18904. */
  18905. calculateInverses() {
  18906. this.boneInverses.length = 0;
  18907. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18908. const inverse = new Matrix4();
  18909. if ( this.bones[ i ] ) {
  18910. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18911. }
  18912. this.boneInverses.push( inverse );
  18913. }
  18914. }
  18915. /**
  18916. * Resets the skeleton to the base pose.
  18917. */
  18918. pose() {
  18919. // recover the bind-time world matrices
  18920. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18921. const bone = this.bones[ i ];
  18922. if ( bone ) {
  18923. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18924. }
  18925. }
  18926. // compute the local matrices, positions, rotations and scales
  18927. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18928. const bone = this.bones[ i ];
  18929. if ( bone ) {
  18930. if ( bone.parent && bone.parent.isBone ) {
  18931. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18932. bone.matrix.multiply( bone.matrixWorld );
  18933. } else {
  18934. bone.matrix.copy( bone.matrixWorld );
  18935. }
  18936. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18937. }
  18938. }
  18939. }
  18940. /**
  18941. * Resets the skeleton to the base pose.
  18942. */
  18943. update() {
  18944. const bones = this.bones;
  18945. const boneInverses = this.boneInverses;
  18946. const boneMatrices = this.boneMatrices;
  18947. const boneTexture = this.boneTexture;
  18948. // flatten bone matrices to array
  18949. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18950. // compute the offset between the current and the original transform
  18951. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18952. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18953. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18954. }
  18955. if ( boneTexture !== null ) {
  18956. boneTexture.needsUpdate = true;
  18957. }
  18958. }
  18959. /**
  18960. * Returns a new skeleton with copied values from this instance.
  18961. *
  18962. * @return {Skeleton} A clone of this instance.
  18963. */
  18964. clone() {
  18965. return new Skeleton( this.bones, this.boneInverses );
  18966. }
  18967. /**
  18968. * Computes a data texture for passing bone data to the vertex shader.
  18969. *
  18970. * @return {Skeleton} A reference of this instance.
  18971. */
  18972. computeBoneTexture() {
  18973. // layout (1 matrix = 4 pixels)
  18974. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18975. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18976. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18977. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18978. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18979. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18980. size = Math.ceil( size / 4 ) * 4;
  18981. size = Math.max( size, 4 );
  18982. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18983. boneMatrices.set( this.boneMatrices ); // copy current values
  18984. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18985. boneTexture.needsUpdate = true;
  18986. this.boneMatrices = boneMatrices;
  18987. this.boneTexture = boneTexture;
  18988. return this;
  18989. }
  18990. /**
  18991. * Searches through the skeleton's bone array and returns the first with a
  18992. * matching name.
  18993. *
  18994. * @param {string} name - The name of the bone.
  18995. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18996. */
  18997. getBoneByName( name ) {
  18998. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18999. const bone = this.bones[ i ];
  19000. if ( bone.name === name ) {
  19001. return bone;
  19002. }
  19003. }
  19004. return undefined;
  19005. }
  19006. /**
  19007. * Frees the GPU-related resources allocated by this instance. Call this
  19008. * method whenever this instance is no longer used in your app.
  19009. */
  19010. dispose( ) {
  19011. if ( this.boneTexture !== null ) {
  19012. this.boneTexture.dispose();
  19013. this.boneTexture = null;
  19014. }
  19015. }
  19016. /**
  19017. * Setups the skeleton by the given JSON and bones.
  19018. *
  19019. * @param {Object} json - The skeleton as serialized JSON.
  19020. * @param {Object<string, Bone>} bones - An array of bones.
  19021. * @return {Skeleton} A reference of this instance.
  19022. */
  19023. fromJSON( json, bones ) {
  19024. this.uuid = json.uuid;
  19025. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19026. const uuid = json.bones[ i ];
  19027. let bone = bones[ uuid ];
  19028. if ( bone === undefined ) {
  19029. warn( 'Skeleton: No bone found with UUID:', uuid );
  19030. bone = new Bone();
  19031. }
  19032. this.bones.push( bone );
  19033. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19034. }
  19035. this.init();
  19036. return this;
  19037. }
  19038. /**
  19039. * Serializes the skeleton into JSON.
  19040. *
  19041. * @return {Object} A JSON object representing the serialized skeleton.
  19042. * @see {@link ObjectLoader#parse}
  19043. */
  19044. toJSON() {
  19045. const data = {
  19046. metadata: {
  19047. version: 4.7,
  19048. type: 'Skeleton',
  19049. generator: 'Skeleton.toJSON'
  19050. },
  19051. bones: [],
  19052. boneInverses: []
  19053. };
  19054. data.uuid = this.uuid;
  19055. const bones = this.bones;
  19056. const boneInverses = this.boneInverses;
  19057. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19058. const bone = bones[ i ];
  19059. data.bones.push( bone.uuid );
  19060. const boneInverse = boneInverses[ i ];
  19061. data.boneInverses.push( boneInverse.toArray() );
  19062. }
  19063. return data;
  19064. }
  19065. }
  19066. /**
  19067. * An instanced version of a buffer attribute.
  19068. *
  19069. * @augments BufferAttribute
  19070. */
  19071. class InstancedBufferAttribute extends BufferAttribute {
  19072. /**
  19073. * Constructs a new instanced buffer attribute.
  19074. *
  19075. * @param {TypedArray} array - The array holding the attribute data.
  19076. * @param {number} itemSize - The item size.
  19077. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19078. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19079. */
  19080. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19081. super( array, itemSize, normalized );
  19082. /**
  19083. * This flag can be used for type testing.
  19084. *
  19085. * @type {boolean}
  19086. * @readonly
  19087. * @default true
  19088. */
  19089. this.isInstancedBufferAttribute = true;
  19090. /**
  19091. * Defines how often a value of this buffer attribute should be repeated. A
  19092. * value of one means that each value of the instanced attribute is used for
  19093. * a single instance. A value of two means that each value is used for two
  19094. * consecutive instances (and so on).
  19095. *
  19096. * @type {number}
  19097. * @default 1
  19098. */
  19099. this.meshPerAttribute = meshPerAttribute;
  19100. }
  19101. copy( source ) {
  19102. super.copy( source );
  19103. this.meshPerAttribute = source.meshPerAttribute;
  19104. return this;
  19105. }
  19106. toJSON() {
  19107. const data = super.toJSON();
  19108. data.meshPerAttribute = this.meshPerAttribute;
  19109. data.isInstancedBufferAttribute = true;
  19110. return data;
  19111. }
  19112. }
  19113. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19114. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19115. const _instanceIntersects = [];
  19116. const _box3 = /*@__PURE__*/ new Box3();
  19117. const _identity = /*@__PURE__*/ new Matrix4();
  19118. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19119. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19120. /**
  19121. * A special version of a mesh with instanced rendering support. Use
  19122. * this class if you have to render a large number of objects with the same
  19123. * geometry and material(s) but with different world transformations. The usage
  19124. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19125. * improve the overall rendering performance in your application.
  19126. *
  19127. * @augments Mesh
  19128. */
  19129. class InstancedMesh extends Mesh {
  19130. /**
  19131. * Constructs a new instanced mesh.
  19132. *
  19133. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19134. * @param {Material|Array<Material>} [material] - The mesh material.
  19135. * @param {number} count - The number of instances.
  19136. */
  19137. constructor( geometry, material, count ) {
  19138. super( geometry, material );
  19139. /**
  19140. * This flag can be used for type testing.
  19141. *
  19142. * @type {boolean}
  19143. * @readonly
  19144. * @default true
  19145. */
  19146. this.isInstancedMesh = true;
  19147. /**
  19148. * Represents the local transformation of all instances. You have to set its
  19149. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19150. * via {@link InstancedMesh#setMatrixAt}.
  19151. *
  19152. * @type {InstancedBufferAttribute}
  19153. */
  19154. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19155. /**
  19156. * Represents the local transformation of all instances of the previous frame.
  19157. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19158. *
  19159. * @type {?InstancedBufferAttribute}
  19160. * @default null
  19161. */
  19162. this.previousInstanceMatrix = null;
  19163. /**
  19164. * Represents the color of all instances. You have to set its
  19165. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19166. * via {@link InstancedMesh#setColorAt}.
  19167. *
  19168. * @type {?InstancedBufferAttribute}
  19169. * @default null
  19170. */
  19171. this.instanceColor = null;
  19172. /**
  19173. * Represents the morph target weights of all instances. You have to set its
  19174. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19175. * via {@link InstancedMesh#setMorphAt}.
  19176. *
  19177. * @type {?DataTexture}
  19178. * @default null
  19179. */
  19180. this.morphTexture = null;
  19181. /**
  19182. * The number of instances.
  19183. *
  19184. * @type {number}
  19185. */
  19186. this.count = count;
  19187. /**
  19188. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19189. *
  19190. * @type {?Box3}
  19191. * @default null
  19192. */
  19193. this.boundingBox = null;
  19194. /**
  19195. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19196. *
  19197. * @type {?Sphere}
  19198. * @default null
  19199. */
  19200. this.boundingSphere = null;
  19201. for ( let i = 0; i < count; i ++ ) {
  19202. this.setMatrixAt( i, _identity );
  19203. }
  19204. }
  19205. /**
  19206. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19207. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19208. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19209. */
  19210. computeBoundingBox() {
  19211. const geometry = this.geometry;
  19212. const count = this.count;
  19213. if ( this.boundingBox === null ) {
  19214. this.boundingBox = new Box3();
  19215. }
  19216. if ( geometry.boundingBox === null ) {
  19217. geometry.computeBoundingBox();
  19218. }
  19219. this.boundingBox.makeEmpty();
  19220. for ( let i = 0; i < count; i ++ ) {
  19221. this.getMatrixAt( i, _instanceLocalMatrix );
  19222. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19223. this.boundingBox.union( _box3 );
  19224. }
  19225. }
  19226. /**
  19227. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19228. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19229. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19230. */
  19231. computeBoundingSphere() {
  19232. const geometry = this.geometry;
  19233. const count = this.count;
  19234. if ( this.boundingSphere === null ) {
  19235. this.boundingSphere = new Sphere();
  19236. }
  19237. if ( geometry.boundingSphere === null ) {
  19238. geometry.computeBoundingSphere();
  19239. }
  19240. this.boundingSphere.makeEmpty();
  19241. for ( let i = 0; i < count; i ++ ) {
  19242. this.getMatrixAt( i, _instanceLocalMatrix );
  19243. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19244. this.boundingSphere.union( _sphere$4 );
  19245. }
  19246. }
  19247. copy( source, recursive ) {
  19248. super.copy( source, recursive );
  19249. this.instanceMatrix.copy( source.instanceMatrix );
  19250. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19251. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19252. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19253. this.count = source.count;
  19254. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19255. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19256. return this;
  19257. }
  19258. /**
  19259. * Gets the color of the defined instance.
  19260. *
  19261. * @param {number} index - The instance index.
  19262. * @param {Color} color - The target object that is used to store the method's result.
  19263. */
  19264. getColorAt( index, color ) {
  19265. color.fromArray( this.instanceColor.array, index * 3 );
  19266. }
  19267. /**
  19268. * Gets the local transformation matrix of the defined instance.
  19269. *
  19270. * @param {number} index - The instance index.
  19271. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19272. */
  19273. getMatrixAt( index, matrix ) {
  19274. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19275. }
  19276. /**
  19277. * Gets the morph target weights of the defined instance.
  19278. *
  19279. * @param {number} index - The instance index.
  19280. * @param {Mesh} object - The target object that is used to store the method's result.
  19281. */
  19282. getMorphAt( index, object ) {
  19283. const objectInfluences = object.morphTargetInfluences;
  19284. const array = this.morphTexture.source.data.data;
  19285. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19286. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19287. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19288. objectInfluences[ i ] = array[ dataIndex + i ];
  19289. }
  19290. }
  19291. raycast( raycaster, intersects ) {
  19292. const matrixWorld = this.matrixWorld;
  19293. const raycastTimes = this.count;
  19294. _mesh$1.geometry = this.geometry;
  19295. _mesh$1.material = this.material;
  19296. if ( _mesh$1.material === undefined ) return;
  19297. // test with bounding sphere first
  19298. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19299. _sphere$4.copy( this.boundingSphere );
  19300. _sphere$4.applyMatrix4( matrixWorld );
  19301. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19302. // now test each instance
  19303. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19304. // calculate the world matrix for each instance
  19305. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19306. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19307. // the mesh represents this single instance
  19308. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19309. _mesh$1.raycast( raycaster, _instanceIntersects );
  19310. // process the result of raycast
  19311. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19312. const intersect = _instanceIntersects[ i ];
  19313. intersect.instanceId = instanceId;
  19314. intersect.object = this;
  19315. intersects.push( intersect );
  19316. }
  19317. _instanceIntersects.length = 0;
  19318. }
  19319. }
  19320. /**
  19321. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19322. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19323. *
  19324. * @param {number} index - The instance index.
  19325. * @param {Color} color - The instance color.
  19326. */
  19327. setColorAt( index, color ) {
  19328. if ( this.instanceColor === null ) {
  19329. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19330. }
  19331. color.toArray( this.instanceColor.array, index * 3 );
  19332. }
  19333. /**
  19334. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19335. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19336. *
  19337. * @param {number} index - The instance index.
  19338. * @param {Matrix4} matrix - The local transformation.
  19339. */
  19340. setMatrixAt( index, matrix ) {
  19341. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19342. }
  19343. /**
  19344. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19345. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19346. *
  19347. * @param {number} index - The instance index.
  19348. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19349. * of a single instance.
  19350. */
  19351. setMorphAt( index, object ) {
  19352. const objectInfluences = object.morphTargetInfluences;
  19353. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19354. if ( this.morphTexture === null ) {
  19355. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19356. }
  19357. const array = this.morphTexture.source.data.data;
  19358. let morphInfluencesSum = 0;
  19359. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19360. morphInfluencesSum += objectInfluences[ i ];
  19361. }
  19362. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19363. const dataIndex = len * index;
  19364. array[ dataIndex ] = morphBaseInfluence;
  19365. array.set( objectInfluences, dataIndex + 1 );
  19366. }
  19367. updateMorphTargets() {
  19368. }
  19369. /**
  19370. * Frees the GPU-related resources allocated by this instance. Call this
  19371. * method whenever this instance is no longer used in your app.
  19372. */
  19373. dispose() {
  19374. this.dispatchEvent( { type: 'dispose' } );
  19375. if ( this.morphTexture !== null ) {
  19376. this.morphTexture.dispose();
  19377. this.morphTexture = null;
  19378. }
  19379. }
  19380. }
  19381. const _vector1 = /*@__PURE__*/ new Vector3();
  19382. const _vector2 = /*@__PURE__*/ new Vector3();
  19383. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19384. /**
  19385. * A two dimensional surface that extends infinitely in 3D space, represented
  19386. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19387. * by a unit length normal vector and a constant.
  19388. */
  19389. class Plane {
  19390. /**
  19391. * Constructs a new plane.
  19392. *
  19393. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19394. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19395. */
  19396. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19397. /**
  19398. * This flag can be used for type testing.
  19399. *
  19400. * @type {boolean}
  19401. * @readonly
  19402. * @default true
  19403. */
  19404. this.isPlane = true;
  19405. /**
  19406. * A unit length vector defining the normal of the plane.
  19407. *
  19408. * @type {Vector3}
  19409. */
  19410. this.normal = normal;
  19411. /**
  19412. * The signed distance from the origin to the plane.
  19413. *
  19414. * @type {number}
  19415. * @default 0
  19416. */
  19417. this.constant = constant;
  19418. }
  19419. /**
  19420. * Sets the plane components by copying the given values.
  19421. *
  19422. * @param {Vector3} normal - The normal.
  19423. * @param {number} constant - The constant.
  19424. * @return {Plane} A reference to this plane.
  19425. */
  19426. set( normal, constant ) {
  19427. this.normal.copy( normal );
  19428. this.constant = constant;
  19429. return this;
  19430. }
  19431. /**
  19432. * Sets the plane components by defining `x`, `y`, `z` as the
  19433. * plane normal and `w` as the constant.
  19434. *
  19435. * @param {number} x - The value for the normal's x component.
  19436. * @param {number} y - The value for the normal's y component.
  19437. * @param {number} z - The value for the normal's z component.
  19438. * @param {number} w - The constant value.
  19439. * @return {Plane} A reference to this plane.
  19440. */
  19441. setComponents( x, y, z, w ) {
  19442. this.normal.set( x, y, z );
  19443. this.constant = w;
  19444. return this;
  19445. }
  19446. /**
  19447. * Sets the plane from the given normal and coplanar point (that is a point
  19448. * that lies onto the plane).
  19449. *
  19450. * @param {Vector3} normal - The normal.
  19451. * @param {Vector3} point - A coplanar point.
  19452. * @return {Plane} A reference to this plane.
  19453. */
  19454. setFromNormalAndCoplanarPoint( normal, point ) {
  19455. this.normal.copy( normal );
  19456. this.constant = - point.dot( this.normal );
  19457. return this;
  19458. }
  19459. /**
  19460. * Sets the plane from three coplanar points. The winding order is
  19461. * assumed to be counter-clockwise, and determines the direction of
  19462. * the plane normal.
  19463. *
  19464. * @param {Vector3} a - The first coplanar point.
  19465. * @param {Vector3} b - The second coplanar point.
  19466. * @param {Vector3} c - The third coplanar point.
  19467. * @return {Plane} A reference to this plane.
  19468. */
  19469. setFromCoplanarPoints( a, b, c ) {
  19470. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19471. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19472. this.setFromNormalAndCoplanarPoint( normal, a );
  19473. return this;
  19474. }
  19475. /**
  19476. * Copies the values of the given plane to this instance.
  19477. *
  19478. * @param {Plane} plane - The plane to copy.
  19479. * @return {Plane} A reference to this plane.
  19480. */
  19481. copy( plane ) {
  19482. this.normal.copy( plane.normal );
  19483. this.constant = plane.constant;
  19484. return this;
  19485. }
  19486. /**
  19487. * Normalizes the plane normal and adjusts the constant accordingly.
  19488. *
  19489. * @return {Plane} A reference to this plane.
  19490. */
  19491. normalize() {
  19492. // Note: will lead to a divide by zero if the plane is invalid.
  19493. const inverseNormalLength = 1.0 / this.normal.length();
  19494. this.normal.multiplyScalar( inverseNormalLength );
  19495. this.constant *= inverseNormalLength;
  19496. return this;
  19497. }
  19498. /**
  19499. * Negates both the plane normal and the constant.
  19500. *
  19501. * @return {Plane} A reference to this plane.
  19502. */
  19503. negate() {
  19504. this.constant *= -1;
  19505. this.normal.negate();
  19506. return this;
  19507. }
  19508. /**
  19509. * Returns the signed distance from the given point to this plane.
  19510. *
  19511. * @param {Vector3} point - The point to compute the distance for.
  19512. * @return {number} The signed distance.
  19513. */
  19514. distanceToPoint( point ) {
  19515. return this.normal.dot( point ) + this.constant;
  19516. }
  19517. /**
  19518. * Returns the signed distance from the given sphere to this plane.
  19519. *
  19520. * @param {Sphere} sphere - The sphere to compute the distance for.
  19521. * @return {number} The signed distance.
  19522. */
  19523. distanceToSphere( sphere ) {
  19524. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19525. }
  19526. /**
  19527. * Projects a the given point onto the plane.
  19528. *
  19529. * @param {Vector3} point - The point to project.
  19530. * @param {Vector3} target - The target vector that is used to store the method's result.
  19531. * @return {Vector3} The projected point on the plane.
  19532. */
  19533. projectPoint( point, target ) {
  19534. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19535. }
  19536. /**
  19537. * Returns the intersection point of the passed line and the plane. Returns
  19538. * `null` if the line does not intersect. Returns the line's starting point if
  19539. * the line is coplanar with the plane.
  19540. *
  19541. * @param {Line3} line - The line to compute the intersection for.
  19542. * @param {Vector3} target - The target vector that is used to store the method's result.
  19543. * @return {?Vector3} The intersection point.
  19544. */
  19545. intersectLine( line, target ) {
  19546. const direction = line.delta( _vector1 );
  19547. const denominator = this.normal.dot( direction );
  19548. if ( denominator === 0 ) {
  19549. // line is coplanar, return origin
  19550. if ( this.distanceToPoint( line.start ) === 0 ) {
  19551. return target.copy( line.start );
  19552. }
  19553. // Unsure if this is the correct method to handle this case.
  19554. return null;
  19555. }
  19556. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19557. if ( t < 0 || t > 1 ) {
  19558. return null;
  19559. }
  19560. return target.copy( line.start ).addScaledVector( direction, t );
  19561. }
  19562. /**
  19563. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19564. *
  19565. * @param {Line3} line - The line to test.
  19566. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19567. */
  19568. intersectsLine( line ) {
  19569. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19570. const startSign = this.distanceToPoint( line.start );
  19571. const endSign = this.distanceToPoint( line.end );
  19572. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19573. }
  19574. /**
  19575. * Returns `true` if the given bounding box intersects with the plane.
  19576. *
  19577. * @param {Box3} box - The bounding box to test.
  19578. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19579. */
  19580. intersectsBox( box ) {
  19581. return box.intersectsPlane( this );
  19582. }
  19583. /**
  19584. * Returns `true` if the given bounding sphere intersects with the plane.
  19585. *
  19586. * @param {Sphere} sphere - The bounding sphere to test.
  19587. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19588. */
  19589. intersectsSphere( sphere ) {
  19590. return sphere.intersectsPlane( this );
  19591. }
  19592. /**
  19593. * Returns a coplanar vector to the plane, by calculating the
  19594. * projection of the normal at the origin onto the plane.
  19595. *
  19596. * @param {Vector3} target - The target vector that is used to store the method's result.
  19597. * @return {Vector3} The coplanar point.
  19598. */
  19599. coplanarPoint( target ) {
  19600. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19601. }
  19602. /**
  19603. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19604. *
  19605. * The optional normal matrix can be pre-computed like so:
  19606. * ```js
  19607. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19608. * ```
  19609. *
  19610. * @param {Matrix4} matrix - The transformation matrix.
  19611. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19612. * @return {Plane} A reference to this plane.
  19613. */
  19614. applyMatrix4( matrix, optionalNormalMatrix ) {
  19615. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19616. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19617. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19618. this.constant = - referencePoint.dot( normal );
  19619. return this;
  19620. }
  19621. /**
  19622. * Translates the plane by the distance defined by the given offset vector.
  19623. * Note that this only affects the plane constant and will not affect the normal vector.
  19624. *
  19625. * @param {Vector3} offset - The offset vector.
  19626. * @return {Plane} A reference to this plane.
  19627. */
  19628. translate( offset ) {
  19629. this.constant -= offset.dot( this.normal );
  19630. return this;
  19631. }
  19632. /**
  19633. * Returns `true` if this plane is equal with the given one.
  19634. *
  19635. * @param {Plane} plane - The plane to test for equality.
  19636. * @return {boolean} Whether this plane is equal with the given one.
  19637. */
  19638. equals( plane ) {
  19639. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19640. }
  19641. /**
  19642. * Returns a new plane with copied values from this instance.
  19643. *
  19644. * @return {Plane} A clone of this instance.
  19645. */
  19646. clone() {
  19647. return new this.constructor().copy( this );
  19648. }
  19649. }
  19650. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19651. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19652. const _vector$6 = /*@__PURE__*/ new Vector3();
  19653. /**
  19654. * Frustums are used to determine what is inside the camera's field of view.
  19655. * They help speed up the rendering process - objects which lie outside a camera's
  19656. * frustum can safely be excluded from rendering.
  19657. *
  19658. * This class is mainly intended for use internally by a renderer.
  19659. */
  19660. class Frustum {
  19661. /**
  19662. * Constructs a new frustum.
  19663. *
  19664. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19665. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19666. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19667. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19668. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19669. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19670. */
  19671. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19672. /**
  19673. * This array holds the planes that enclose the frustum.
  19674. *
  19675. * @type {Array<Plane>}
  19676. */
  19677. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19678. }
  19679. /**
  19680. * Sets the frustum planes by copying the given planes.
  19681. *
  19682. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19683. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19684. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19685. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19686. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19687. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19688. * @return {Frustum} A reference to this frustum.
  19689. */
  19690. set( p0, p1, p2, p3, p4, p5 ) {
  19691. const planes = this.planes;
  19692. planes[ 0 ].copy( p0 );
  19693. planes[ 1 ].copy( p1 );
  19694. planes[ 2 ].copy( p2 );
  19695. planes[ 3 ].copy( p3 );
  19696. planes[ 4 ].copy( p4 );
  19697. planes[ 5 ].copy( p5 );
  19698. return this;
  19699. }
  19700. /**
  19701. * Copies the values of the given frustum to this instance.
  19702. *
  19703. * @param {Frustum} frustum - The frustum to copy.
  19704. * @return {Frustum} A reference to this frustum.
  19705. */
  19706. copy( frustum ) {
  19707. const planes = this.planes;
  19708. for ( let i = 0; i < 6; i ++ ) {
  19709. planes[ i ].copy( frustum.planes[ i ] );
  19710. }
  19711. return this;
  19712. }
  19713. /**
  19714. * Sets the frustum planes from the given projection matrix.
  19715. *
  19716. * @param {Matrix4} m - The projection matrix.
  19717. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19718. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19719. * @return {Frustum} A reference to this frustum.
  19720. */
  19721. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19722. const planes = this.planes;
  19723. const me = m.elements;
  19724. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19725. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19726. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19727. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19728. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19729. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19730. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19731. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19732. if ( reversedDepth ) {
  19733. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19734. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19735. } else {
  19736. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19737. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19738. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19739. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19740. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19741. } else {
  19742. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19743. }
  19744. }
  19745. return this;
  19746. }
  19747. /**
  19748. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19749. *
  19750. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19751. *
  19752. * @param {Object3D} object - The 3D object to test.
  19753. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19754. */
  19755. intersectsObject( object ) {
  19756. if ( object.boundingSphere !== undefined ) {
  19757. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19758. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19759. } else {
  19760. const geometry = object.geometry;
  19761. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19762. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19763. }
  19764. return this.intersectsSphere( _sphere$3 );
  19765. }
  19766. /**
  19767. * Returns `true` if the given sprite is intersecting this frustum.
  19768. *
  19769. * @param {Sprite} sprite - The sprite to test.
  19770. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19771. */
  19772. intersectsSprite( sprite ) {
  19773. _sphere$3.center.set( 0, 0, 0 );
  19774. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19775. _sphere$3.radius = 0.7071067811865476 + offset;
  19776. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19777. return this.intersectsSphere( _sphere$3 );
  19778. }
  19779. /**
  19780. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19781. *
  19782. * @param {Sphere} sphere - The bounding sphere to test.
  19783. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19784. */
  19785. intersectsSphere( sphere ) {
  19786. const planes = this.planes;
  19787. const center = sphere.center;
  19788. const negRadius = - sphere.radius;
  19789. for ( let i = 0; i < 6; i ++ ) {
  19790. const distance = planes[ i ].distanceToPoint( center );
  19791. if ( distance < negRadius ) {
  19792. return false;
  19793. }
  19794. }
  19795. return true;
  19796. }
  19797. /**
  19798. * Returns `true` if the given bounding box is intersecting this frustum.
  19799. *
  19800. * @param {Box3} box - The bounding box to test.
  19801. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19802. */
  19803. intersectsBox( box ) {
  19804. const planes = this.planes;
  19805. for ( let i = 0; i < 6; i ++ ) {
  19806. const plane = planes[ i ];
  19807. // corner at max distance
  19808. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19809. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19810. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19811. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19812. return false;
  19813. }
  19814. }
  19815. return true;
  19816. }
  19817. /**
  19818. * Returns `true` if the given point lies within the frustum.
  19819. *
  19820. * @param {Vector3} point - The point to test.
  19821. * @return {boolean} Whether the point lies within this frustum or not.
  19822. */
  19823. containsPoint( point ) {
  19824. const planes = this.planes;
  19825. for ( let i = 0; i < 6; i ++ ) {
  19826. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19827. return false;
  19828. }
  19829. }
  19830. return true;
  19831. }
  19832. /**
  19833. * Returns a new frustum with copied values from this instance.
  19834. *
  19835. * @return {Frustum} A clone of this instance.
  19836. */
  19837. clone() {
  19838. return new this.constructor().copy( this );
  19839. }
  19840. }
  19841. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19842. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19843. /**
  19844. * FrustumArray is used to determine if an object is visible in at least one camera
  19845. * from an array of cameras. This is particularly useful for multi-view renderers.
  19846. */
  19847. class FrustumArray {
  19848. /**
  19849. * Constructs a new frustum array.
  19850. *
  19851. */
  19852. constructor() {
  19853. /**
  19854. * The coordinate system to use.
  19855. *
  19856. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19857. * @default WebGLCoordinateSystem
  19858. */
  19859. this.coordinateSystem = WebGLCoordinateSystem;
  19860. }
  19861. /**
  19862. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19863. * from the camera array.
  19864. *
  19865. * @param {Object3D} object - The 3D object to test.
  19866. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19867. * @return {boolean} Whether the 3D object is visible in any camera.
  19868. */
  19869. intersectsObject( object, cameraArray ) {
  19870. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19871. return false;
  19872. }
  19873. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19874. const camera = cameraArray.cameras[ i ];
  19875. _projScreenMatrix$2.multiplyMatrices(
  19876. camera.projectionMatrix,
  19877. camera.matrixWorldInverse
  19878. );
  19879. _frustum$1.setFromProjectionMatrix(
  19880. _projScreenMatrix$2,
  19881. camera.coordinateSystem,
  19882. camera.reversedDepth
  19883. );
  19884. if ( _frustum$1.intersectsObject( object ) ) {
  19885. return true; // Object is visible in at least one camera
  19886. }
  19887. }
  19888. return false; // Not visible in any camera
  19889. }
  19890. /**
  19891. * Returns `true` if the given sprite is intersecting any frustum
  19892. * from the camera array.
  19893. *
  19894. * @param {Sprite} sprite - The sprite to test.
  19895. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19896. * @return {boolean} Whether the sprite is visible in any camera.
  19897. */
  19898. intersectsSprite( sprite, cameraArray ) {
  19899. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19900. return false;
  19901. }
  19902. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19903. const camera = cameraArray.cameras[ i ];
  19904. _projScreenMatrix$2.multiplyMatrices(
  19905. camera.projectionMatrix,
  19906. camera.matrixWorldInverse
  19907. );
  19908. _frustum$1.setFromProjectionMatrix(
  19909. _projScreenMatrix$2,
  19910. camera.coordinateSystem,
  19911. camera.reversedDepth
  19912. );
  19913. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19914. return true; // Sprite is visible in at least one camera
  19915. }
  19916. }
  19917. return false; // Not visible in any camera
  19918. }
  19919. /**
  19920. * Returns `true` if the given bounding sphere is intersecting any frustum
  19921. * from the camera array.
  19922. *
  19923. * @param {Sphere} sphere - The bounding sphere to test.
  19924. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19925. * @return {boolean} Whether the sphere is visible in any camera.
  19926. */
  19927. intersectsSphere( sphere, cameraArray ) {
  19928. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19929. return false;
  19930. }
  19931. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19932. const camera = cameraArray.cameras[ i ];
  19933. _projScreenMatrix$2.multiplyMatrices(
  19934. camera.projectionMatrix,
  19935. camera.matrixWorldInverse
  19936. );
  19937. _frustum$1.setFromProjectionMatrix(
  19938. _projScreenMatrix$2,
  19939. camera.coordinateSystem,
  19940. camera.reversedDepth
  19941. );
  19942. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19943. return true; // Sphere is visible in at least one camera
  19944. }
  19945. }
  19946. return false; // Not visible in any camera
  19947. }
  19948. /**
  19949. * Returns `true` if the given bounding box is intersecting any frustum
  19950. * from the camera array.
  19951. *
  19952. * @param {Box3} box - The bounding box to test.
  19953. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19954. * @return {boolean} Whether the box is visible in any camera.
  19955. */
  19956. intersectsBox( box, cameraArray ) {
  19957. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19958. return false;
  19959. }
  19960. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19961. const camera = cameraArray.cameras[ i ];
  19962. _projScreenMatrix$2.multiplyMatrices(
  19963. camera.projectionMatrix,
  19964. camera.matrixWorldInverse
  19965. );
  19966. _frustum$1.setFromProjectionMatrix(
  19967. _projScreenMatrix$2,
  19968. camera.coordinateSystem,
  19969. camera.reversedDepth
  19970. );
  19971. if ( _frustum$1.intersectsBox( box ) ) {
  19972. return true; // Box is visible in at least one camera
  19973. }
  19974. }
  19975. return false; // Not visible in any camera
  19976. }
  19977. /**
  19978. * Returns `true` if the given point lies within any frustum
  19979. * from the camera array.
  19980. *
  19981. * @param {Vector3} point - The point to test.
  19982. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19983. * @return {boolean} Whether the point is visible in any camera.
  19984. */
  19985. containsPoint( point, cameraArray ) {
  19986. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19987. return false;
  19988. }
  19989. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19990. const camera = cameraArray.cameras[ i ];
  19991. _projScreenMatrix$2.multiplyMatrices(
  19992. camera.projectionMatrix,
  19993. camera.matrixWorldInverse
  19994. );
  19995. _frustum$1.setFromProjectionMatrix(
  19996. _projScreenMatrix$2,
  19997. camera.coordinateSystem,
  19998. camera.reversedDepth
  19999. );
  20000. if ( _frustum$1.containsPoint( point ) ) {
  20001. return true; // Point is visible in at least one camera
  20002. }
  20003. }
  20004. return false; // Not visible in any camera
  20005. }
  20006. /**
  20007. * Returns a new frustum array with copied values from this instance.
  20008. *
  20009. * @return {FrustumArray} A clone of this instance.
  20010. */
  20011. clone() {
  20012. return new FrustumArray();
  20013. }
  20014. }
  20015. function ascIdSort( a, b ) {
  20016. return a - b;
  20017. }
  20018. function sortOpaque( a, b ) {
  20019. return a.z - b.z;
  20020. }
  20021. function sortTransparent( a, b ) {
  20022. return b.z - a.z;
  20023. }
  20024. class MultiDrawRenderList {
  20025. constructor() {
  20026. this.index = 0;
  20027. this.pool = [];
  20028. this.list = [];
  20029. }
  20030. push( start, count, z, index ) {
  20031. const pool = this.pool;
  20032. const list = this.list;
  20033. if ( this.index >= pool.length ) {
  20034. pool.push( {
  20035. start: -1,
  20036. count: -1,
  20037. z: -1,
  20038. index: -1,
  20039. } );
  20040. }
  20041. const item = pool[ this.index ];
  20042. list.push( item );
  20043. this.index ++;
  20044. item.start = start;
  20045. item.count = count;
  20046. item.z = z;
  20047. item.index = index;
  20048. }
  20049. reset() {
  20050. this.list.length = 0;
  20051. this.index = 0;
  20052. }
  20053. }
  20054. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20055. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20056. const _frustum = /*@__PURE__*/ new Frustum();
  20057. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20058. const _box$1 = /*@__PURE__*/ new Box3();
  20059. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20060. const _vector$5 = /*@__PURE__*/ new Vector3();
  20061. const _forward$1 = /*@__PURE__*/ new Vector3();
  20062. const _temp = /*@__PURE__*/ new Vector3();
  20063. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20064. const _mesh = /*@__PURE__*/ new Mesh();
  20065. const _batchIntersects = [];
  20066. // copies data from attribute "src" into "target" starting at "targetOffset"
  20067. function copyAttributeData( src, target, targetOffset = 0 ) {
  20068. const itemSize = target.itemSize;
  20069. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20070. // use the component getters and setters if the array data cannot
  20071. // be copied directly
  20072. const vertexCount = src.count;
  20073. for ( let i = 0; i < vertexCount; i ++ ) {
  20074. for ( let c = 0; c < itemSize; c ++ ) {
  20075. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20076. }
  20077. }
  20078. } else {
  20079. // faster copy approach using typed array set function
  20080. target.array.set( src.array, targetOffset * itemSize );
  20081. }
  20082. target.needsUpdate = true;
  20083. }
  20084. // safely copies array contents to a potentially smaller array
  20085. function copyArrayContents( src, target ) {
  20086. if ( src.constructor !== target.constructor ) {
  20087. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20088. const len = Math.min( src.length, target.length );
  20089. for ( let i = 0; i < len; i ++ ) {
  20090. target[ i ] = src[ i ];
  20091. }
  20092. } else {
  20093. // if the arrays use the same data layout we can use a fast block copy
  20094. const len = Math.min( src.length, target.length );
  20095. target.set( new src.constructor( src.buffer, 0, len ) );
  20096. }
  20097. }
  20098. /**
  20099. * A special version of a mesh with multi draw batch rendering support. Use
  20100. * this class if you have to render a large number of objects with the same
  20101. * material but with different geometries or world transformations. The usage of
  20102. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20103. * rendering performance in your application.
  20104. *
  20105. * ```js
  20106. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20107. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20108. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20109. *
  20110. * // initialize and add geometries into the batched mesh
  20111. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20112. * const boxGeometryId = batchedMesh.addGeometry( box );
  20113. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20114. *
  20115. * // create instances of those geometries
  20116. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20117. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20118. *
  20119. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20120. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20121. *
  20122. * // position the geometries
  20123. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20124. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20125. *
  20126. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20127. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20128. *
  20129. * scene.add( batchedMesh );
  20130. * ```
  20131. *
  20132. * @augments Mesh
  20133. */
  20134. class BatchedMesh extends Mesh {
  20135. /**
  20136. * Constructs a new batched mesh.
  20137. *
  20138. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20139. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20140. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20141. * @param {Material|Array<Material>} [material] - The mesh material.
  20142. */
  20143. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20144. super( new BufferGeometry(), material );
  20145. /**
  20146. * This flag can be used for type testing.
  20147. *
  20148. * @type {boolean}
  20149. * @readonly
  20150. * @default true
  20151. */
  20152. this.isBatchedMesh = true;
  20153. /**
  20154. * When set ot `true`, the individual objects of a batch are frustum culled.
  20155. *
  20156. * @type {boolean}
  20157. * @default true
  20158. */
  20159. this.perObjectFrustumCulled = true;
  20160. /**
  20161. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20162. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20163. * rendered front to back.
  20164. *
  20165. * @type {boolean}
  20166. * @default true
  20167. */
  20168. this.sortObjects = true;
  20169. /**
  20170. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20171. *
  20172. * @type {?Box3}
  20173. * @default null
  20174. */
  20175. this.boundingBox = null;
  20176. /**
  20177. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20178. *
  20179. * @type {?Sphere}
  20180. * @default null
  20181. */
  20182. this.boundingSphere = null;
  20183. /**
  20184. * Takes a sort a function that is run before render. The function takes a list of instances to
  20185. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20186. * sort with.
  20187. *
  20188. * @type {?Function}
  20189. * @default null
  20190. */
  20191. this.customSort = null;
  20192. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20193. this._instanceInfo = [];
  20194. this._geometryInfo = [];
  20195. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20196. this._availableInstanceIds = [];
  20197. this._availableGeometryIds = [];
  20198. // used to track where the next point is that geometry should be inserted
  20199. this._nextIndexStart = 0;
  20200. this._nextVertexStart = 0;
  20201. this._geometryCount = 0;
  20202. // flags
  20203. this._visibilityChanged = true;
  20204. this._geometryInitialized = false;
  20205. // cached user options
  20206. this._maxInstanceCount = maxInstanceCount;
  20207. this._maxVertexCount = maxVertexCount;
  20208. this._maxIndexCount = maxIndexCount;
  20209. // buffers for multi draw
  20210. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20211. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20212. this._multiDrawCount = 0;
  20213. this._multiDrawInstances = null;
  20214. // Local matrix per geometry by using data texture
  20215. this._matricesTexture = null;
  20216. this._indirectTexture = null;
  20217. this._colorsTexture = null;
  20218. this._initMatricesTexture();
  20219. this._initIndirectTexture();
  20220. }
  20221. /**
  20222. * The maximum number of individual instances that can be stored in the batch.
  20223. *
  20224. * @type {number}
  20225. * @readonly
  20226. */
  20227. get maxInstanceCount() {
  20228. return this._maxInstanceCount;
  20229. }
  20230. /**
  20231. * The instance count.
  20232. *
  20233. * @type {number}
  20234. * @readonly
  20235. */
  20236. get instanceCount() {
  20237. return this._instanceInfo.length - this._availableInstanceIds.length;
  20238. }
  20239. /**
  20240. * The number of unused vertices.
  20241. *
  20242. * @type {number}
  20243. * @readonly
  20244. */
  20245. get unusedVertexCount() {
  20246. return this._maxVertexCount - this._nextVertexStart;
  20247. }
  20248. /**
  20249. * The number of unused indices.
  20250. *
  20251. * @type {number}
  20252. * @readonly
  20253. */
  20254. get unusedIndexCount() {
  20255. return this._maxIndexCount - this._nextIndexStart;
  20256. }
  20257. _initMatricesTexture() {
  20258. // layout (1 matrix = 4 pixels)
  20259. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20260. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20261. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20262. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20263. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20264. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20265. size = Math.ceil( size / 4 ) * 4;
  20266. size = Math.max( size, 4 );
  20267. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20268. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20269. this._matricesTexture = matricesTexture;
  20270. }
  20271. _initIndirectTexture() {
  20272. let size = Math.sqrt( this._maxInstanceCount );
  20273. size = Math.ceil( size );
  20274. const indirectArray = new Uint32Array( size * size );
  20275. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20276. this._indirectTexture = indirectTexture;
  20277. }
  20278. _initColorsTexture() {
  20279. let size = Math.sqrt( this._maxInstanceCount );
  20280. size = Math.ceil( size );
  20281. // 4 floats per RGBA pixel initialized to white
  20282. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20283. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20284. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20285. this._colorsTexture = colorsTexture;
  20286. }
  20287. _initializeGeometry( reference ) {
  20288. const geometry = this.geometry;
  20289. const maxVertexCount = this._maxVertexCount;
  20290. const maxIndexCount = this._maxIndexCount;
  20291. if ( this._geometryInitialized === false ) {
  20292. for ( const attributeName in reference.attributes ) {
  20293. const srcAttribute = reference.getAttribute( attributeName );
  20294. const { array, itemSize, normalized } = srcAttribute;
  20295. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20296. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20297. geometry.setAttribute( attributeName, dstAttribute );
  20298. }
  20299. if ( reference.getIndex() !== null ) {
  20300. // Reserve last u16 index for primitive restart.
  20301. const indexArray = maxVertexCount > 65535
  20302. ? new Uint32Array( maxIndexCount )
  20303. : new Uint16Array( maxIndexCount );
  20304. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20305. }
  20306. this._geometryInitialized = true;
  20307. }
  20308. }
  20309. // Make sure the geometry is compatible with the existing combined geometry attributes
  20310. _validateGeometry( geometry ) {
  20311. // check to ensure the geometries are using consistent attributes and indices
  20312. const batchGeometry = this.geometry;
  20313. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20314. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20315. }
  20316. for ( const attributeName in batchGeometry.attributes ) {
  20317. if ( ! geometry.hasAttribute( attributeName ) ) {
  20318. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20319. }
  20320. const srcAttribute = geometry.getAttribute( attributeName );
  20321. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20322. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20323. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20324. }
  20325. }
  20326. }
  20327. /**
  20328. * Validates the instance defined by the given ID.
  20329. *
  20330. * @param {number} instanceId - The instance to validate.
  20331. */
  20332. validateInstanceId( instanceId ) {
  20333. const instanceInfo = this._instanceInfo;
  20334. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20335. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20336. }
  20337. }
  20338. /**
  20339. * Validates the geometry defined by the given ID.
  20340. *
  20341. * @param {number} geometryId - The geometry to validate.
  20342. */
  20343. validateGeometryId( geometryId ) {
  20344. const geometryInfoList = this._geometryInfo;
  20345. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20346. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20347. }
  20348. }
  20349. /**
  20350. * Takes a sort a function that is run before render. The function takes a list of instances to
  20351. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20352. *
  20353. * @param {Function} func - The custom sort function.
  20354. * @return {BatchedMesh} A reference to this batched mesh.
  20355. */
  20356. setCustomSort( func ) {
  20357. this.customSort = func;
  20358. return this;
  20359. }
  20360. /**
  20361. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20362. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20363. * otherwise they are `null`.
  20364. */
  20365. computeBoundingBox() {
  20366. if ( this.boundingBox === null ) {
  20367. this.boundingBox = new Box3();
  20368. }
  20369. const boundingBox = this.boundingBox;
  20370. const instanceInfo = this._instanceInfo;
  20371. boundingBox.makeEmpty();
  20372. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20373. if ( instanceInfo[ i ].active === false ) continue;
  20374. const geometryId = instanceInfo[ i ].geometryIndex;
  20375. this.getMatrixAt( i, _matrix$1 );
  20376. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20377. boundingBox.union( _box$1 );
  20378. }
  20379. }
  20380. /**
  20381. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20382. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20383. * otherwise they are `null`.
  20384. */
  20385. computeBoundingSphere() {
  20386. if ( this.boundingSphere === null ) {
  20387. this.boundingSphere = new Sphere();
  20388. }
  20389. const boundingSphere = this.boundingSphere;
  20390. const instanceInfo = this._instanceInfo;
  20391. boundingSphere.makeEmpty();
  20392. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20393. if ( instanceInfo[ i ].active === false ) continue;
  20394. const geometryId = instanceInfo[ i ].geometryIndex;
  20395. this.getMatrixAt( i, _matrix$1 );
  20396. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20397. boundingSphere.union( _sphere$2 );
  20398. }
  20399. }
  20400. /**
  20401. * Adds a new instance to the batch using the geometry of the given ID and returns
  20402. * a new id referring to the new instance to be used by other functions.
  20403. *
  20404. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20405. * @return {number} The instance ID.
  20406. */
  20407. addInstance( geometryId ) {
  20408. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20409. // ensure we're not over geometry
  20410. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20411. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20412. }
  20413. const instanceInfo = {
  20414. visible: true,
  20415. active: true,
  20416. geometryIndex: geometryId,
  20417. };
  20418. let drawId = null;
  20419. // Prioritize using previously freed instance ids
  20420. if ( this._availableInstanceIds.length > 0 ) {
  20421. this._availableInstanceIds.sort( ascIdSort );
  20422. drawId = this._availableInstanceIds.shift();
  20423. this._instanceInfo[ drawId ] = instanceInfo;
  20424. } else {
  20425. drawId = this._instanceInfo.length;
  20426. this._instanceInfo.push( instanceInfo );
  20427. }
  20428. const matricesTexture = this._matricesTexture;
  20429. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20430. matricesTexture.needsUpdate = true;
  20431. const colorsTexture = this._colorsTexture;
  20432. if ( colorsTexture ) {
  20433. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20434. colorsTexture.needsUpdate = true;
  20435. }
  20436. this._visibilityChanged = true;
  20437. return drawId;
  20438. }
  20439. /**
  20440. * Adds the given geometry to the batch and returns the associated
  20441. * geometry id referring to it to be used in other functions.
  20442. *
  20443. * @param {BufferGeometry} geometry - The geometry to add.
  20444. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20445. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20446. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20447. * Defaults to the length of the given geometry vertex buffer.
  20448. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20449. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20450. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20451. * the length of the given geometry index buffer.
  20452. * @return {number} The geometry ID.
  20453. */
  20454. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20455. this._initializeGeometry( geometry );
  20456. this._validateGeometry( geometry );
  20457. const geometryInfo = {
  20458. // geometry information
  20459. vertexStart: -1,
  20460. vertexCount: -1,
  20461. reservedVertexCount: -1,
  20462. indexStart: -1,
  20463. indexCount: -1,
  20464. reservedIndexCount: -1,
  20465. // draw range information
  20466. start: -1,
  20467. count: -1,
  20468. // state
  20469. boundingBox: null,
  20470. boundingSphere: null,
  20471. active: true,
  20472. };
  20473. const geometryInfoList = this._geometryInfo;
  20474. geometryInfo.vertexStart = this._nextVertexStart;
  20475. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20476. const index = geometry.getIndex();
  20477. const hasIndex = index !== null;
  20478. if ( hasIndex ) {
  20479. geometryInfo.indexStart = this._nextIndexStart;
  20480. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20481. }
  20482. if (
  20483. geometryInfo.indexStart !== -1 &&
  20484. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20485. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20486. ) {
  20487. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20488. }
  20489. // update id
  20490. let geometryId;
  20491. if ( this._availableGeometryIds.length > 0 ) {
  20492. this._availableGeometryIds.sort( ascIdSort );
  20493. geometryId = this._availableGeometryIds.shift();
  20494. geometryInfoList[ geometryId ] = geometryInfo;
  20495. } else {
  20496. geometryId = this._geometryCount;
  20497. this._geometryCount ++;
  20498. geometryInfoList.push( geometryInfo );
  20499. }
  20500. // update the geometry
  20501. this.setGeometryAt( geometryId, geometry );
  20502. // increment the next geometry position
  20503. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20504. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20505. return geometryId;
  20506. }
  20507. /**
  20508. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20509. * is not enough space reserved for geometry. Calling this will change all instances that are
  20510. * rendering that geometry.
  20511. *
  20512. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20513. * @param {BufferGeometry} geometry - The new geometry.
  20514. * @return {number} The geometry ID.
  20515. */
  20516. setGeometryAt( geometryId, geometry ) {
  20517. if ( geometryId >= this._geometryCount ) {
  20518. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20519. }
  20520. this._validateGeometry( geometry );
  20521. const batchGeometry = this.geometry;
  20522. const hasIndex = batchGeometry.getIndex() !== null;
  20523. const dstIndex = batchGeometry.getIndex();
  20524. const srcIndex = geometry.getIndex();
  20525. const geometryInfo = this._geometryInfo[ geometryId ];
  20526. if (
  20527. hasIndex &&
  20528. srcIndex.count > geometryInfo.reservedIndexCount ||
  20529. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20530. ) {
  20531. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20532. }
  20533. // copy geometry buffer data over
  20534. const vertexStart = geometryInfo.vertexStart;
  20535. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20536. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20537. for ( const attributeName in batchGeometry.attributes ) {
  20538. // copy attribute data
  20539. const srcAttribute = geometry.getAttribute( attributeName );
  20540. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20541. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20542. // fill the rest in with zeroes
  20543. const itemSize = srcAttribute.itemSize;
  20544. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20545. const index = vertexStart + i;
  20546. for ( let c = 0; c < itemSize; c ++ ) {
  20547. dstAttribute.setComponent( index, c, 0 );
  20548. }
  20549. }
  20550. dstAttribute.needsUpdate = true;
  20551. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20552. }
  20553. // copy index
  20554. if ( hasIndex ) {
  20555. const indexStart = geometryInfo.indexStart;
  20556. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20557. geometryInfo.indexCount = geometry.getIndex().count;
  20558. // copy index data over
  20559. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20560. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20561. }
  20562. // fill the rest in with zeroes
  20563. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20564. dstIndex.setX( indexStart + i, vertexStart );
  20565. }
  20566. dstIndex.needsUpdate = true;
  20567. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20568. }
  20569. // update the draw range
  20570. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20571. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20572. // store the bounding boxes
  20573. geometryInfo.boundingBox = null;
  20574. if ( geometry.boundingBox !== null ) {
  20575. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20576. }
  20577. geometryInfo.boundingSphere = null;
  20578. if ( geometry.boundingSphere !== null ) {
  20579. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20580. }
  20581. this._visibilityChanged = true;
  20582. return geometryId;
  20583. }
  20584. /**
  20585. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20586. * this geometry will also be removed as a side effect.
  20587. *
  20588. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20589. * @return {BatchedMesh} A reference to this batched mesh.
  20590. */
  20591. deleteGeometry( geometryId ) {
  20592. const geometryInfoList = this._geometryInfo;
  20593. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20594. return this;
  20595. }
  20596. // delete any instances associated with this geometry
  20597. const instanceInfo = this._instanceInfo;
  20598. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20599. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20600. this.deleteInstance( i );
  20601. }
  20602. }
  20603. geometryInfoList[ geometryId ].active = false;
  20604. this._availableGeometryIds.push( geometryId );
  20605. this._visibilityChanged = true;
  20606. return this;
  20607. }
  20608. /**
  20609. * Deletes an existing instance from the batch using the given ID.
  20610. *
  20611. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20612. * @return {BatchedMesh} A reference to this batched mesh.
  20613. */
  20614. deleteInstance( instanceId ) {
  20615. this.validateInstanceId( instanceId );
  20616. this._instanceInfo[ instanceId ].active = false;
  20617. this._availableInstanceIds.push( instanceId );
  20618. this._visibilityChanged = true;
  20619. return this;
  20620. }
  20621. /**
  20622. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20623. * previously deleted geometry, freeing up space to add new geometry.
  20624. *
  20625. * @return {BatchedMesh} A reference to this batched mesh.
  20626. */
  20627. optimize() {
  20628. // track the next indices to copy data to
  20629. let nextVertexStart = 0;
  20630. let nextIndexStart = 0;
  20631. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20632. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20633. const geometryInfoList = this._geometryInfo;
  20634. const indices = geometryInfoList
  20635. .map( ( e, i ) => i )
  20636. .sort( ( a, b ) => {
  20637. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20638. } );
  20639. const geometry = this.geometry;
  20640. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20641. // if a geometry range is inactive then don't copy anything
  20642. const index = indices[ i ];
  20643. const geometryInfo = geometryInfoList[ index ];
  20644. if ( geometryInfo.active === false ) {
  20645. continue;
  20646. }
  20647. // if a geometry contains an index buffer then shift it, as well
  20648. if ( geometry.index !== null ) {
  20649. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20650. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20651. const index = geometry.index;
  20652. const array = index.array;
  20653. // shift the index pointers based on how the vertex data will shift
  20654. // adjusting the index must happen first so the original vertex start value is available
  20655. const elementDelta = nextVertexStart - vertexStart;
  20656. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20657. array[ j ] = array[ j ] + elementDelta;
  20658. }
  20659. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20660. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20661. index.needsUpdate = true;
  20662. geometryInfo.indexStart = nextIndexStart;
  20663. }
  20664. nextIndexStart += geometryInfo.reservedIndexCount;
  20665. }
  20666. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20667. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20668. const { vertexStart, reservedVertexCount } = geometryInfo;
  20669. const attributes = geometry.attributes;
  20670. for ( const key in attributes ) {
  20671. const attribute = attributes[ key ];
  20672. const { array, itemSize } = attribute;
  20673. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20674. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20675. attribute.needsUpdate = true;
  20676. }
  20677. geometryInfo.vertexStart = nextVertexStart;
  20678. }
  20679. nextVertexStart += geometryInfo.reservedVertexCount;
  20680. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20681. // step the next geometry points to the shifted position
  20682. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20683. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20684. }
  20685. this._visibilityChanged = true;
  20686. return this;
  20687. }
  20688. /**
  20689. * Returns the bounding box for the given geometry.
  20690. *
  20691. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20692. * @param {Box3} target - The target object that is used to store the method's result.
  20693. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20694. */
  20695. getBoundingBoxAt( geometryId, target ) {
  20696. if ( geometryId >= this._geometryCount ) {
  20697. return null;
  20698. }
  20699. // compute bounding box
  20700. const geometry = this.geometry;
  20701. const geometryInfo = this._geometryInfo[ geometryId ];
  20702. if ( geometryInfo.boundingBox === null ) {
  20703. const box = new Box3();
  20704. const index = geometry.index;
  20705. const position = geometry.attributes.position;
  20706. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20707. let iv = i;
  20708. if ( index ) {
  20709. iv = index.getX( iv );
  20710. }
  20711. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20712. }
  20713. geometryInfo.boundingBox = box;
  20714. }
  20715. target.copy( geometryInfo.boundingBox );
  20716. return target;
  20717. }
  20718. /**
  20719. * Returns the bounding sphere for the given geometry.
  20720. *
  20721. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20722. * @param {Sphere} target - The target object that is used to store the method's result.
  20723. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20724. */
  20725. getBoundingSphereAt( geometryId, target ) {
  20726. if ( geometryId >= this._geometryCount ) {
  20727. return null;
  20728. }
  20729. // compute bounding sphere
  20730. const geometry = this.geometry;
  20731. const geometryInfo = this._geometryInfo[ geometryId ];
  20732. if ( geometryInfo.boundingSphere === null ) {
  20733. const sphere = new Sphere();
  20734. this.getBoundingBoxAt( geometryId, _box$1 );
  20735. _box$1.getCenter( sphere.center );
  20736. const index = geometry.index;
  20737. const position = geometry.attributes.position;
  20738. let maxRadiusSq = 0;
  20739. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20740. let iv = i;
  20741. if ( index ) {
  20742. iv = index.getX( iv );
  20743. }
  20744. _vector$5.fromBufferAttribute( position, iv );
  20745. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20746. }
  20747. sphere.radius = Math.sqrt( maxRadiusSq );
  20748. geometryInfo.boundingSphere = sphere;
  20749. }
  20750. target.copy( geometryInfo.boundingSphere );
  20751. return target;
  20752. }
  20753. /**
  20754. * Sets the given local transformation matrix to the defined instance.
  20755. * Negatively scaled matrices are not supported.
  20756. *
  20757. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20758. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20759. * @return {BatchedMesh} A reference to this batched mesh.
  20760. */
  20761. setMatrixAt( instanceId, matrix ) {
  20762. this.validateInstanceId( instanceId );
  20763. const matricesTexture = this._matricesTexture;
  20764. const matricesArray = this._matricesTexture.image.data;
  20765. matrix.toArray( matricesArray, instanceId * 16 );
  20766. matricesTexture.needsUpdate = true;
  20767. return this;
  20768. }
  20769. /**
  20770. * Returns the local transformation matrix of the defined instance.
  20771. *
  20772. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20773. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20774. * @return {Matrix4} The instance's local transformation matrix.
  20775. */
  20776. getMatrixAt( instanceId, matrix ) {
  20777. this.validateInstanceId( instanceId );
  20778. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20779. }
  20780. /**
  20781. * Sets the given color to the defined instance.
  20782. *
  20783. * @param {number} instanceId - The ID of an instance to set the color of.
  20784. * @param {Color} color - The color to set the instance to.
  20785. * @return {BatchedMesh} A reference to this batched mesh.
  20786. */
  20787. setColorAt( instanceId, color ) {
  20788. this.validateInstanceId( instanceId );
  20789. if ( this._colorsTexture === null ) {
  20790. this._initColorsTexture();
  20791. }
  20792. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20793. this._colorsTexture.needsUpdate = true;
  20794. return this;
  20795. }
  20796. /**
  20797. * Returns the color of the defined instance.
  20798. *
  20799. * @param {number} instanceId - The ID of an instance to get the color of.
  20800. * @param {Color} color - The target object that is used to store the method's result.
  20801. * @return {Color} The instance's color.
  20802. */
  20803. getColorAt( instanceId, color ) {
  20804. this.validateInstanceId( instanceId );
  20805. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20806. }
  20807. /**
  20808. * Sets the visibility of the instance.
  20809. *
  20810. * @param {number} instanceId - The id of the instance to set the visibility of.
  20811. * @param {boolean} visible - Whether the instance is visible or not.
  20812. * @return {BatchedMesh} A reference to this batched mesh.
  20813. */
  20814. setVisibleAt( instanceId, visible ) {
  20815. this.validateInstanceId( instanceId );
  20816. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20817. return this;
  20818. }
  20819. this._instanceInfo[ instanceId ].visible = visible;
  20820. this._visibilityChanged = true;
  20821. return this;
  20822. }
  20823. /**
  20824. * Returns the visibility state of the defined instance.
  20825. *
  20826. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20827. * @return {boolean} Whether the instance is visible or not.
  20828. */
  20829. getVisibleAt( instanceId ) {
  20830. this.validateInstanceId( instanceId );
  20831. return this._instanceInfo[ instanceId ].visible;
  20832. }
  20833. /**
  20834. * Sets the geometry ID of the instance at the given index.
  20835. *
  20836. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20837. * @param {number} geometryId - The geometry ID to be use by the instance.
  20838. * @return {BatchedMesh} A reference to this batched mesh.
  20839. */
  20840. setGeometryIdAt( instanceId, geometryId ) {
  20841. this.validateInstanceId( instanceId );
  20842. this.validateGeometryId( geometryId );
  20843. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20844. return this;
  20845. }
  20846. /**
  20847. * Returns the geometry ID of the defined instance.
  20848. *
  20849. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20850. * @return {number} The instance's geometry ID.
  20851. */
  20852. getGeometryIdAt( instanceId ) {
  20853. this.validateInstanceId( instanceId );
  20854. return this._instanceInfo[ instanceId ].geometryIndex;
  20855. }
  20856. /**
  20857. * Get the range representing the subset of triangles related to the attached geometry,
  20858. * indicating the starting offset and count, or `null` if invalid.
  20859. *
  20860. * @param {number} geometryId - The id of the geometry to get the range of.
  20861. * @param {Object} [target] - The target object that is used to store the method's result.
  20862. * @return {{
  20863. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20864. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20865. * start:number,count:number
  20866. * }} The result object with range data.
  20867. */
  20868. getGeometryRangeAt( geometryId, target = {} ) {
  20869. this.validateGeometryId( geometryId );
  20870. const geometryInfo = this._geometryInfo[ geometryId ];
  20871. target.vertexStart = geometryInfo.vertexStart;
  20872. target.vertexCount = geometryInfo.vertexCount;
  20873. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20874. target.indexStart = geometryInfo.indexStart;
  20875. target.indexCount = geometryInfo.indexCount;
  20876. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20877. target.start = geometryInfo.start;
  20878. target.count = geometryInfo.count;
  20879. return target;
  20880. }
  20881. /**
  20882. * Resizes the necessary buffers to support the provided number of instances.
  20883. * If the provided arguments shrink the number of instances but there are not enough
  20884. * unused Ids at the end of the list then an error is thrown.
  20885. *
  20886. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20887. */
  20888. setInstanceCount( maxInstanceCount ) {
  20889. // shrink the available instances as much as possible
  20890. const availableInstanceIds = this._availableInstanceIds;
  20891. const instanceInfo = this._instanceInfo;
  20892. availableInstanceIds.sort( ascIdSort );
  20893. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20894. instanceInfo.pop();
  20895. availableInstanceIds.pop();
  20896. }
  20897. // throw an error if it can't be shrunk to the desired size
  20898. if ( maxInstanceCount < instanceInfo.length ) {
  20899. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20900. }
  20901. // copy the multi draw counts
  20902. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20903. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20904. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20905. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20906. this._multiDrawCounts = multiDrawCounts;
  20907. this._multiDrawStarts = multiDrawStarts;
  20908. this._maxInstanceCount = maxInstanceCount;
  20909. // update texture data for instance sampling
  20910. const indirectTexture = this._indirectTexture;
  20911. const matricesTexture = this._matricesTexture;
  20912. const colorsTexture = this._colorsTexture;
  20913. indirectTexture.dispose();
  20914. this._initIndirectTexture();
  20915. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20916. matricesTexture.dispose();
  20917. this._initMatricesTexture();
  20918. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20919. if ( colorsTexture ) {
  20920. colorsTexture.dispose();
  20921. this._initColorsTexture();
  20922. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20923. }
  20924. }
  20925. /**
  20926. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20927. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20928. * end of the geometry attributes then an error is thrown.
  20929. *
  20930. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20931. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20932. */
  20933. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20934. // Check if we can shrink to the requested vertex attribute size
  20935. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20936. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20937. if ( requiredVertexLength > maxVertexCount ) {
  20938. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20939. }
  20940. // Check if we can shrink to the requested index attribute size
  20941. if ( this.geometry.index ) {
  20942. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20943. if ( requiredIndexLength > maxIndexCount ) {
  20944. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20945. }
  20946. }
  20947. //
  20948. // dispose of the previous geometry
  20949. const oldGeometry = this.geometry;
  20950. oldGeometry.dispose();
  20951. // recreate the geometry needed based on the previous variant
  20952. this._maxVertexCount = maxVertexCount;
  20953. this._maxIndexCount = maxIndexCount;
  20954. if ( this._geometryInitialized ) {
  20955. this._geometryInitialized = false;
  20956. this.geometry = new BufferGeometry();
  20957. this._initializeGeometry( oldGeometry );
  20958. }
  20959. // copy data from the previous geometry
  20960. const geometry = this.geometry;
  20961. if ( oldGeometry.index ) {
  20962. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20963. }
  20964. for ( const key in oldGeometry.attributes ) {
  20965. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20966. }
  20967. }
  20968. raycast( raycaster, intersects ) {
  20969. const instanceInfo = this._instanceInfo;
  20970. const geometryInfoList = this._geometryInfo;
  20971. const matrixWorld = this.matrixWorld;
  20972. const batchGeometry = this.geometry;
  20973. // iterate over each geometry
  20974. _mesh.material = this.material;
  20975. _mesh.geometry.index = batchGeometry.index;
  20976. _mesh.geometry.attributes = batchGeometry.attributes;
  20977. if ( _mesh.geometry.boundingBox === null ) {
  20978. _mesh.geometry.boundingBox = new Box3();
  20979. }
  20980. if ( _mesh.geometry.boundingSphere === null ) {
  20981. _mesh.geometry.boundingSphere = new Sphere();
  20982. }
  20983. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20984. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20985. continue;
  20986. }
  20987. const geometryId = instanceInfo[ i ].geometryIndex;
  20988. const geometryInfo = geometryInfoList[ geometryId ];
  20989. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20990. // get the intersects
  20991. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20992. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20993. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20994. _mesh.raycast( raycaster, _batchIntersects );
  20995. // add batch id to the intersects
  20996. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20997. const intersect = _batchIntersects[ j ];
  20998. intersect.object = this;
  20999. intersect.batchId = i;
  21000. intersects.push( intersect );
  21001. }
  21002. _batchIntersects.length = 0;
  21003. }
  21004. _mesh.material = null;
  21005. _mesh.geometry.index = null;
  21006. _mesh.geometry.attributes = {};
  21007. _mesh.geometry.setDrawRange( 0, Infinity );
  21008. }
  21009. copy( source ) {
  21010. super.copy( source );
  21011. this.geometry = source.geometry.clone();
  21012. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  21013. this.sortObjects = source.sortObjects;
  21014. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  21015. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  21016. this._geometryInfo = source._geometryInfo.map( info => ( {
  21017. ...info,
  21018. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  21019. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  21020. } ) );
  21021. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  21022. this._availableInstanceIds = source._availableInstanceIds.slice();
  21023. this._availableGeometryIds = source._availableGeometryIds.slice();
  21024. this._nextIndexStart = source._nextIndexStart;
  21025. this._nextVertexStart = source._nextVertexStart;
  21026. this._geometryCount = source._geometryCount;
  21027. this._maxInstanceCount = source._maxInstanceCount;
  21028. this._maxVertexCount = source._maxVertexCount;
  21029. this._maxIndexCount = source._maxIndexCount;
  21030. this._geometryInitialized = source._geometryInitialized;
  21031. this._multiDrawCounts = source._multiDrawCounts.slice();
  21032. this._multiDrawStarts = source._multiDrawStarts.slice();
  21033. this._indirectTexture = source._indirectTexture.clone();
  21034. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  21035. this._matricesTexture = source._matricesTexture.clone();
  21036. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  21037. if ( this._colorsTexture !== null ) {
  21038. this._colorsTexture = source._colorsTexture.clone();
  21039. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  21040. }
  21041. return this;
  21042. }
  21043. /**
  21044. * Frees the GPU-related resources allocated by this instance. Call this
  21045. * method whenever this instance is no longer used in your app.
  21046. */
  21047. dispose() {
  21048. // Assuming the geometry is not shared with other meshes
  21049. this.geometry.dispose();
  21050. this._matricesTexture.dispose();
  21051. this._matricesTexture = null;
  21052. this._indirectTexture.dispose();
  21053. this._indirectTexture = null;
  21054. if ( this._colorsTexture !== null ) {
  21055. this._colorsTexture.dispose();
  21056. this._colorsTexture = null;
  21057. }
  21058. }
  21059. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21060. // if visibility has not changed and frustum culling and object sorting is not required
  21061. // then skip iterating over all items
  21062. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21063. return;
  21064. }
  21065. // the indexed version of the multi draw function requires specifying the start
  21066. // offset in bytes.
  21067. const index = geometry.getIndex();
  21068. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21069. const instanceInfo = this._instanceInfo;
  21070. const multiDrawStarts = this._multiDrawStarts;
  21071. const multiDrawCounts = this._multiDrawCounts;
  21072. const geometryInfoList = this._geometryInfo;
  21073. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21074. const indirectTexture = this._indirectTexture;
  21075. const indirectArray = indirectTexture.image.data;
  21076. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21077. // prepare the frustum in the local frame
  21078. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21079. _matrix$1
  21080. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21081. .multiply( this.matrixWorld );
  21082. _frustum.setFromProjectionMatrix(
  21083. _matrix$1,
  21084. camera.coordinateSystem,
  21085. camera.reversedDepth
  21086. );
  21087. }
  21088. let multiDrawCount = 0;
  21089. if ( this.sortObjects ) {
  21090. // get the camera position in the local frame
  21091. _matrix$1.copy( this.matrixWorld ).invert();
  21092. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21093. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21094. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21095. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21096. const geometryId = instanceInfo[ i ].geometryIndex;
  21097. // get the bounds in world space
  21098. this.getMatrixAt( i, _matrix$1 );
  21099. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21100. // determine whether the batched geometry is within the frustum
  21101. let culled = false;
  21102. if ( perObjectFrustumCulled ) {
  21103. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21104. }
  21105. if ( ! culled ) {
  21106. // get the distance from camera used for sorting
  21107. const geometryInfo = geometryInfoList[ geometryId ];
  21108. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21109. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21110. }
  21111. }
  21112. }
  21113. // Sort the draw ranges and prep for rendering
  21114. const list = _renderList.list;
  21115. const customSort = this.customSort;
  21116. if ( customSort === null ) {
  21117. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21118. } else {
  21119. customSort.call( this, list, camera );
  21120. }
  21121. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21122. const item = list[ i ];
  21123. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21124. multiDrawCounts[ multiDrawCount ] = item.count;
  21125. indirectArray[ multiDrawCount ] = item.index;
  21126. multiDrawCount ++;
  21127. }
  21128. _renderList.reset();
  21129. } else {
  21130. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21131. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21132. const geometryId = instanceInfo[ i ].geometryIndex;
  21133. // determine whether the batched geometry is within the frustum
  21134. let culled = false;
  21135. if ( perObjectFrustumCulled ) {
  21136. // get the bounds in world space
  21137. this.getMatrixAt( i, _matrix$1 );
  21138. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21139. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21140. }
  21141. if ( ! culled ) {
  21142. const geometryInfo = geometryInfoList[ geometryId ];
  21143. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21144. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21145. indirectArray[ multiDrawCount ] = i;
  21146. multiDrawCount ++;
  21147. }
  21148. }
  21149. }
  21150. }
  21151. indirectTexture.needsUpdate = true;
  21152. this._multiDrawCount = multiDrawCount;
  21153. this._visibilityChanged = false;
  21154. }
  21155. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21156. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21157. }
  21158. }
  21159. /**
  21160. * A material for rendering line primitives.
  21161. *
  21162. * Materials define the appearance of renderable 3D objects.
  21163. *
  21164. * ```js
  21165. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21166. * ```
  21167. *
  21168. * @augments Material
  21169. */
  21170. class LineBasicMaterial extends Material {
  21171. /**
  21172. * Constructs a new line basic material.
  21173. *
  21174. * @param {Object} [parameters] - An object with one or more properties
  21175. * defining the material's appearance. Any property of the material
  21176. * (including any property from inherited materials) can be passed
  21177. * in here. Color values can be passed any type of value accepted
  21178. * by {@link Color#set}.
  21179. */
  21180. constructor( parameters ) {
  21181. super();
  21182. /**
  21183. * This flag can be used for type testing.
  21184. *
  21185. * @type {boolean}
  21186. * @readonly
  21187. * @default true
  21188. */
  21189. this.isLineBasicMaterial = true;
  21190. this.type = 'LineBasicMaterial';
  21191. /**
  21192. * Color of the material.
  21193. *
  21194. * @type {Color}
  21195. * @default (1,1,1)
  21196. */
  21197. this.color = new Color( 0xffffff );
  21198. /**
  21199. * Sets the color of the lines using data from a texture. The texture map
  21200. * color is modulated by the diffuse `color`.
  21201. *
  21202. * @type {?Texture}
  21203. * @default null
  21204. */
  21205. this.map = null;
  21206. /**
  21207. * Controls line thickness or lines.
  21208. *
  21209. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21210. * ignore this setting and always render line primitives with a
  21211. * width of one pixel.
  21212. *
  21213. * @type {number}
  21214. * @default 1
  21215. */
  21216. this.linewidth = 1;
  21217. /**
  21218. * Defines appearance of line ends.
  21219. *
  21220. * Can only be used with {@link SVGRenderer}.
  21221. *
  21222. * @type {('butt'|'round'|'square')}
  21223. * @default 'round'
  21224. */
  21225. this.linecap = 'round';
  21226. /**
  21227. * Defines appearance of line joints.
  21228. *
  21229. * Can only be used with {@link SVGRenderer}.
  21230. *
  21231. * @type {('round'|'bevel'|'miter')}
  21232. * @default 'round'
  21233. */
  21234. this.linejoin = 'round';
  21235. /**
  21236. * Whether the material is affected by fog or not.
  21237. *
  21238. * @type {boolean}
  21239. * @default true
  21240. */
  21241. this.fog = true;
  21242. this.setValues( parameters );
  21243. }
  21244. copy( source ) {
  21245. super.copy( source );
  21246. this.color.copy( source.color );
  21247. this.map = source.map;
  21248. this.linewidth = source.linewidth;
  21249. this.linecap = source.linecap;
  21250. this.linejoin = source.linejoin;
  21251. this.fog = source.fog;
  21252. return this;
  21253. }
  21254. }
  21255. const _vStart = /*@__PURE__*/ new Vector3();
  21256. const _vEnd = /*@__PURE__*/ new Vector3();
  21257. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21258. const _ray$1 = /*@__PURE__*/ new Ray();
  21259. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21260. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21261. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21262. /**
  21263. * A continuous line. The line are rendered by connecting consecutive
  21264. * vertices with straight lines.
  21265. *
  21266. * ```js
  21267. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21268. *
  21269. * const points = [];
  21270. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21271. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21272. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21273. *
  21274. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21275. *
  21276. * const line = new THREE.Line( geometry, material );
  21277. * scene.add( line );
  21278. * ```
  21279. *
  21280. * @augments Object3D
  21281. */
  21282. class Line extends Object3D {
  21283. /**
  21284. * Constructs a new line.
  21285. *
  21286. * @param {BufferGeometry} [geometry] - The line geometry.
  21287. * @param {Material|Array<Material>} [material] - The line material.
  21288. */
  21289. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21290. super();
  21291. /**
  21292. * This flag can be used for type testing.
  21293. *
  21294. * @type {boolean}
  21295. * @readonly
  21296. * @default true
  21297. */
  21298. this.isLine = true;
  21299. this.type = 'Line';
  21300. /**
  21301. * The line geometry.
  21302. *
  21303. * @type {BufferGeometry}
  21304. */
  21305. this.geometry = geometry;
  21306. /**
  21307. * The line material.
  21308. *
  21309. * @type {Material|Array<Material>}
  21310. * @default LineBasicMaterial
  21311. */
  21312. this.material = material;
  21313. /**
  21314. * A dictionary representing the morph targets in the geometry. The key is the
  21315. * morph targets name, the value its attribute index. This member is `undefined`
  21316. * by default and only set when morph targets are detected in the geometry.
  21317. *
  21318. * @type {Object<string,number>|undefined}
  21319. * @default undefined
  21320. */
  21321. this.morphTargetDictionary = undefined;
  21322. /**
  21323. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21324. * is applied. This member is `undefined` by default and only set when morph targets are
  21325. * detected in the geometry.
  21326. *
  21327. * @type {Array<number>|undefined}
  21328. * @default undefined
  21329. */
  21330. this.morphTargetInfluences = undefined;
  21331. this.updateMorphTargets();
  21332. }
  21333. copy( source, recursive ) {
  21334. super.copy( source, recursive );
  21335. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21336. this.geometry = source.geometry;
  21337. return this;
  21338. }
  21339. /**
  21340. * Computes an array of distance values which are necessary for rendering dashed lines.
  21341. * For each vertex in the geometry, the method calculates the cumulative length from the
  21342. * current point to the very beginning of the line.
  21343. *
  21344. * @return {Line} A reference to this line.
  21345. */
  21346. computeLineDistances() {
  21347. const geometry = this.geometry;
  21348. // we assume non-indexed geometry
  21349. if ( geometry.index === null ) {
  21350. const positionAttribute = geometry.attributes.position;
  21351. const lineDistances = [ 0 ];
  21352. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21353. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21354. _vEnd.fromBufferAttribute( positionAttribute, i );
  21355. lineDistances[ i ] = lineDistances[ i - 1 ];
  21356. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21357. }
  21358. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21359. } else {
  21360. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21361. }
  21362. return this;
  21363. }
  21364. /**
  21365. * Computes intersection points between a casted ray and this line.
  21366. *
  21367. * @param {Raycaster} raycaster - The raycaster.
  21368. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21369. */
  21370. raycast( raycaster, intersects ) {
  21371. const geometry = this.geometry;
  21372. const matrixWorld = this.matrixWorld;
  21373. const threshold = raycaster.params.Line.threshold;
  21374. const drawRange = geometry.drawRange;
  21375. // Checking boundingSphere distance to ray
  21376. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21377. _sphere$1.copy( geometry.boundingSphere );
  21378. _sphere$1.applyMatrix4( matrixWorld );
  21379. _sphere$1.radius += threshold;
  21380. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21381. //
  21382. _inverseMatrix$1.copy( matrixWorld ).invert();
  21383. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21384. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21385. const localThresholdSq = localThreshold * localThreshold;
  21386. const step = this.isLineSegments ? 2 : 1;
  21387. const index = geometry.index;
  21388. const attributes = geometry.attributes;
  21389. const positionAttribute = attributes.position;
  21390. if ( index !== null ) {
  21391. const start = Math.max( 0, drawRange.start );
  21392. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21393. for ( let i = start, l = end - 1; i < l; i += step ) {
  21394. const a = index.getX( i );
  21395. const b = index.getX( i + 1 );
  21396. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21397. if ( intersect ) {
  21398. intersects.push( intersect );
  21399. }
  21400. }
  21401. if ( this.isLineLoop ) {
  21402. const a = index.getX( end - 1 );
  21403. const b = index.getX( start );
  21404. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21405. if ( intersect ) {
  21406. intersects.push( intersect );
  21407. }
  21408. }
  21409. } else {
  21410. const start = Math.max( 0, drawRange.start );
  21411. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21412. for ( let i = start, l = end - 1; i < l; i += step ) {
  21413. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21414. if ( intersect ) {
  21415. intersects.push( intersect );
  21416. }
  21417. }
  21418. if ( this.isLineLoop ) {
  21419. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21420. if ( intersect ) {
  21421. intersects.push( intersect );
  21422. }
  21423. }
  21424. }
  21425. }
  21426. /**
  21427. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21428. * to make sure existing morph targets can influence this 3D object.
  21429. */
  21430. updateMorphTargets() {
  21431. const geometry = this.geometry;
  21432. const morphAttributes = geometry.morphAttributes;
  21433. const keys = Object.keys( morphAttributes );
  21434. if ( keys.length > 0 ) {
  21435. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21436. if ( morphAttribute !== undefined ) {
  21437. this.morphTargetInfluences = [];
  21438. this.morphTargetDictionary = {};
  21439. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21440. const name = morphAttribute[ m ].name || String( m );
  21441. this.morphTargetInfluences.push( 0 );
  21442. this.morphTargetDictionary[ name ] = m;
  21443. }
  21444. }
  21445. }
  21446. }
  21447. }
  21448. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21449. const positionAttribute = object.geometry.attributes.position;
  21450. _vStart.fromBufferAttribute( positionAttribute, a );
  21451. _vEnd.fromBufferAttribute( positionAttribute, b );
  21452. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21453. if ( distSq > thresholdSq ) return;
  21454. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21455. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21456. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21457. return {
  21458. distance: distance,
  21459. // What do we want? intersection point on the ray or on the segment??
  21460. // point: raycaster.ray.at( distance ),
  21461. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21462. index: i,
  21463. face: null,
  21464. faceIndex: null,
  21465. barycoord: null,
  21466. object: object
  21467. };
  21468. }
  21469. const _start = /*@__PURE__*/ new Vector3();
  21470. const _end = /*@__PURE__*/ new Vector3();
  21471. /**
  21472. * A series of lines drawn between pairs of vertices.
  21473. *
  21474. * @augments Line
  21475. */
  21476. class LineSegments extends Line {
  21477. /**
  21478. * Constructs a new line segments.
  21479. *
  21480. * @param {BufferGeometry} [geometry] - The line geometry.
  21481. * @param {Material|Array<Material>} [material] - The line material.
  21482. */
  21483. constructor( geometry, material ) {
  21484. super( geometry, material );
  21485. /**
  21486. * This flag can be used for type testing.
  21487. *
  21488. * @type {boolean}
  21489. * @readonly
  21490. * @default true
  21491. */
  21492. this.isLineSegments = true;
  21493. this.type = 'LineSegments';
  21494. }
  21495. computeLineDistances() {
  21496. const geometry = this.geometry;
  21497. // we assume non-indexed geometry
  21498. if ( geometry.index === null ) {
  21499. const positionAttribute = geometry.attributes.position;
  21500. const lineDistances = [];
  21501. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21502. _start.fromBufferAttribute( positionAttribute, i );
  21503. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21504. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21505. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21506. }
  21507. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21508. } else {
  21509. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21510. }
  21511. return this;
  21512. }
  21513. }
  21514. /**
  21515. * A continuous line. This is nearly the same as {@link Line} the only difference
  21516. * is that the last vertex is connected with the first vertex in order to close
  21517. * the line to form a loop.
  21518. *
  21519. * @augments Line
  21520. */
  21521. class LineLoop extends Line {
  21522. /**
  21523. * Constructs a new line loop.
  21524. *
  21525. * @param {BufferGeometry} [geometry] - The line geometry.
  21526. * @param {Material|Array<Material>} [material] - The line material.
  21527. */
  21528. constructor( geometry, material ) {
  21529. super( geometry, material );
  21530. /**
  21531. * This flag can be used for type testing.
  21532. *
  21533. * @type {boolean}
  21534. * @readonly
  21535. * @default true
  21536. */
  21537. this.isLineLoop = true;
  21538. this.type = 'LineLoop';
  21539. }
  21540. }
  21541. /**
  21542. * A material for rendering point primitives.
  21543. *
  21544. * Materials define the appearance of renderable 3D objects.
  21545. *
  21546. * ```js
  21547. * const vertices = [];
  21548. *
  21549. * for ( let i = 0; i < 10000; i ++ ) {
  21550. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21551. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21552. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21553. *
  21554. * vertices.push( x, y, z );
  21555. * }
  21556. *
  21557. * const geometry = new THREE.BufferGeometry();
  21558. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21559. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21560. * const points = new THREE.Points( geometry, material );
  21561. * scene.add( points );
  21562. * ```
  21563. *
  21564. * @augments Material
  21565. */
  21566. class PointsMaterial extends Material {
  21567. /**
  21568. * Constructs a new points material.
  21569. *
  21570. * @param {Object} [parameters] - An object with one or more properties
  21571. * defining the material's appearance. Any property of the material
  21572. * (including any property from inherited materials) can be passed
  21573. * in here. Color values can be passed any type of value accepted
  21574. * by {@link Color#set}.
  21575. */
  21576. constructor( parameters ) {
  21577. super();
  21578. /**
  21579. * This flag can be used for type testing.
  21580. *
  21581. * @type {boolean}
  21582. * @readonly
  21583. * @default true
  21584. */
  21585. this.isPointsMaterial = true;
  21586. this.type = 'PointsMaterial';
  21587. /**
  21588. * Color of the material.
  21589. *
  21590. * @type {Color}
  21591. * @default (1,1,1)
  21592. */
  21593. this.color = new Color( 0xffffff );
  21594. /**
  21595. * The color map. May optionally include an alpha channel, typically combined
  21596. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21597. * color is modulated by the diffuse `color`.
  21598. *
  21599. * @type {?Texture}
  21600. * @default null
  21601. */
  21602. this.map = null;
  21603. /**
  21604. * The alpha map is a grayscale texture that controls the opacity across the
  21605. * surface (black: fully transparent; white: fully opaque).
  21606. *
  21607. * Only the color of the texture is used, ignoring the alpha channel if one
  21608. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21609. * when sampling this texture due to the extra bit of precision provided for
  21610. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21611. * luminance/alpha textures will also still work as expected.
  21612. *
  21613. * @type {?Texture}
  21614. * @default null
  21615. */
  21616. this.alphaMap = null;
  21617. /**
  21618. * Defines the size of the points in pixels.
  21619. *
  21620. * 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).
  21621. *
  21622. * @type {number}
  21623. * @default 1
  21624. */
  21625. this.size = 1;
  21626. /**
  21627. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21628. *
  21629. * @type {boolean}
  21630. * @default true
  21631. */
  21632. this.sizeAttenuation = true;
  21633. /**
  21634. * Whether the material is affected by fog or not.
  21635. *
  21636. * @type {boolean}
  21637. * @default true
  21638. */
  21639. this.fog = true;
  21640. this.setValues( parameters );
  21641. }
  21642. copy( source ) {
  21643. super.copy( source );
  21644. this.color.copy( source.color );
  21645. this.map = source.map;
  21646. this.alphaMap = source.alphaMap;
  21647. this.size = source.size;
  21648. this.sizeAttenuation = source.sizeAttenuation;
  21649. this.fog = source.fog;
  21650. return this;
  21651. }
  21652. }
  21653. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21654. const _ray = /*@__PURE__*/ new Ray();
  21655. const _sphere = /*@__PURE__*/ new Sphere();
  21656. const _position$2 = /*@__PURE__*/ new Vector3();
  21657. /**
  21658. * A class for displaying points or point clouds.
  21659. *
  21660. * @augments Object3D
  21661. */
  21662. class Points extends Object3D {
  21663. /**
  21664. * Constructs a new point cloud.
  21665. *
  21666. * @param {BufferGeometry} [geometry] - The points geometry.
  21667. * @param {Material|Array<Material>} [material] - The points material.
  21668. */
  21669. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21670. super();
  21671. /**
  21672. * This flag can be used for type testing.
  21673. *
  21674. * @type {boolean}
  21675. * @readonly
  21676. * @default true
  21677. */
  21678. this.isPoints = true;
  21679. this.type = 'Points';
  21680. /**
  21681. * The points geometry.
  21682. *
  21683. * @type {BufferGeometry}
  21684. */
  21685. this.geometry = geometry;
  21686. /**
  21687. * The line material.
  21688. *
  21689. * @type {Material|Array<Material>}
  21690. * @default PointsMaterial
  21691. */
  21692. this.material = material;
  21693. /**
  21694. * A dictionary representing the morph targets in the geometry. The key is the
  21695. * morph targets name, the value its attribute index. This member is `undefined`
  21696. * by default and only set when morph targets are detected in the geometry.
  21697. *
  21698. * @type {Object<string,number>|undefined}
  21699. * @default undefined
  21700. */
  21701. this.morphTargetDictionary = undefined;
  21702. /**
  21703. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21704. * is applied. This member is `undefined` by default and only set when morph targets are
  21705. * detected in the geometry.
  21706. *
  21707. * @type {Array<number>|undefined}
  21708. * @default undefined
  21709. */
  21710. this.morphTargetInfluences = undefined;
  21711. this.updateMorphTargets();
  21712. }
  21713. copy( source, recursive ) {
  21714. super.copy( source, recursive );
  21715. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21716. this.geometry = source.geometry;
  21717. return this;
  21718. }
  21719. /**
  21720. * Computes intersection points between a casted ray and this point cloud.
  21721. *
  21722. * @param {Raycaster} raycaster - The raycaster.
  21723. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21724. */
  21725. raycast( raycaster, intersects ) {
  21726. const geometry = this.geometry;
  21727. const matrixWorld = this.matrixWorld;
  21728. const threshold = raycaster.params.Points.threshold;
  21729. const drawRange = geometry.drawRange;
  21730. // Checking boundingSphere distance to ray
  21731. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21732. _sphere.copy( geometry.boundingSphere );
  21733. _sphere.applyMatrix4( matrixWorld );
  21734. _sphere.radius += threshold;
  21735. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21736. //
  21737. _inverseMatrix.copy( matrixWorld ).invert();
  21738. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21739. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21740. const localThresholdSq = localThreshold * localThreshold;
  21741. const index = geometry.index;
  21742. const attributes = geometry.attributes;
  21743. const positionAttribute = attributes.position;
  21744. if ( index !== null ) {
  21745. const start = Math.max( 0, drawRange.start );
  21746. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21747. for ( let i = start, il = end; i < il; i ++ ) {
  21748. const a = index.getX( i );
  21749. _position$2.fromBufferAttribute( positionAttribute, a );
  21750. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21751. }
  21752. } else {
  21753. const start = Math.max( 0, drawRange.start );
  21754. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21755. for ( let i = start, l = end; i < l; i ++ ) {
  21756. _position$2.fromBufferAttribute( positionAttribute, i );
  21757. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21758. }
  21759. }
  21760. }
  21761. /**
  21762. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21763. * to make sure existing morph targets can influence this 3D object.
  21764. */
  21765. updateMorphTargets() {
  21766. const geometry = this.geometry;
  21767. const morphAttributes = geometry.morphAttributes;
  21768. const keys = Object.keys( morphAttributes );
  21769. if ( keys.length > 0 ) {
  21770. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21771. if ( morphAttribute !== undefined ) {
  21772. this.morphTargetInfluences = [];
  21773. this.morphTargetDictionary = {};
  21774. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21775. const name = morphAttribute[ m ].name || String( m );
  21776. this.morphTargetInfluences.push( 0 );
  21777. this.morphTargetDictionary[ name ] = m;
  21778. }
  21779. }
  21780. }
  21781. }
  21782. }
  21783. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21784. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21785. if ( rayPointDistanceSq < localThresholdSq ) {
  21786. const intersectPoint = new Vector3();
  21787. _ray.closestPointToPoint( point, intersectPoint );
  21788. intersectPoint.applyMatrix4( matrixWorld );
  21789. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21790. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21791. intersects.push( {
  21792. distance: distance,
  21793. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21794. point: intersectPoint,
  21795. index: index,
  21796. face: null,
  21797. faceIndex: null,
  21798. barycoord: null,
  21799. object: object
  21800. } );
  21801. }
  21802. }
  21803. /**
  21804. * A texture for use with a video.
  21805. *
  21806. * ```js
  21807. * // assuming you have created a HTML video element with id="video"
  21808. * const video = document.getElementById( 'video' );
  21809. * const texture = new THREE.VideoTexture( video );
  21810. * ```
  21811. *
  21812. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21813. * set to THREE.SRGBColorSpace.
  21814. *
  21815. * Note: After the initial use of a texture, its dimensions, format, and type
  21816. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21817. *
  21818. * @augments Texture
  21819. */
  21820. class VideoTexture extends Texture {
  21821. /**
  21822. * Constructs a new video texture.
  21823. *
  21824. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21825. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21826. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21827. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21828. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21829. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21830. * @param {number} [format=RGBAFormat] - The texture format.
  21831. * @param {number} [type=UnsignedByteType] - The texture type.
  21832. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21833. */
  21834. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21835. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21836. /**
  21837. * This flag can be used for type testing.
  21838. *
  21839. * @type {boolean}
  21840. * @readonly
  21841. * @default true
  21842. */
  21843. this.isVideoTexture = true;
  21844. /**
  21845. * Whether to generate mipmaps (if possible) for a texture.
  21846. *
  21847. * Overwritten and set to `false` by default.
  21848. *
  21849. * @type {boolean}
  21850. * @default false
  21851. */
  21852. this.generateMipmaps = false;
  21853. /**
  21854. * The video frame request callback identifier, which is a positive integer.
  21855. *
  21856. * Value of 0 represents no scheduled rVFC.
  21857. *
  21858. * @private
  21859. * @type {number}
  21860. */
  21861. this._requestVideoFrameCallbackId = 0;
  21862. const scope = this;
  21863. function updateVideo() {
  21864. scope.needsUpdate = true;
  21865. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21866. }
  21867. if ( 'requestVideoFrameCallback' in video ) {
  21868. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21869. }
  21870. }
  21871. clone() {
  21872. return new this.constructor( this.image ).copy( this );
  21873. }
  21874. /**
  21875. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21876. * to `true` every time a new frame is available.
  21877. *
  21878. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21879. */
  21880. update() {
  21881. const video = this.image;
  21882. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21883. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21884. this.needsUpdate = true;
  21885. }
  21886. }
  21887. dispose() {
  21888. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21889. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21890. this._requestVideoFrameCallbackId = 0;
  21891. }
  21892. super.dispose();
  21893. }
  21894. }
  21895. /**
  21896. * This class can be used as an alternative way to define video data. Instead of using
  21897. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21898. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21899. * video frames are decoded with the WebCodecs API.
  21900. *
  21901. * ```js
  21902. * const texture = new THREE.VideoFrameTexture();
  21903. * texture.setFrame( frame );
  21904. * ```
  21905. *
  21906. * @augments VideoTexture
  21907. */
  21908. class VideoFrameTexture extends VideoTexture {
  21909. /**
  21910. * Constructs a new video frame texture.
  21911. *
  21912. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21913. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21914. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21915. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21916. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21917. * @param {number} [format=RGBAFormat] - The texture format.
  21918. * @param {number} [type=UnsignedByteType] - The texture type.
  21919. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21920. */
  21921. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21922. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21923. /**
  21924. * This flag can be used for type testing.
  21925. *
  21926. * @type {boolean}
  21927. * @readonly
  21928. * @default true
  21929. */
  21930. this.isVideoFrameTexture = true;
  21931. }
  21932. /**
  21933. * This method overwritten with an empty implementation since
  21934. * this type of texture is updated via `setFrame()`.
  21935. */
  21936. update() {}
  21937. clone() {
  21938. return new this.constructor().copy( this ); // restoring Texture.clone()
  21939. }
  21940. /**
  21941. * Sets the current frame of the video. This will automatically update the texture
  21942. * so the data can be used for rendering.
  21943. *
  21944. * @param {VideoFrame} frame - The video frame.
  21945. */
  21946. setFrame( frame ) {
  21947. this.image = frame;
  21948. this.needsUpdate = true;
  21949. }
  21950. }
  21951. /**
  21952. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21953. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21954. * as a texture for further usage.
  21955. *
  21956. * ```js
  21957. * const pixelRatio = window.devicePixelRatio;
  21958. * const textureSize = 128 * pixelRatio;
  21959. *
  21960. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21961. *
  21962. * // calculate start position for copying part of the frame data
  21963. * const vector = new Vector2();
  21964. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21965. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21966. *
  21967. * renderer.render( scene, camera );
  21968. *
  21969. * // copy part of the rendered frame into the framebuffer texture
  21970. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21971. * ```
  21972. *
  21973. * @augments Texture
  21974. */
  21975. class FramebufferTexture extends Texture {
  21976. /**
  21977. * Constructs a new framebuffer texture.
  21978. *
  21979. * @param {number} [width] - The width of the texture.
  21980. * @param {number} [height] - The height of the texture.
  21981. */
  21982. constructor( width, height ) {
  21983. super( { width, height } );
  21984. /**
  21985. * This flag can be used for type testing.
  21986. *
  21987. * @type {boolean}
  21988. * @readonly
  21989. * @default true
  21990. */
  21991. this.isFramebufferTexture = true;
  21992. /**
  21993. * How the texture is sampled when a texel covers more than one pixel.
  21994. *
  21995. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21996. *
  21997. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21998. * @default NearestFilter
  21999. */
  22000. this.magFilter = NearestFilter;
  22001. /**
  22002. * How the texture is sampled when a texel covers less than one pixel.
  22003. *
  22004. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22005. *
  22006. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22007. * @default NearestFilter
  22008. */
  22009. this.minFilter = NearestFilter;
  22010. /**
  22011. * Whether to generate mipmaps (if possible) for a texture.
  22012. *
  22013. * Overwritten and set to `false` by default.
  22014. *
  22015. * @type {boolean}
  22016. * @default false
  22017. */
  22018. this.generateMipmaps = false;
  22019. this.needsUpdate = true;
  22020. }
  22021. }
  22022. /**
  22023. * Creates a texture based on data in compressed form.
  22024. *
  22025. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22026. *
  22027. * @augments Texture
  22028. */
  22029. class CompressedTexture extends Texture {
  22030. /**
  22031. * Constructs a new compressed texture.
  22032. *
  22033. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22034. * the data and dimensions.
  22035. * @param {number} width - The width of the texture.
  22036. * @param {number} height - The height of the texture.
  22037. * @param {number} [format=RGBAFormat] - The texture format.
  22038. * @param {number} [type=UnsignedByteType] - The texture type.
  22039. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22040. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22041. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22042. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22043. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22044. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22045. * @param {string} [colorSpace=NoColorSpace] - The color space.
  22046. */
  22047. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  22048. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  22049. /**
  22050. * This flag can be used for type testing.
  22051. *
  22052. * @type {boolean}
  22053. * @readonly
  22054. * @default true
  22055. */
  22056. this.isCompressedTexture = true;
  22057. /**
  22058. * The image property of a compressed texture just defines its dimensions.
  22059. *
  22060. * @type {{width:number,height:number}}
  22061. */
  22062. this.image = { width: width, height: height };
  22063. /**
  22064. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22065. *
  22066. * @type {Array<Object>}
  22067. */
  22068. this.mipmaps = mipmaps;
  22069. /**
  22070. * If set to `true`, the texture is flipped along the vertical axis when
  22071. * uploaded to the GPU.
  22072. *
  22073. * Overwritten and set to `false` by default since it is not possible to
  22074. * flip compressed textures.
  22075. *
  22076. * @type {boolean}
  22077. * @default false
  22078. * @readonly
  22079. */
  22080. this.flipY = false;
  22081. /**
  22082. * Whether to generate mipmaps (if possible) for a texture.
  22083. *
  22084. * Overwritten and set to `false` by default since it is not
  22085. * possible to generate mipmaps for compressed data. Mipmaps
  22086. * must be embedded in the compressed texture file.
  22087. *
  22088. * @type {boolean}
  22089. * @default false
  22090. * @readonly
  22091. */
  22092. this.generateMipmaps = false;
  22093. }
  22094. }
  22095. /**
  22096. * Creates a texture 2D array based on data in compressed form.
  22097. *
  22098. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22099. *
  22100. * @augments CompressedTexture
  22101. */
  22102. class CompressedArrayTexture extends CompressedTexture {
  22103. /**
  22104. * Constructs a new compressed array texture.
  22105. *
  22106. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22107. * the data and dimensions.
  22108. * @param {number} width - The width of the texture.
  22109. * @param {number} height - The height of the texture.
  22110. * @param {number} depth - The depth of the texture.
  22111. * @param {number} [format=RGBAFormat] - The min filter value.
  22112. * @param {number} [type=UnsignedByteType] - The min filter value.
  22113. */
  22114. constructor( mipmaps, width, height, depth, format, type ) {
  22115. super( mipmaps, width, height, format, type );
  22116. /**
  22117. * This flag can be used for type testing.
  22118. *
  22119. * @type {boolean}
  22120. * @readonly
  22121. * @default true
  22122. */
  22123. this.isCompressedArrayTexture = true;
  22124. /**
  22125. * The image property of a compressed texture just defines its dimensions.
  22126. *
  22127. * @name CompressedArrayTexture#image
  22128. * @type {{width:number,height:number,depth:number}}
  22129. */
  22130. this.image.depth = depth;
  22131. /**
  22132. * This defines how the texture is wrapped in the depth and corresponds to
  22133. * *W* in UVW mapping.
  22134. *
  22135. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22136. * @default ClampToEdgeWrapping
  22137. */
  22138. this.wrapR = ClampToEdgeWrapping;
  22139. /**
  22140. * A set of all layers which need to be updated in the texture.
  22141. *
  22142. * @type {Set<number>}
  22143. */
  22144. this.layerUpdates = new Set();
  22145. }
  22146. /**
  22147. * Describes that a specific layer of the texture needs to be updated.
  22148. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22149. * entire compressed texture array is sent to the GPU. Marking specific
  22150. * layers will only transmit subsets of all mipmaps associated with a
  22151. * specific depth in the array which is often much more performant.
  22152. *
  22153. * @param {number} layerIndex - The layer index that should be updated.
  22154. */
  22155. addLayerUpdate( layerIndex ) {
  22156. this.layerUpdates.add( layerIndex );
  22157. }
  22158. /**
  22159. * Resets the layer updates registry.
  22160. */
  22161. clearLayerUpdates() {
  22162. this.layerUpdates.clear();
  22163. }
  22164. }
  22165. /**
  22166. * Creates a cube texture based on data in compressed form.
  22167. *
  22168. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22169. *
  22170. * @augments CompressedTexture
  22171. */
  22172. class CompressedCubeTexture extends CompressedTexture {
  22173. /**
  22174. * Constructs a new compressed texture.
  22175. *
  22176. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22177. * @param {number} [format=RGBAFormat] - The texture format.
  22178. * @param {number} [type=UnsignedByteType] - The texture type.
  22179. */
  22180. constructor( images, format, type ) {
  22181. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22182. /**
  22183. * This flag can be used for type testing.
  22184. *
  22185. * @type {boolean}
  22186. * @readonly
  22187. * @default true
  22188. */
  22189. this.isCompressedCubeTexture = true;
  22190. /**
  22191. * This flag can be used for type testing.
  22192. *
  22193. * @type {boolean}
  22194. * @readonly
  22195. * @default true
  22196. */
  22197. this.isCubeTexture = true;
  22198. this.image = images;
  22199. }
  22200. }
  22201. /**
  22202. * Creates a texture from a canvas element.
  22203. *
  22204. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22205. * to `true` immediately since a canvas can directly be used for rendering.
  22206. *
  22207. * @augments Texture
  22208. */
  22209. class CanvasTexture extends Texture {
  22210. /**
  22211. * Constructs a new texture.
  22212. *
  22213. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22214. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22215. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22216. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22217. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22218. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22219. * @param {number} [format=RGBAFormat] - The texture format.
  22220. * @param {number} [type=UnsignedByteType] - The texture type.
  22221. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22222. */
  22223. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22224. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22225. /**
  22226. * This flag can be used for type testing.
  22227. *
  22228. * @type {boolean}
  22229. * @readonly
  22230. * @default true
  22231. */
  22232. this.isCanvasTexture = true;
  22233. this.needsUpdate = true;
  22234. }
  22235. }
  22236. /**
  22237. * This class can be used to automatically save the depth information of a
  22238. * rendering into a texture.
  22239. *
  22240. * @augments Texture
  22241. */
  22242. class DepthTexture extends Texture {
  22243. /**
  22244. * Constructs a new depth texture.
  22245. *
  22246. * @param {number} width - The width of the texture.
  22247. * @param {number} height - The height of the texture.
  22248. * @param {number} [type=UnsignedIntType] - The texture type.
  22249. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22250. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22251. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22252. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22253. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22254. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22255. * @param {number} [format=DepthFormat] - The texture format.
  22256. * @param {number} [depth=1] - The depth of the texture.
  22257. */
  22258. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22259. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22260. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22261. }
  22262. const image = { width: width, height: height, depth: depth };
  22263. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22264. /**
  22265. * This flag can be used for type testing.
  22266. *
  22267. * @type {boolean}
  22268. * @readonly
  22269. * @default true
  22270. */
  22271. this.isDepthTexture = true;
  22272. /**
  22273. * If set to `true`, the texture is flipped along the vertical axis when
  22274. * uploaded to the GPU.
  22275. *
  22276. * Overwritten and set to `false` by default.
  22277. *
  22278. * @type {boolean}
  22279. * @default false
  22280. */
  22281. this.flipY = false;
  22282. /**
  22283. * Whether to generate mipmaps (if possible) for a texture.
  22284. *
  22285. * Overwritten and set to `false` by default.
  22286. *
  22287. * @type {boolean}
  22288. * @default false
  22289. */
  22290. this.generateMipmaps = false;
  22291. /**
  22292. * Code corresponding to the depth compare function.
  22293. *
  22294. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22295. * @default null
  22296. */
  22297. this.compareFunction = null;
  22298. }
  22299. copy( source ) {
  22300. super.copy( source );
  22301. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22302. this.compareFunction = source.compareFunction;
  22303. return this;
  22304. }
  22305. toJSON( meta ) {
  22306. const data = super.toJSON( meta );
  22307. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22308. return data;
  22309. }
  22310. }
  22311. /**
  22312. * This class can be used to automatically save the depth information of a
  22313. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22314. *
  22315. * @augments DepthTexture
  22316. */
  22317. class CubeDepthTexture extends DepthTexture {
  22318. /**
  22319. * Constructs a new cube depth texture.
  22320. *
  22321. * @param {number} size - The size (width and height) of each cube face.
  22322. * @param {number} [type=UnsignedIntType] - The texture type.
  22323. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22324. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22325. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22326. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22327. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22328. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22329. * @param {number} [format=DepthFormat] - The texture format.
  22330. */
  22331. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22332. // Create 6 identical image descriptors for the cube faces
  22333. const image = { width: size, height: size, depth: 1 };
  22334. const images = [ image, image, image, image, image, image ];
  22335. // Call DepthTexture constructor with width, height
  22336. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22337. // Replace the single image with the array of 6 images
  22338. this.image = images;
  22339. /**
  22340. * This flag can be used for type testing.
  22341. *
  22342. * @type {boolean}
  22343. * @readonly
  22344. * @default true
  22345. */
  22346. this.isCubeDepthTexture = true;
  22347. /**
  22348. * Set to true for cube texture handling in WebGLTextures.
  22349. *
  22350. * @type {boolean}
  22351. * @readonly
  22352. * @default true
  22353. */
  22354. this.isCubeTexture = true;
  22355. }
  22356. /**
  22357. * Alias for {@link CubeDepthTexture#image}.
  22358. *
  22359. * @type {Array<Image>}
  22360. */
  22361. get images() {
  22362. return this.image;
  22363. }
  22364. set images( value ) {
  22365. this.image = value;
  22366. }
  22367. }
  22368. /**
  22369. * Represents a texture created externally with the same renderer context.
  22370. *
  22371. * This may be a texture from a protected media stream, device camera feed,
  22372. * or other data feeds like a depth sensor.
  22373. *
  22374. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22375. * the {@link WebGPURenderer} WebGPU backend.
  22376. *
  22377. * @augments Texture
  22378. */
  22379. class ExternalTexture extends Texture {
  22380. /**
  22381. * Creates a new raw texture.
  22382. *
  22383. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22384. */
  22385. constructor( sourceTexture = null ) {
  22386. super();
  22387. /**
  22388. * The external source texture.
  22389. *
  22390. * @type {?(WebGLTexture|GPUTexture)}
  22391. * @default null
  22392. */
  22393. this.sourceTexture = sourceTexture;
  22394. /**
  22395. * This flag can be used for type testing.
  22396. *
  22397. * @type {boolean}
  22398. * @readonly
  22399. * @default true
  22400. */
  22401. this.isExternalTexture = true;
  22402. }
  22403. copy( source ) {
  22404. super.copy( source );
  22405. this.sourceTexture = source.sourceTexture;
  22406. return this;
  22407. }
  22408. }
  22409. /**
  22410. * A geometry class for representing a capsule.
  22411. *
  22412. * ```js
  22413. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22414. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22415. * const capsule = new THREE.Mesh( geometry, material );
  22416. * scene.add( capsule );
  22417. * ```
  22418. *
  22419. * @augments BufferGeometry
  22420. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22421. */
  22422. class CapsuleGeometry extends BufferGeometry {
  22423. /**
  22424. * Constructs a new capsule geometry.
  22425. *
  22426. * @param {number} [radius=1] - Radius of the capsule.
  22427. * @param {number} [height=1] - Height of the middle section.
  22428. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22429. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22430. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22431. */
  22432. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22433. super();
  22434. this.type = 'CapsuleGeometry';
  22435. /**
  22436. * Holds the constructor parameters that have been
  22437. * used to generate the geometry. Any modification
  22438. * after instantiation does not change the geometry.
  22439. *
  22440. * @type {Object}
  22441. */
  22442. this.parameters = {
  22443. radius: radius,
  22444. height: height,
  22445. capSegments: capSegments,
  22446. radialSegments: radialSegments,
  22447. heightSegments: heightSegments,
  22448. };
  22449. height = Math.max( 0, height );
  22450. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22451. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22452. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22453. // buffers
  22454. const indices = [];
  22455. const vertices = [];
  22456. const normals = [];
  22457. const uvs = [];
  22458. // helper variables
  22459. const halfHeight = height / 2;
  22460. const capArcLength = ( Math.PI / 2 ) * radius;
  22461. const cylinderPartLength = height;
  22462. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22463. const numVerticalSegments = capSegments * 2 + heightSegments;
  22464. const verticesPerRow = radialSegments + 1;
  22465. const normal = new Vector3();
  22466. const vertex = new Vector3();
  22467. // generate vertices, normals, and uvs
  22468. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22469. let currentArcLength = 0;
  22470. let profileY = 0;
  22471. let profileRadius = 0;
  22472. let normalYComponent = 0;
  22473. if ( iy <= capSegments ) {
  22474. // bottom cap
  22475. const segmentProgress = iy / capSegments;
  22476. const angle = ( segmentProgress * Math.PI ) / 2;
  22477. profileY = - halfHeight - radius * Math.cos( angle );
  22478. profileRadius = radius * Math.sin( angle );
  22479. normalYComponent = - radius * Math.cos( angle );
  22480. currentArcLength = segmentProgress * capArcLength;
  22481. } else if ( iy <= capSegments + heightSegments ) {
  22482. // middle section
  22483. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22484. profileY = - halfHeight + segmentProgress * height;
  22485. profileRadius = radius;
  22486. normalYComponent = 0;
  22487. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22488. } else {
  22489. // top cap
  22490. const segmentProgress =
  22491. ( iy - capSegments - heightSegments ) / capSegments;
  22492. const angle = ( segmentProgress * Math.PI ) / 2;
  22493. profileY = halfHeight + radius * Math.sin( angle );
  22494. profileRadius = radius * Math.cos( angle );
  22495. normalYComponent = radius * Math.sin( angle );
  22496. currentArcLength =
  22497. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22498. }
  22499. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22500. // special case for the poles
  22501. let uOffset = 0;
  22502. if ( iy === 0 ) {
  22503. uOffset = 0.5 / radialSegments;
  22504. } else if ( iy === numVerticalSegments ) {
  22505. uOffset = -0.5 / radialSegments;
  22506. }
  22507. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22508. const u = ix / radialSegments;
  22509. const theta = u * Math.PI * 2;
  22510. const sinTheta = Math.sin( theta );
  22511. const cosTheta = Math.cos( theta );
  22512. // vertex
  22513. vertex.x = - profileRadius * cosTheta;
  22514. vertex.y = profileY;
  22515. vertex.z = profileRadius * sinTheta;
  22516. vertices.push( vertex.x, vertex.y, vertex.z );
  22517. // normal
  22518. normal.set(
  22519. - profileRadius * cosTheta,
  22520. normalYComponent,
  22521. profileRadius * sinTheta
  22522. );
  22523. normal.normalize();
  22524. normals.push( normal.x, normal.y, normal.z );
  22525. // uv
  22526. uvs.push( u + uOffset, v );
  22527. }
  22528. if ( iy > 0 ) {
  22529. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22530. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22531. const i1 = prevIndexRow + ix;
  22532. const i2 = prevIndexRow + ix + 1;
  22533. const i3 = iy * verticesPerRow + ix;
  22534. const i4 = iy * verticesPerRow + ix + 1;
  22535. indices.push( i1, i2, i3 );
  22536. indices.push( i2, i4, i3 );
  22537. }
  22538. }
  22539. }
  22540. // build geometry
  22541. this.setIndex( indices );
  22542. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22543. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22544. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22545. }
  22546. copy( source ) {
  22547. super.copy( source );
  22548. this.parameters = Object.assign( {}, source.parameters );
  22549. return this;
  22550. }
  22551. /**
  22552. * Factory method for creating an instance of this class from the given
  22553. * JSON object.
  22554. *
  22555. * @param {Object} data - A JSON object representing the serialized geometry.
  22556. * @return {CapsuleGeometry} A new instance.
  22557. */
  22558. static fromJSON( data ) {
  22559. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22560. }
  22561. }
  22562. /**
  22563. * A simple shape of Euclidean geometry. It is constructed from a
  22564. * number of triangular segments that are oriented around a central point and
  22565. * extend as far out as a given radius. It is built counter-clockwise from a
  22566. * start angle and a given central angle. It can also be used to create
  22567. * regular polygons, where the number of segments determines the number of
  22568. * sides.
  22569. *
  22570. * ```js
  22571. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22572. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22573. * const circle = new THREE.Mesh( geometry, material );
  22574. * scene.add( circle )
  22575. * ```
  22576. *
  22577. * @augments BufferGeometry
  22578. * @demo scenes/geometry-browser.html#CircleGeometry
  22579. */
  22580. class CircleGeometry extends BufferGeometry {
  22581. /**
  22582. * Constructs a new circle geometry.
  22583. *
  22584. * @param {number} [radius=1] - Radius of the circle.
  22585. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22586. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22587. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22588. * of the circular sector in radians. The default value results in a complete circle.
  22589. */
  22590. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22591. super();
  22592. this.type = 'CircleGeometry';
  22593. /**
  22594. * Holds the constructor parameters that have been
  22595. * used to generate the geometry. Any modification
  22596. * after instantiation does not change the geometry.
  22597. *
  22598. * @type {Object}
  22599. */
  22600. this.parameters = {
  22601. radius: radius,
  22602. segments: segments,
  22603. thetaStart: thetaStart,
  22604. thetaLength: thetaLength
  22605. };
  22606. segments = Math.max( 3, segments );
  22607. // buffers
  22608. const indices = [];
  22609. const vertices = [];
  22610. const normals = [];
  22611. const uvs = [];
  22612. // helper variables
  22613. const vertex = new Vector3();
  22614. const uv = new Vector2();
  22615. // center point
  22616. vertices.push( 0, 0, 0 );
  22617. normals.push( 0, 0, 1 );
  22618. uvs.push( 0.5, 0.5 );
  22619. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22620. const segment = thetaStart + s / segments * thetaLength;
  22621. // vertex
  22622. vertex.x = radius * Math.cos( segment );
  22623. vertex.y = radius * Math.sin( segment );
  22624. vertices.push( vertex.x, vertex.y, vertex.z );
  22625. // normal
  22626. normals.push( 0, 0, 1 );
  22627. // uvs
  22628. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22629. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22630. uvs.push( uv.x, uv.y );
  22631. }
  22632. // indices
  22633. for ( let i = 1; i <= segments; i ++ ) {
  22634. indices.push( i, i + 1, 0 );
  22635. }
  22636. // build geometry
  22637. this.setIndex( indices );
  22638. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22639. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22640. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22641. }
  22642. copy( source ) {
  22643. super.copy( source );
  22644. this.parameters = Object.assign( {}, source.parameters );
  22645. return this;
  22646. }
  22647. /**
  22648. * Factory method for creating an instance of this class from the given
  22649. * JSON object.
  22650. *
  22651. * @param {Object} data - A JSON object representing the serialized geometry.
  22652. * @return {CircleGeometry} A new instance.
  22653. */
  22654. static fromJSON( data ) {
  22655. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22656. }
  22657. }
  22658. /**
  22659. * A geometry class for representing a cylinder.
  22660. *
  22661. * ```js
  22662. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22663. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22664. * const cylinder = new THREE.Mesh( geometry, material );
  22665. * scene.add( cylinder );
  22666. * ```
  22667. *
  22668. * @augments BufferGeometry
  22669. * @demo scenes/geometry-browser.html#CylinderGeometry
  22670. */
  22671. class CylinderGeometry extends BufferGeometry {
  22672. /**
  22673. * Constructs a new cylinder geometry.
  22674. *
  22675. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22676. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22677. * @param {number} [height=1] - Height of the cylinder.
  22678. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22679. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22680. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22681. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22682. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22683. * The default value results in a complete cylinder.
  22684. */
  22685. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22686. super();
  22687. this.type = 'CylinderGeometry';
  22688. /**
  22689. * Holds the constructor parameters that have been
  22690. * used to generate the geometry. Any modification
  22691. * after instantiation does not change the geometry.
  22692. *
  22693. * @type {Object}
  22694. */
  22695. this.parameters = {
  22696. radiusTop: radiusTop,
  22697. radiusBottom: radiusBottom,
  22698. height: height,
  22699. radialSegments: radialSegments,
  22700. heightSegments: heightSegments,
  22701. openEnded: openEnded,
  22702. thetaStart: thetaStart,
  22703. thetaLength: thetaLength
  22704. };
  22705. const scope = this;
  22706. radialSegments = Math.floor( radialSegments );
  22707. heightSegments = Math.floor( heightSegments );
  22708. // buffers
  22709. const indices = [];
  22710. const vertices = [];
  22711. const normals = [];
  22712. const uvs = [];
  22713. // helper variables
  22714. let index = 0;
  22715. const indexArray = [];
  22716. const halfHeight = height / 2;
  22717. let groupStart = 0;
  22718. // generate geometry
  22719. generateTorso();
  22720. if ( openEnded === false ) {
  22721. if ( radiusTop > 0 ) generateCap( true );
  22722. if ( radiusBottom > 0 ) generateCap( false );
  22723. }
  22724. // build geometry
  22725. this.setIndex( indices );
  22726. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22727. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22728. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22729. function generateTorso() {
  22730. const normal = new Vector3();
  22731. const vertex = new Vector3();
  22732. let groupCount = 0;
  22733. // this will be used to calculate the normal
  22734. const slope = ( radiusBottom - radiusTop ) / height;
  22735. // generate vertices, normals and uvs
  22736. for ( let y = 0; y <= heightSegments; y ++ ) {
  22737. const indexRow = [];
  22738. const v = y / heightSegments;
  22739. // calculate the radius of the current row
  22740. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22741. for ( let x = 0; x <= radialSegments; x ++ ) {
  22742. const u = x / radialSegments;
  22743. const theta = u * thetaLength + thetaStart;
  22744. const sinTheta = Math.sin( theta );
  22745. const cosTheta = Math.cos( theta );
  22746. // vertex
  22747. vertex.x = radius * sinTheta;
  22748. vertex.y = - v * height + halfHeight;
  22749. vertex.z = radius * cosTheta;
  22750. vertices.push( vertex.x, vertex.y, vertex.z );
  22751. // normal
  22752. normal.set( sinTheta, slope, cosTheta ).normalize();
  22753. normals.push( normal.x, normal.y, normal.z );
  22754. // uv
  22755. uvs.push( u, 1 - v );
  22756. // save index of vertex in respective row
  22757. indexRow.push( index ++ );
  22758. }
  22759. // now save vertices of the row in our index array
  22760. indexArray.push( indexRow );
  22761. }
  22762. // generate indices
  22763. for ( let x = 0; x < radialSegments; x ++ ) {
  22764. for ( let y = 0; y < heightSegments; y ++ ) {
  22765. // we use the index array to access the correct indices
  22766. const a = indexArray[ y ][ x ];
  22767. const b = indexArray[ y + 1 ][ x ];
  22768. const c = indexArray[ y + 1 ][ x + 1 ];
  22769. const d = indexArray[ y ][ x + 1 ];
  22770. // faces
  22771. if ( radiusTop > 0 || y !== 0 ) {
  22772. indices.push( a, b, d );
  22773. groupCount += 3;
  22774. }
  22775. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22776. indices.push( b, c, d );
  22777. groupCount += 3;
  22778. }
  22779. }
  22780. }
  22781. // add a group to the geometry. this will ensure multi material support
  22782. scope.addGroup( groupStart, groupCount, 0 );
  22783. // calculate new start value for groups
  22784. groupStart += groupCount;
  22785. }
  22786. function generateCap( top ) {
  22787. // save the index of the first center vertex
  22788. const centerIndexStart = index;
  22789. const uv = new Vector2();
  22790. const vertex = new Vector3();
  22791. let groupCount = 0;
  22792. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22793. const sign = ( top === true ) ? 1 : -1;
  22794. // first we generate the center vertex data of the cap.
  22795. // because the geometry needs one set of uvs per face,
  22796. // we must generate a center vertex per face/segment
  22797. for ( let x = 1; x <= radialSegments; x ++ ) {
  22798. // vertex
  22799. vertices.push( 0, halfHeight * sign, 0 );
  22800. // normal
  22801. normals.push( 0, sign, 0 );
  22802. // uv
  22803. uvs.push( 0.5, 0.5 );
  22804. // increase index
  22805. index ++;
  22806. }
  22807. // save the index of the last center vertex
  22808. const centerIndexEnd = index;
  22809. // now we generate the surrounding vertices, normals and uvs
  22810. for ( let x = 0; x <= radialSegments; x ++ ) {
  22811. const u = x / radialSegments;
  22812. const theta = u * thetaLength + thetaStart;
  22813. const cosTheta = Math.cos( theta );
  22814. const sinTheta = Math.sin( theta );
  22815. // vertex
  22816. vertex.x = radius * sinTheta;
  22817. vertex.y = halfHeight * sign;
  22818. vertex.z = radius * cosTheta;
  22819. vertices.push( vertex.x, vertex.y, vertex.z );
  22820. // normal
  22821. normals.push( 0, sign, 0 );
  22822. // uv
  22823. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22824. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22825. uvs.push( uv.x, uv.y );
  22826. // increase index
  22827. index ++;
  22828. }
  22829. // generate indices
  22830. for ( let x = 0; x < radialSegments; x ++ ) {
  22831. const c = centerIndexStart + x;
  22832. const i = centerIndexEnd + x;
  22833. if ( top === true ) {
  22834. // face top
  22835. indices.push( i, i + 1, c );
  22836. } else {
  22837. // face bottom
  22838. indices.push( i + 1, i, c );
  22839. }
  22840. groupCount += 3;
  22841. }
  22842. // add a group to the geometry. this will ensure multi material support
  22843. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22844. // calculate new start value for groups
  22845. groupStart += groupCount;
  22846. }
  22847. }
  22848. copy( source ) {
  22849. super.copy( source );
  22850. this.parameters = Object.assign( {}, source.parameters );
  22851. return this;
  22852. }
  22853. /**
  22854. * Factory method for creating an instance of this class from the given
  22855. * JSON object.
  22856. *
  22857. * @param {Object} data - A JSON object representing the serialized geometry.
  22858. * @return {CylinderGeometry} A new instance.
  22859. */
  22860. static fromJSON( data ) {
  22861. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22862. }
  22863. }
  22864. /**
  22865. * A geometry class for representing a cone.
  22866. *
  22867. * ```js
  22868. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22869. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22870. * const cone = new THREE.Mesh(geometry, material );
  22871. * scene.add( cone );
  22872. * ```
  22873. *
  22874. * @augments CylinderGeometry
  22875. * @demo scenes/geometry-browser.html#ConeGeometry
  22876. */
  22877. class ConeGeometry extends CylinderGeometry {
  22878. /**
  22879. * Constructs a new cone geometry.
  22880. *
  22881. * @param {number} [radius=1] - Radius of the cone base.
  22882. * @param {number} [height=1] - Height of the cone.
  22883. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22884. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22885. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22886. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22887. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22888. * The default value results in a complete cone.
  22889. */
  22890. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22891. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22892. this.type = 'ConeGeometry';
  22893. /**
  22894. * Holds the constructor parameters that have been
  22895. * used to generate the geometry. Any modification
  22896. * after instantiation does not change the geometry.
  22897. *
  22898. * @type {Object}
  22899. */
  22900. this.parameters = {
  22901. radius: radius,
  22902. height: height,
  22903. radialSegments: radialSegments,
  22904. heightSegments: heightSegments,
  22905. openEnded: openEnded,
  22906. thetaStart: thetaStart,
  22907. thetaLength: thetaLength
  22908. };
  22909. }
  22910. /**
  22911. * Factory method for creating an instance of this class from the given
  22912. * JSON object.
  22913. *
  22914. * @param {Object} data - A JSON object representing the serialized geometry.
  22915. * @return {ConeGeometry} A new instance.
  22916. */
  22917. static fromJSON( data ) {
  22918. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22919. }
  22920. }
  22921. /**
  22922. * A polyhedron is a solid in three dimensions with flat faces. This class
  22923. * will take an array of vertices, project them onto a sphere, and then
  22924. * divide them up to the desired level of detail.
  22925. *
  22926. * @augments BufferGeometry
  22927. */
  22928. class PolyhedronGeometry extends BufferGeometry {
  22929. /**
  22930. * Constructs a new polyhedron geometry.
  22931. *
  22932. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22933. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22934. * @param {number} [radius=1] - The radius of the shape.
  22935. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22936. */
  22937. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22938. super();
  22939. this.type = 'PolyhedronGeometry';
  22940. /**
  22941. * Holds the constructor parameters that have been
  22942. * used to generate the geometry. Any modification
  22943. * after instantiation does not change the geometry.
  22944. *
  22945. * @type {Object}
  22946. */
  22947. this.parameters = {
  22948. vertices: vertices,
  22949. indices: indices,
  22950. radius: radius,
  22951. detail: detail
  22952. };
  22953. // default buffer data
  22954. const vertexBuffer = [];
  22955. const uvBuffer = [];
  22956. // the subdivision creates the vertex buffer data
  22957. subdivide( detail );
  22958. // all vertices should lie on a conceptual sphere with a given radius
  22959. applyRadius( radius );
  22960. // finally, create the uv data
  22961. generateUVs();
  22962. // build non-indexed geometry
  22963. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22964. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22965. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22966. if ( detail === 0 ) {
  22967. this.computeVertexNormals(); // flat normals
  22968. } else {
  22969. this.normalizeNormals(); // smooth normals
  22970. }
  22971. // helper functions
  22972. function subdivide( detail ) {
  22973. const a = new Vector3();
  22974. const b = new Vector3();
  22975. const c = new Vector3();
  22976. // iterate over all faces and apply a subdivision with the given detail value
  22977. for ( let i = 0; i < indices.length; i += 3 ) {
  22978. // get the vertices of the face
  22979. getVertexByIndex( indices[ i + 0 ], a );
  22980. getVertexByIndex( indices[ i + 1 ], b );
  22981. getVertexByIndex( indices[ i + 2 ], c );
  22982. // perform subdivision
  22983. subdivideFace( a, b, c, detail );
  22984. }
  22985. }
  22986. function subdivideFace( a, b, c, detail ) {
  22987. const cols = detail + 1;
  22988. // we use this multidimensional array as a data structure for creating the subdivision
  22989. const v = [];
  22990. // construct all of the vertices for this subdivision
  22991. for ( let i = 0; i <= cols; i ++ ) {
  22992. v[ i ] = [];
  22993. const aj = a.clone().lerp( c, i / cols );
  22994. const bj = b.clone().lerp( c, i / cols );
  22995. const rows = cols - i;
  22996. for ( let j = 0; j <= rows; j ++ ) {
  22997. if ( j === 0 && i === cols ) {
  22998. v[ i ][ j ] = aj;
  22999. } else {
  23000. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  23001. }
  23002. }
  23003. }
  23004. // construct all of the faces
  23005. for ( let i = 0; i < cols; i ++ ) {
  23006. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23007. const k = Math.floor( j / 2 );
  23008. if ( j % 2 === 0 ) {
  23009. pushVertex( v[ i ][ k + 1 ] );
  23010. pushVertex( v[ i + 1 ][ k ] );
  23011. pushVertex( v[ i ][ k ] );
  23012. } else {
  23013. pushVertex( v[ i ][ k + 1 ] );
  23014. pushVertex( v[ i + 1 ][ k + 1 ] );
  23015. pushVertex( v[ i + 1 ][ k ] );
  23016. }
  23017. }
  23018. }
  23019. }
  23020. function applyRadius( radius ) {
  23021. const vertex = new Vector3();
  23022. // iterate over the entire buffer and apply the radius to each vertex
  23023. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23024. vertex.x = vertexBuffer[ i + 0 ];
  23025. vertex.y = vertexBuffer[ i + 1 ];
  23026. vertex.z = vertexBuffer[ i + 2 ];
  23027. vertex.normalize().multiplyScalar( radius );
  23028. vertexBuffer[ i + 0 ] = vertex.x;
  23029. vertexBuffer[ i + 1 ] = vertex.y;
  23030. vertexBuffer[ i + 2 ] = vertex.z;
  23031. }
  23032. }
  23033. function generateUVs() {
  23034. const vertex = new Vector3();
  23035. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23036. vertex.x = vertexBuffer[ i + 0 ];
  23037. vertex.y = vertexBuffer[ i + 1 ];
  23038. vertex.z = vertexBuffer[ i + 2 ];
  23039. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  23040. const v = inclination( vertex ) / Math.PI + 0.5;
  23041. uvBuffer.push( u, 1 - v );
  23042. }
  23043. correctUVs();
  23044. correctSeam();
  23045. }
  23046. function correctSeam() {
  23047. // handle case when face straddles the seam, see #3269
  23048. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  23049. // uv data of a single face
  23050. const x0 = uvBuffer[ i + 0 ];
  23051. const x1 = uvBuffer[ i + 2 ];
  23052. const x2 = uvBuffer[ i + 4 ];
  23053. const max = Math.max( x0, x1, x2 );
  23054. const min = Math.min( x0, x1, x2 );
  23055. // 0.9 is somewhat arbitrary
  23056. if ( max > 0.9 && min < 0.1 ) {
  23057. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23058. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23059. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23060. }
  23061. }
  23062. }
  23063. function pushVertex( vertex ) {
  23064. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23065. }
  23066. function getVertexByIndex( index, vertex ) {
  23067. const stride = index * 3;
  23068. vertex.x = vertices[ stride + 0 ];
  23069. vertex.y = vertices[ stride + 1 ];
  23070. vertex.z = vertices[ stride + 2 ];
  23071. }
  23072. function correctUVs() {
  23073. const a = new Vector3();
  23074. const b = new Vector3();
  23075. const c = new Vector3();
  23076. const centroid = new Vector3();
  23077. const uvA = new Vector2();
  23078. const uvB = new Vector2();
  23079. const uvC = new Vector2();
  23080. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23081. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23082. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23083. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23084. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23085. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23086. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23087. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23088. const azi = azimuth( centroid );
  23089. correctUV( uvA, j + 0, a, azi );
  23090. correctUV( uvB, j + 2, b, azi );
  23091. correctUV( uvC, j + 4, c, azi );
  23092. }
  23093. }
  23094. function correctUV( uv, stride, vector, azimuth ) {
  23095. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23096. uvBuffer[ stride ] = uv.x - 1;
  23097. }
  23098. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23099. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23100. }
  23101. }
  23102. // Angle around the Y axis, counter-clockwise when looking from above.
  23103. function azimuth( vector ) {
  23104. return Math.atan2( vector.z, - vector.x );
  23105. }
  23106. // Angle above the XZ plane.
  23107. function inclination( vector ) {
  23108. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23109. }
  23110. }
  23111. copy( source ) {
  23112. super.copy( source );
  23113. this.parameters = Object.assign( {}, source.parameters );
  23114. return this;
  23115. }
  23116. /**
  23117. * Factory method for creating an instance of this class from the given
  23118. * JSON object.
  23119. *
  23120. * @param {Object} data - A JSON object representing the serialized geometry.
  23121. * @return {PolyhedronGeometry} A new instance.
  23122. */
  23123. static fromJSON( data ) {
  23124. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23125. }
  23126. }
  23127. /**
  23128. * A geometry class for representing a dodecahedron.
  23129. *
  23130. * ```js
  23131. * const geometry = new THREE.DodecahedronGeometry();
  23132. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23133. * const dodecahedron = new THREE.Mesh( geometry, material );
  23134. * scene.add( dodecahedron );
  23135. * ```
  23136. *
  23137. * @augments PolyhedronGeometry
  23138. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23139. */
  23140. class DodecahedronGeometry extends PolyhedronGeometry {
  23141. /**
  23142. * Constructs a new dodecahedron geometry.
  23143. *
  23144. * @param {number} [radius=1] - Radius of the dodecahedron.
  23145. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23146. */
  23147. constructor( radius = 1, detail = 0 ) {
  23148. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23149. const r = 1 / t;
  23150. const vertices = [
  23151. // (±1, ±1, ±1)
  23152. -1, -1, -1, -1, -1, 1,
  23153. -1, 1, -1, -1, 1, 1,
  23154. 1, -1, -1, 1, -1, 1,
  23155. 1, 1, -1, 1, 1, 1,
  23156. // (0, ±1/φ, ±φ)
  23157. 0, - r, - t, 0, - r, t,
  23158. 0, r, - t, 0, r, t,
  23159. // (±1/φ, ±φ, 0)
  23160. - r, - t, 0, - r, t, 0,
  23161. r, - t, 0, r, t, 0,
  23162. // (±φ, 0, ±1/φ)
  23163. - t, 0, - r, t, 0, - r,
  23164. - t, 0, r, t, 0, r
  23165. ];
  23166. const indices = [
  23167. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23168. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23169. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23170. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23171. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23172. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23173. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23174. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23175. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23176. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23177. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23178. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23179. ];
  23180. super( vertices, indices, radius, detail );
  23181. this.type = 'DodecahedronGeometry';
  23182. /**
  23183. * Holds the constructor parameters that have been
  23184. * used to generate the geometry. Any modification
  23185. * after instantiation does not change the geometry.
  23186. *
  23187. * @type {Object}
  23188. */
  23189. this.parameters = {
  23190. radius: radius,
  23191. detail: detail
  23192. };
  23193. }
  23194. /**
  23195. * Factory method for creating an instance of this class from the given
  23196. * JSON object.
  23197. *
  23198. * @param {Object} data - A JSON object representing the serialized geometry.
  23199. * @return {DodecahedronGeometry} A new instance.
  23200. */
  23201. static fromJSON( data ) {
  23202. return new DodecahedronGeometry( data.radius, data.detail );
  23203. }
  23204. }
  23205. const _v0$1 = /*@__PURE__*/ new Vector3();
  23206. const _v1$1 = /*@__PURE__*/ new Vector3();
  23207. const _normal = /*@__PURE__*/ new Vector3();
  23208. const _triangle = /*@__PURE__*/ new Triangle();
  23209. /**
  23210. * Can be used as a helper object to view the edges of a geometry.
  23211. *
  23212. * ```js
  23213. * const geometry = new THREE.BoxGeometry();
  23214. * const edges = new THREE.EdgesGeometry( geometry );
  23215. * const line = new THREE.LineSegments( edges );
  23216. * scene.add( line );
  23217. * ```
  23218. *
  23219. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23220. *
  23221. * @augments BufferGeometry
  23222. */
  23223. class EdgesGeometry extends BufferGeometry {
  23224. /**
  23225. * Constructs a new edges geometry.
  23226. *
  23227. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23228. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23229. * between the face normals of the adjoining faces exceeds this value.
  23230. */
  23231. constructor( geometry = null, thresholdAngle = 1 ) {
  23232. super();
  23233. this.type = 'EdgesGeometry';
  23234. /**
  23235. * Holds the constructor parameters that have been
  23236. * used to generate the geometry. Any modification
  23237. * after instantiation does not change the geometry.
  23238. *
  23239. * @type {Object}
  23240. */
  23241. this.parameters = {
  23242. geometry: geometry,
  23243. thresholdAngle: thresholdAngle
  23244. };
  23245. if ( geometry !== null ) {
  23246. const precisionPoints = 4;
  23247. const precision = Math.pow( 10, precisionPoints );
  23248. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23249. const indexAttr = geometry.getIndex();
  23250. const positionAttr = geometry.getAttribute( 'position' );
  23251. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23252. const indexArr = [ 0, 0, 0 ];
  23253. const vertKeys = [ 'a', 'b', 'c' ];
  23254. const hashes = new Array( 3 );
  23255. const edgeData = {};
  23256. const vertices = [];
  23257. for ( let i = 0; i < indexCount; i += 3 ) {
  23258. if ( indexAttr ) {
  23259. indexArr[ 0 ] = indexAttr.getX( i );
  23260. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23261. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23262. } else {
  23263. indexArr[ 0 ] = i;
  23264. indexArr[ 1 ] = i + 1;
  23265. indexArr[ 2 ] = i + 2;
  23266. }
  23267. const { a, b, c } = _triangle;
  23268. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23269. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23270. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23271. _triangle.getNormal( _normal );
  23272. // create hashes for the edge from the vertices
  23273. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23274. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23275. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23276. // skip degenerate triangles
  23277. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23278. continue;
  23279. }
  23280. // iterate over every edge
  23281. for ( let j = 0; j < 3; j ++ ) {
  23282. // get the first and next vertex making up the edge
  23283. const jNext = ( j + 1 ) % 3;
  23284. const vecHash0 = hashes[ j ];
  23285. const vecHash1 = hashes[ jNext ];
  23286. const v0 = _triangle[ vertKeys[ j ] ];
  23287. const v1 = _triangle[ vertKeys[ jNext ] ];
  23288. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23289. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23290. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23291. // if we found a sibling edge add it into the vertex array if
  23292. // it meets the angle threshold and delete the edge from the map.
  23293. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23294. vertices.push( v0.x, v0.y, v0.z );
  23295. vertices.push( v1.x, v1.y, v1.z );
  23296. }
  23297. edgeData[ reverseHash ] = null;
  23298. } else if ( ! ( hash in edgeData ) ) {
  23299. // if we've already got an edge here then skip adding a new one
  23300. edgeData[ hash ] = {
  23301. index0: indexArr[ j ],
  23302. index1: indexArr[ jNext ],
  23303. normal: _normal.clone(),
  23304. };
  23305. }
  23306. }
  23307. }
  23308. // iterate over all remaining, unmatched edges and add them to the vertex array
  23309. for ( const key in edgeData ) {
  23310. if ( edgeData[ key ] ) {
  23311. const { index0, index1 } = edgeData[ key ];
  23312. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23313. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23314. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23315. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23316. }
  23317. }
  23318. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23319. }
  23320. }
  23321. copy( source ) {
  23322. super.copy( source );
  23323. this.parameters = Object.assign( {}, source.parameters );
  23324. return this;
  23325. }
  23326. }
  23327. /**
  23328. * An abstract base class for creating an analytic curve object that contains methods
  23329. * for interpolation.
  23330. *
  23331. * @abstract
  23332. */
  23333. class Curve {
  23334. /**
  23335. * Constructs a new curve.
  23336. */
  23337. constructor() {
  23338. /**
  23339. * The type property is used for detecting the object type
  23340. * in context of serialization/deserialization.
  23341. *
  23342. * @type {string}
  23343. * @readonly
  23344. */
  23345. this.type = 'Curve';
  23346. /**
  23347. * This value determines the amount of divisions when calculating the
  23348. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23349. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23350. * recommended to increase the value of this property if the curve is very large.
  23351. *
  23352. * @type {number}
  23353. * @default 200
  23354. */
  23355. this.arcLengthDivisions = 200;
  23356. /**
  23357. * Must be set to `true` if the curve parameters have changed.
  23358. *
  23359. * @type {boolean}
  23360. * @default false
  23361. */
  23362. this.needsUpdate = false;
  23363. /**
  23364. * An internal cache that holds precomputed curve length values.
  23365. *
  23366. * @private
  23367. * @type {?Array<number>}
  23368. * @default null
  23369. */
  23370. this.cacheArcLengths = null;
  23371. }
  23372. /**
  23373. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23374. * for the given interpolation factor.
  23375. *
  23376. * @abstract
  23377. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23378. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23379. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23380. */
  23381. getPoint( /* t, optionalTarget */ ) {
  23382. warn( 'Curve: .getPoint() not implemented.' );
  23383. }
  23384. /**
  23385. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23386. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23387. * of the curve which equidistant samples.
  23388. *
  23389. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23390. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23391. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23392. */
  23393. getPointAt( u, optionalTarget ) {
  23394. const t = this.getUtoTmapping( u );
  23395. return this.getPoint( t, optionalTarget );
  23396. }
  23397. /**
  23398. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23399. * the curve shape.
  23400. *
  23401. * @param {number} [divisions=5] - The number of divisions.
  23402. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23403. */
  23404. getPoints( divisions = 5 ) {
  23405. const points = [];
  23406. for ( let d = 0; d <= divisions; d ++ ) {
  23407. points.push( this.getPoint( d / divisions ) );
  23408. }
  23409. return points;
  23410. }
  23411. // Get sequence of points using getPointAt( u )
  23412. /**
  23413. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23414. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23415. * curve.
  23416. *
  23417. * @param {number} [divisions=5] - The number of divisions.
  23418. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23419. */
  23420. getSpacedPoints( divisions = 5 ) {
  23421. const points = [];
  23422. for ( let d = 0; d <= divisions; d ++ ) {
  23423. points.push( this.getPointAt( d / divisions ) );
  23424. }
  23425. return points;
  23426. }
  23427. /**
  23428. * Returns the total arc length of the curve.
  23429. *
  23430. * @return {number} The length of the curve.
  23431. */
  23432. getLength() {
  23433. const lengths = this.getLengths();
  23434. return lengths[ lengths.length - 1 ];
  23435. }
  23436. /**
  23437. * Returns an array of cumulative segment lengths of the curve.
  23438. *
  23439. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23440. * @return {Array<number>} An array holding the cumulative segment lengths.
  23441. */
  23442. getLengths( divisions = this.arcLengthDivisions ) {
  23443. if ( this.cacheArcLengths &&
  23444. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23445. ! this.needsUpdate ) {
  23446. return this.cacheArcLengths;
  23447. }
  23448. this.needsUpdate = false;
  23449. const cache = [];
  23450. let current, last = this.getPoint( 0 );
  23451. let sum = 0;
  23452. cache.push( 0 );
  23453. for ( let p = 1; p <= divisions; p ++ ) {
  23454. current = this.getPoint( p / divisions );
  23455. sum += current.distanceTo( last );
  23456. cache.push( sum );
  23457. last = current;
  23458. }
  23459. this.cacheArcLengths = cache;
  23460. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23461. }
  23462. /**
  23463. * Update the cumulative segment distance cache. The method must be called
  23464. * every time curve parameters are changed. If an updated curve is part of a
  23465. * composed curve like {@link CurvePath}, this method must be called on the
  23466. * composed curve, too.
  23467. */
  23468. updateArcLengths() {
  23469. this.needsUpdate = true;
  23470. this.getLengths();
  23471. }
  23472. /**
  23473. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23474. * interpolation factor in the same range that can be ued to sample equidistant points
  23475. * from a curve.
  23476. *
  23477. * @param {number} u - The interpolation factor.
  23478. * @param {?number} distance - An optional distance on the curve.
  23479. * @return {number} The updated interpolation factor.
  23480. */
  23481. getUtoTmapping( u, distance = null ) {
  23482. const arcLengths = this.getLengths();
  23483. let i = 0;
  23484. const il = arcLengths.length;
  23485. let targetArcLength; // The targeted u distance value to get
  23486. if ( distance ) {
  23487. targetArcLength = distance;
  23488. } else {
  23489. targetArcLength = u * arcLengths[ il - 1 ];
  23490. }
  23491. // binary search for the index with largest value smaller than target u distance
  23492. let low = 0, high = il - 1, comparison;
  23493. while ( low <= high ) {
  23494. 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
  23495. comparison = arcLengths[ i ] - targetArcLength;
  23496. if ( comparison < 0 ) {
  23497. low = i + 1;
  23498. } else if ( comparison > 0 ) {
  23499. high = i - 1;
  23500. } else {
  23501. high = i;
  23502. break;
  23503. // DONE
  23504. }
  23505. }
  23506. i = high;
  23507. if ( arcLengths[ i ] === targetArcLength ) {
  23508. return i / ( il - 1 );
  23509. }
  23510. // we could get finer grain at lengths, or use simple interpolation between two points
  23511. const lengthBefore = arcLengths[ i ];
  23512. const lengthAfter = arcLengths[ i + 1 ];
  23513. const segmentLength = lengthAfter - lengthBefore;
  23514. // determine where we are between the 'before' and 'after' points
  23515. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23516. // add that fractional amount to t
  23517. const t = ( i + segmentFraction ) / ( il - 1 );
  23518. return t;
  23519. }
  23520. /**
  23521. * Returns a unit vector tangent for the given interpolation factor.
  23522. * If the derived curve does not implement its tangent derivation,
  23523. * two points a small delta apart will be used to find its gradient
  23524. * which seems to give a reasonable approximation.
  23525. *
  23526. * @param {number} t - The interpolation factor.
  23527. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23528. * @return {(Vector2|Vector3)} The tangent vector.
  23529. */
  23530. getTangent( t, optionalTarget ) {
  23531. const delta = 0.0001;
  23532. let t1 = t - delta;
  23533. let t2 = t + delta;
  23534. // Capping in case of danger
  23535. if ( t1 < 0 ) t1 = 0;
  23536. if ( t2 > 1 ) t2 = 1;
  23537. const pt1 = this.getPoint( t1 );
  23538. const pt2 = this.getPoint( t2 );
  23539. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23540. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23541. return tangent;
  23542. }
  23543. /**
  23544. * Same as {@link Curve#getTangent} but with equidistant samples.
  23545. *
  23546. * @param {number} u - The interpolation factor.
  23547. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23548. * @return {(Vector2|Vector3)} The tangent vector.
  23549. * @see {@link Curve#getPointAt}
  23550. */
  23551. getTangentAt( u, optionalTarget ) {
  23552. const t = this.getUtoTmapping( u );
  23553. return this.getTangent( t, optionalTarget );
  23554. }
  23555. /**
  23556. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23557. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23558. *
  23559. * @param {number} segments - The number of segments.
  23560. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23561. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23562. */
  23563. computeFrenetFrames( segments, closed = false ) {
  23564. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23565. const normal = new Vector3();
  23566. const tangents = [];
  23567. const normals = [];
  23568. const binormals = [];
  23569. const vec = new Vector3();
  23570. const mat = new Matrix4();
  23571. // compute the tangent vectors for each segment on the curve
  23572. for ( let i = 0; i <= segments; i ++ ) {
  23573. const u = i / segments;
  23574. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23575. }
  23576. // select an initial normal vector perpendicular to the first tangent vector,
  23577. // and in the direction of the minimum tangent xyz component
  23578. normals[ 0 ] = new Vector3();
  23579. binormals[ 0 ] = new Vector3();
  23580. let min = Number.MAX_VALUE;
  23581. const tx = Math.abs( tangents[ 0 ].x );
  23582. const ty = Math.abs( tangents[ 0 ].y );
  23583. const tz = Math.abs( tangents[ 0 ].z );
  23584. if ( tx <= min ) {
  23585. min = tx;
  23586. normal.set( 1, 0, 0 );
  23587. }
  23588. if ( ty <= min ) {
  23589. min = ty;
  23590. normal.set( 0, 1, 0 );
  23591. }
  23592. if ( tz <= min ) {
  23593. normal.set( 0, 0, 1 );
  23594. }
  23595. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23596. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23597. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23598. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23599. for ( let i = 1; i <= segments; i ++ ) {
  23600. normals[ i ] = normals[ i - 1 ].clone();
  23601. binormals[ i ] = binormals[ i - 1 ].clone();
  23602. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23603. if ( vec.length() > Number.EPSILON ) {
  23604. vec.normalize();
  23605. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23606. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23607. }
  23608. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23609. }
  23610. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23611. if ( closed === true ) {
  23612. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23613. theta /= segments;
  23614. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23615. theta = - theta;
  23616. }
  23617. for ( let i = 1; i <= segments; i ++ ) {
  23618. // twist a little...
  23619. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23620. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23621. }
  23622. }
  23623. return {
  23624. tangents: tangents,
  23625. normals: normals,
  23626. binormals: binormals
  23627. };
  23628. }
  23629. /**
  23630. * Returns a new curve with copied values from this instance.
  23631. *
  23632. * @return {Curve} A clone of this instance.
  23633. */
  23634. clone() {
  23635. return new this.constructor().copy( this );
  23636. }
  23637. /**
  23638. * Copies the values of the given curve to this instance.
  23639. *
  23640. * @param {Curve} source - The curve to copy.
  23641. * @return {Curve} A reference to this curve.
  23642. */
  23643. copy( source ) {
  23644. this.arcLengthDivisions = source.arcLengthDivisions;
  23645. return this;
  23646. }
  23647. /**
  23648. * Serializes the curve into JSON.
  23649. *
  23650. * @return {Object} A JSON object representing the serialized curve.
  23651. * @see {@link ObjectLoader#parse}
  23652. */
  23653. toJSON() {
  23654. const data = {
  23655. metadata: {
  23656. version: 4.7,
  23657. type: 'Curve',
  23658. generator: 'Curve.toJSON'
  23659. }
  23660. };
  23661. data.arcLengthDivisions = this.arcLengthDivisions;
  23662. data.type = this.type;
  23663. return data;
  23664. }
  23665. /**
  23666. * Deserializes the curve from the given JSON.
  23667. *
  23668. * @param {Object} json - The JSON holding the serialized curve.
  23669. * @return {Curve} A reference to this curve.
  23670. */
  23671. fromJSON( json ) {
  23672. this.arcLengthDivisions = json.arcLengthDivisions;
  23673. return this;
  23674. }
  23675. }
  23676. /**
  23677. * A curve representing an ellipse.
  23678. *
  23679. * ```js
  23680. * const curve = new THREE.EllipseCurve(
  23681. * 0, 0,
  23682. * 10, 10,
  23683. * 0, 2 * Math.PI,
  23684. * false,
  23685. * 0
  23686. * );
  23687. *
  23688. * const points = curve.getPoints( 50 );
  23689. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23690. *
  23691. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23692. *
  23693. * // Create the final object to add to the scene
  23694. * const ellipse = new THREE.Line( geometry, material );
  23695. * ```
  23696. *
  23697. * @augments Curve
  23698. */
  23699. class EllipseCurve extends Curve {
  23700. /**
  23701. * Constructs a new ellipse curve.
  23702. *
  23703. * @param {number} [aX=0] - The X center of the ellipse.
  23704. * @param {number} [aY=0] - The Y center of the ellipse.
  23705. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23706. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23707. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23708. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23709. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23710. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23711. */
  23712. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23713. super();
  23714. /**
  23715. * This flag can be used for type testing.
  23716. *
  23717. * @type {boolean}
  23718. * @readonly
  23719. * @default true
  23720. */
  23721. this.isEllipseCurve = true;
  23722. this.type = 'EllipseCurve';
  23723. /**
  23724. * The X center of the ellipse.
  23725. *
  23726. * @type {number}
  23727. * @default 0
  23728. */
  23729. this.aX = aX;
  23730. /**
  23731. * The Y center of the ellipse.
  23732. *
  23733. * @type {number}
  23734. * @default 0
  23735. */
  23736. this.aY = aY;
  23737. /**
  23738. * The radius of the ellipse in the x direction.
  23739. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23740. *
  23741. * @type {number}
  23742. * @default 1
  23743. */
  23744. this.xRadius = xRadius;
  23745. /**
  23746. * The radius of the ellipse in the y direction.
  23747. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23748. *
  23749. * @type {number}
  23750. * @default 1
  23751. */
  23752. this.yRadius = yRadius;
  23753. /**
  23754. * The start angle of the curve in radians starting from the positive X axis.
  23755. *
  23756. * @type {number}
  23757. * @default 0
  23758. */
  23759. this.aStartAngle = aStartAngle;
  23760. /**
  23761. * The end angle of the curve in radians starting from the positive X axis.
  23762. *
  23763. * @type {number}
  23764. * @default Math.PI*2
  23765. */
  23766. this.aEndAngle = aEndAngle;
  23767. /**
  23768. * Whether the ellipse is drawn clockwise or not.
  23769. *
  23770. * @type {boolean}
  23771. * @default false
  23772. */
  23773. this.aClockwise = aClockwise;
  23774. /**
  23775. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23776. *
  23777. * @type {number}
  23778. * @default 0
  23779. */
  23780. this.aRotation = aRotation;
  23781. }
  23782. /**
  23783. * Returns a point on the curve.
  23784. *
  23785. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23786. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23787. * @return {Vector2} The position on the curve.
  23788. */
  23789. getPoint( t, optionalTarget = new Vector2() ) {
  23790. const point = optionalTarget;
  23791. const twoPi = Math.PI * 2;
  23792. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23793. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23794. // ensures that deltaAngle is 0 .. 2 PI
  23795. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23796. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23797. if ( deltaAngle < Number.EPSILON ) {
  23798. if ( samePoints ) {
  23799. deltaAngle = 0;
  23800. } else {
  23801. deltaAngle = twoPi;
  23802. }
  23803. }
  23804. if ( this.aClockwise === true && ! samePoints ) {
  23805. if ( deltaAngle === twoPi ) {
  23806. deltaAngle = - twoPi;
  23807. } else {
  23808. deltaAngle = deltaAngle - twoPi;
  23809. }
  23810. }
  23811. const angle = this.aStartAngle + t * deltaAngle;
  23812. let x = this.aX + this.xRadius * Math.cos( angle );
  23813. let y = this.aY + this.yRadius * Math.sin( angle );
  23814. if ( this.aRotation !== 0 ) {
  23815. const cos = Math.cos( this.aRotation );
  23816. const sin = Math.sin( this.aRotation );
  23817. const tx = x - this.aX;
  23818. const ty = y - this.aY;
  23819. // Rotate the point about the center of the ellipse.
  23820. x = tx * cos - ty * sin + this.aX;
  23821. y = tx * sin + ty * cos + this.aY;
  23822. }
  23823. return point.set( x, y );
  23824. }
  23825. copy( source ) {
  23826. super.copy( source );
  23827. this.aX = source.aX;
  23828. this.aY = source.aY;
  23829. this.xRadius = source.xRadius;
  23830. this.yRadius = source.yRadius;
  23831. this.aStartAngle = source.aStartAngle;
  23832. this.aEndAngle = source.aEndAngle;
  23833. this.aClockwise = source.aClockwise;
  23834. this.aRotation = source.aRotation;
  23835. return this;
  23836. }
  23837. toJSON() {
  23838. const data = super.toJSON();
  23839. data.aX = this.aX;
  23840. data.aY = this.aY;
  23841. data.xRadius = this.xRadius;
  23842. data.yRadius = this.yRadius;
  23843. data.aStartAngle = this.aStartAngle;
  23844. data.aEndAngle = this.aEndAngle;
  23845. data.aClockwise = this.aClockwise;
  23846. data.aRotation = this.aRotation;
  23847. return data;
  23848. }
  23849. fromJSON( json ) {
  23850. super.fromJSON( json );
  23851. this.aX = json.aX;
  23852. this.aY = json.aY;
  23853. this.xRadius = json.xRadius;
  23854. this.yRadius = json.yRadius;
  23855. this.aStartAngle = json.aStartAngle;
  23856. this.aEndAngle = json.aEndAngle;
  23857. this.aClockwise = json.aClockwise;
  23858. this.aRotation = json.aRotation;
  23859. return this;
  23860. }
  23861. }
  23862. /**
  23863. * A curve representing an arc.
  23864. *
  23865. * @augments EllipseCurve
  23866. */
  23867. class ArcCurve extends EllipseCurve {
  23868. /**
  23869. * Constructs a new arc curve.
  23870. *
  23871. * @param {number} [aX=0] - The X center of the ellipse.
  23872. * @param {number} [aY=0] - The Y center of the ellipse.
  23873. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23874. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23875. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23876. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23877. */
  23878. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23879. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23880. /**
  23881. * This flag can be used for type testing.
  23882. *
  23883. * @type {boolean}
  23884. * @readonly
  23885. * @default true
  23886. */
  23887. this.isArcCurve = true;
  23888. this.type = 'ArcCurve';
  23889. }
  23890. }
  23891. function CubicPoly() {
  23892. /**
  23893. * Centripetal CatmullRom Curve - which is useful for avoiding
  23894. * cusps and self-intersections in non-uniform catmull rom curves.
  23895. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23896. *
  23897. * curve.type accepts centripetal(default), chordal and catmullrom
  23898. * curve.tension is used for catmullrom which defaults to 0.5
  23899. */
  23900. /*
  23901. Based on an optimized c++ solution in
  23902. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23903. - http://ideone.com/NoEbVM
  23904. This CubicPoly class could be used for reusing some variables and calculations,
  23905. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23906. which can be placed in CurveUtils.
  23907. */
  23908. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23909. /*
  23910. * Compute coefficients for a cubic polynomial
  23911. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23912. * such that
  23913. * p(0) = x0, p(1) = x1
  23914. * and
  23915. * p'(0) = t0, p'(1) = t1.
  23916. */
  23917. function init( x0, x1, t0, t1 ) {
  23918. c0 = x0;
  23919. c1 = t0;
  23920. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23921. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23922. }
  23923. return {
  23924. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23925. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23926. },
  23927. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23928. // compute tangents when parameterized in [t1,t2]
  23929. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23930. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23931. // rescale tangents for parametrization in [0,1]
  23932. t1 *= dt1;
  23933. t2 *= dt1;
  23934. init( x1, x2, t1, t2 );
  23935. },
  23936. calc: function ( t ) {
  23937. const t2 = t * t;
  23938. const t3 = t2 * t;
  23939. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23940. }
  23941. };
  23942. }
  23943. //
  23944. const tmp = /*@__PURE__*/ new Vector3();
  23945. const px = /*@__PURE__*/ new CubicPoly();
  23946. const py = /*@__PURE__*/ new CubicPoly();
  23947. const pz = /*@__PURE__*/ new CubicPoly();
  23948. /**
  23949. * A curve representing a Catmull-Rom spline.
  23950. *
  23951. * ```js
  23952. * //Create a closed wavey loop
  23953. * const curve = new THREE.CatmullRomCurve3( [
  23954. * new THREE.Vector3( -10, 0, 10 ),
  23955. * new THREE.Vector3( -5, 5, 5 ),
  23956. * new THREE.Vector3( 0, 0, 0 ),
  23957. * new THREE.Vector3( 5, -5, 5 ),
  23958. * new THREE.Vector3( 10, 0, 10 )
  23959. * ] );
  23960. *
  23961. * const points = curve.getPoints( 50 );
  23962. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23963. *
  23964. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23965. *
  23966. * // Create the final object to add to the scene
  23967. * const curveObject = new THREE.Line( geometry, material );
  23968. * ```
  23969. *
  23970. * @augments Curve
  23971. */
  23972. class CatmullRomCurve3 extends Curve {
  23973. /**
  23974. * Constructs a new Catmull-Rom curve.
  23975. *
  23976. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23977. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23978. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23979. * @param {number} [tension=0.5] - Tension of the curve.
  23980. */
  23981. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23982. super();
  23983. /**
  23984. * This flag can be used for type testing.
  23985. *
  23986. * @type {boolean}
  23987. * @readonly
  23988. * @default true
  23989. */
  23990. this.isCatmullRomCurve3 = true;
  23991. this.type = 'CatmullRomCurve3';
  23992. /**
  23993. * An array of 3D points defining the curve.
  23994. *
  23995. * @type {Array<Vector3>}
  23996. */
  23997. this.points = points;
  23998. /**
  23999. * Whether the curve is closed or not.
  24000. *
  24001. * @type {boolean}
  24002. * @default false
  24003. */
  24004. this.closed = closed;
  24005. /**
  24006. * The curve type.
  24007. *
  24008. * @type {('centripetal'|'chordal'|'catmullrom')}
  24009. * @default 'centripetal'
  24010. */
  24011. this.curveType = curveType;
  24012. /**
  24013. * Tension of the curve.
  24014. *
  24015. * @type {number}
  24016. * @default 0.5
  24017. */
  24018. this.tension = tension;
  24019. }
  24020. /**
  24021. * Returns a point on the curve.
  24022. *
  24023. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24024. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24025. * @return {Vector3} The position on the curve.
  24026. */
  24027. getPoint( t, optionalTarget = new Vector3() ) {
  24028. const point = optionalTarget;
  24029. const points = this.points;
  24030. const l = points.length;
  24031. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24032. let intPoint = Math.floor( p );
  24033. let weight = p - intPoint;
  24034. if ( this.closed ) {
  24035. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  24036. } else if ( weight === 0 && intPoint === l - 1 ) {
  24037. intPoint = l - 2;
  24038. weight = 1;
  24039. }
  24040. let p0, p3; // 4 points (p1 & p2 defined below)
  24041. if ( this.closed || intPoint > 0 ) {
  24042. p0 = points[ ( intPoint - 1 ) % l ];
  24043. } else {
  24044. // extrapolate first point
  24045. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24046. p0 = tmp;
  24047. }
  24048. const p1 = points[ intPoint % l ];
  24049. const p2 = points[ ( intPoint + 1 ) % l ];
  24050. if ( this.closed || intPoint + 2 < l ) {
  24051. p3 = points[ ( intPoint + 2 ) % l ];
  24052. } else {
  24053. // extrapolate last point
  24054. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24055. p3 = tmp;
  24056. }
  24057. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24058. // init Centripetal / Chordal Catmull-Rom
  24059. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24060. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24061. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24062. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24063. // safety check for repeated points
  24064. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24065. if ( dt0 < 1e-4 ) dt0 = dt1;
  24066. if ( dt2 < 1e-4 ) dt2 = dt1;
  24067. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24068. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24069. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24070. } else if ( this.curveType === 'catmullrom' ) {
  24071. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24072. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24073. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24074. }
  24075. point.set(
  24076. px.calc( weight ),
  24077. py.calc( weight ),
  24078. pz.calc( weight )
  24079. );
  24080. return point;
  24081. }
  24082. copy( source ) {
  24083. super.copy( source );
  24084. this.points = [];
  24085. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24086. const point = source.points[ i ];
  24087. this.points.push( point.clone() );
  24088. }
  24089. this.closed = source.closed;
  24090. this.curveType = source.curveType;
  24091. this.tension = source.tension;
  24092. return this;
  24093. }
  24094. toJSON() {
  24095. const data = super.toJSON();
  24096. data.points = [];
  24097. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24098. const point = this.points[ i ];
  24099. data.points.push( point.toArray() );
  24100. }
  24101. data.closed = this.closed;
  24102. data.curveType = this.curveType;
  24103. data.tension = this.tension;
  24104. return data;
  24105. }
  24106. fromJSON( json ) {
  24107. super.fromJSON( json );
  24108. this.points = [];
  24109. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24110. const point = json.points[ i ];
  24111. this.points.push( new Vector3().fromArray( point ) );
  24112. }
  24113. this.closed = json.closed;
  24114. this.curveType = json.curveType;
  24115. this.tension = json.tension;
  24116. return this;
  24117. }
  24118. }
  24119. /**
  24120. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24121. *
  24122. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24123. *
  24124. * @module Interpolations
  24125. */
  24126. /**
  24127. * Computes a point on a Catmull-Rom spline.
  24128. *
  24129. * @param {number} t - The interpolation factor.
  24130. * @param {number} p0 - The first control point.
  24131. * @param {number} p1 - The second control point.
  24132. * @param {number} p2 - The third control point.
  24133. * @param {number} p3 - The fourth control point.
  24134. * @return {number} The calculated point on a Catmull-Rom spline.
  24135. */
  24136. function CatmullRom( t, p0, p1, p2, p3 ) {
  24137. const v0 = ( p2 - p0 ) * 0.5;
  24138. const v1 = ( p3 - p1 ) * 0.5;
  24139. const t2 = t * t;
  24140. const t3 = t * t2;
  24141. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24142. }
  24143. //
  24144. function QuadraticBezierP0( t, p ) {
  24145. const k = 1 - t;
  24146. return k * k * p;
  24147. }
  24148. function QuadraticBezierP1( t, p ) {
  24149. return 2 * ( 1 - t ) * t * p;
  24150. }
  24151. function QuadraticBezierP2( t, p ) {
  24152. return t * t * p;
  24153. }
  24154. /**
  24155. * Computes a point on a Quadratic Bezier curve.
  24156. *
  24157. * @param {number} t - The interpolation factor.
  24158. * @param {number} p0 - The first control point.
  24159. * @param {number} p1 - The second control point.
  24160. * @param {number} p2 - The third control point.
  24161. * @return {number} The calculated point on a Quadratic Bezier curve.
  24162. */
  24163. function QuadraticBezier( t, p0, p1, p2 ) {
  24164. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24165. QuadraticBezierP2( t, p2 );
  24166. }
  24167. //
  24168. function CubicBezierP0( t, p ) {
  24169. const k = 1 - t;
  24170. return k * k * k * p;
  24171. }
  24172. function CubicBezierP1( t, p ) {
  24173. const k = 1 - t;
  24174. return 3 * k * k * t * p;
  24175. }
  24176. function CubicBezierP2( t, p ) {
  24177. return 3 * ( 1 - t ) * t * t * p;
  24178. }
  24179. function CubicBezierP3( t, p ) {
  24180. return t * t * t * p;
  24181. }
  24182. /**
  24183. * Computes a point on a Cubic Bezier curve.
  24184. *
  24185. * @param {number} t - The interpolation factor.
  24186. * @param {number} p0 - The first control point.
  24187. * @param {number} p1 - The second control point.
  24188. * @param {number} p2 - The third control point.
  24189. * @param {number} p3 - The fourth control point.
  24190. * @return {number} The calculated point on a Cubic Bezier curve.
  24191. */
  24192. function CubicBezier( t, p0, p1, p2, p3 ) {
  24193. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24194. CubicBezierP3( t, p3 );
  24195. }
  24196. /**
  24197. * A curve representing a 2D Cubic Bezier curve.
  24198. *
  24199. * ```js
  24200. * const curve = new THREE.CubicBezierCurve(
  24201. * new THREE.Vector2( - 0, 0 ),
  24202. * new THREE.Vector2( - 5, 15 ),
  24203. * new THREE.Vector2( 20, 15 ),
  24204. * new THREE.Vector2( 10, 0 )
  24205. * );
  24206. *
  24207. * const points = curve.getPoints( 50 );
  24208. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24209. *
  24210. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24211. *
  24212. * // Create the final object to add to the scene
  24213. * const curveObject = new THREE.Line( geometry, material );
  24214. * ```
  24215. *
  24216. * @augments Curve
  24217. */
  24218. class CubicBezierCurve extends Curve {
  24219. /**
  24220. * Constructs a new Cubic Bezier curve.
  24221. *
  24222. * @param {Vector2} [v0] - The start point.
  24223. * @param {Vector2} [v1] - The first control point.
  24224. * @param {Vector2} [v2] - The second control point.
  24225. * @param {Vector2} [v3] - The end point.
  24226. */
  24227. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24228. super();
  24229. /**
  24230. * This flag can be used for type testing.
  24231. *
  24232. * @type {boolean}
  24233. * @readonly
  24234. * @default true
  24235. */
  24236. this.isCubicBezierCurve = true;
  24237. this.type = 'CubicBezierCurve';
  24238. /**
  24239. * The start point.
  24240. *
  24241. * @type {Vector2}
  24242. */
  24243. this.v0 = v0;
  24244. /**
  24245. * The first control point.
  24246. *
  24247. * @type {Vector2}
  24248. */
  24249. this.v1 = v1;
  24250. /**
  24251. * The second control point.
  24252. *
  24253. * @type {Vector2}
  24254. */
  24255. this.v2 = v2;
  24256. /**
  24257. * The end point.
  24258. *
  24259. * @type {Vector2}
  24260. */
  24261. this.v3 = v3;
  24262. }
  24263. /**
  24264. * Returns a point on the curve.
  24265. *
  24266. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24267. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24268. * @return {Vector2} The position on the curve.
  24269. */
  24270. getPoint( t, optionalTarget = new Vector2() ) {
  24271. const point = optionalTarget;
  24272. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24273. point.set(
  24274. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24275. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24276. );
  24277. return point;
  24278. }
  24279. copy( source ) {
  24280. super.copy( source );
  24281. this.v0.copy( source.v0 );
  24282. this.v1.copy( source.v1 );
  24283. this.v2.copy( source.v2 );
  24284. this.v3.copy( source.v3 );
  24285. return this;
  24286. }
  24287. toJSON() {
  24288. const data = super.toJSON();
  24289. data.v0 = this.v0.toArray();
  24290. data.v1 = this.v1.toArray();
  24291. data.v2 = this.v2.toArray();
  24292. data.v3 = this.v3.toArray();
  24293. return data;
  24294. }
  24295. fromJSON( json ) {
  24296. super.fromJSON( json );
  24297. this.v0.fromArray( json.v0 );
  24298. this.v1.fromArray( json.v1 );
  24299. this.v2.fromArray( json.v2 );
  24300. this.v3.fromArray( json.v3 );
  24301. return this;
  24302. }
  24303. }
  24304. /**
  24305. * A curve representing a 3D Cubic Bezier curve.
  24306. *
  24307. * @augments Curve
  24308. */
  24309. class CubicBezierCurve3 extends Curve {
  24310. /**
  24311. * Constructs a new Cubic Bezier curve.
  24312. *
  24313. * @param {Vector3} [v0] - The start point.
  24314. * @param {Vector3} [v1] - The first control point.
  24315. * @param {Vector3} [v2] - The second control point.
  24316. * @param {Vector3} [v3] - The end point.
  24317. */
  24318. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24319. super();
  24320. /**
  24321. * This flag can be used for type testing.
  24322. *
  24323. * @type {boolean}
  24324. * @readonly
  24325. * @default true
  24326. */
  24327. this.isCubicBezierCurve3 = true;
  24328. this.type = 'CubicBezierCurve3';
  24329. /**
  24330. * The start point.
  24331. *
  24332. * @type {Vector3}
  24333. */
  24334. this.v0 = v0;
  24335. /**
  24336. * The first control point.
  24337. *
  24338. * @type {Vector3}
  24339. */
  24340. this.v1 = v1;
  24341. /**
  24342. * The second control point.
  24343. *
  24344. * @type {Vector3}
  24345. */
  24346. this.v2 = v2;
  24347. /**
  24348. * The end point.
  24349. *
  24350. * @type {Vector3}
  24351. */
  24352. this.v3 = v3;
  24353. }
  24354. /**
  24355. * Returns a point on the curve.
  24356. *
  24357. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24358. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24359. * @return {Vector3} The position on the curve.
  24360. */
  24361. getPoint( t, optionalTarget = new Vector3() ) {
  24362. const point = optionalTarget;
  24363. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24364. point.set(
  24365. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24366. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24367. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24368. );
  24369. return point;
  24370. }
  24371. copy( source ) {
  24372. super.copy( source );
  24373. this.v0.copy( source.v0 );
  24374. this.v1.copy( source.v1 );
  24375. this.v2.copy( source.v2 );
  24376. this.v3.copy( source.v3 );
  24377. return this;
  24378. }
  24379. toJSON() {
  24380. const data = super.toJSON();
  24381. data.v0 = this.v0.toArray();
  24382. data.v1 = this.v1.toArray();
  24383. data.v2 = this.v2.toArray();
  24384. data.v3 = this.v3.toArray();
  24385. return data;
  24386. }
  24387. fromJSON( json ) {
  24388. super.fromJSON( json );
  24389. this.v0.fromArray( json.v0 );
  24390. this.v1.fromArray( json.v1 );
  24391. this.v2.fromArray( json.v2 );
  24392. this.v3.fromArray( json.v3 );
  24393. return this;
  24394. }
  24395. }
  24396. /**
  24397. * A curve representing a 2D line segment.
  24398. *
  24399. * @augments Curve
  24400. */
  24401. class LineCurve extends Curve {
  24402. /**
  24403. * Constructs a new line curve.
  24404. *
  24405. * @param {Vector2} [v1] - The start point.
  24406. * @param {Vector2} [v2] - The end point.
  24407. */
  24408. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24409. super();
  24410. /**
  24411. * This flag can be used for type testing.
  24412. *
  24413. * @type {boolean}
  24414. * @readonly
  24415. * @default true
  24416. */
  24417. this.isLineCurve = true;
  24418. this.type = 'LineCurve';
  24419. /**
  24420. * The start point.
  24421. *
  24422. * @type {Vector2}
  24423. */
  24424. this.v1 = v1;
  24425. /**
  24426. * The end point.
  24427. *
  24428. * @type {Vector2}
  24429. */
  24430. this.v2 = v2;
  24431. }
  24432. /**
  24433. * Returns a point on the line.
  24434. *
  24435. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24436. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24437. * @return {Vector2} The position on the line.
  24438. */
  24439. getPoint( t, optionalTarget = new Vector2() ) {
  24440. const point = optionalTarget;
  24441. if ( t === 1 ) {
  24442. point.copy( this.v2 );
  24443. } else {
  24444. point.copy( this.v2 ).sub( this.v1 );
  24445. point.multiplyScalar( t ).add( this.v1 );
  24446. }
  24447. return point;
  24448. }
  24449. // Line curve is linear, so we can overwrite default getPointAt
  24450. getPointAt( u, optionalTarget ) {
  24451. return this.getPoint( u, optionalTarget );
  24452. }
  24453. getTangent( t, optionalTarget = new Vector2() ) {
  24454. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24455. }
  24456. getTangentAt( u, optionalTarget ) {
  24457. return this.getTangent( u, optionalTarget );
  24458. }
  24459. copy( source ) {
  24460. super.copy( source );
  24461. this.v1.copy( source.v1 );
  24462. this.v2.copy( source.v2 );
  24463. return this;
  24464. }
  24465. toJSON() {
  24466. const data = super.toJSON();
  24467. data.v1 = this.v1.toArray();
  24468. data.v2 = this.v2.toArray();
  24469. return data;
  24470. }
  24471. fromJSON( json ) {
  24472. super.fromJSON( json );
  24473. this.v1.fromArray( json.v1 );
  24474. this.v2.fromArray( json.v2 );
  24475. return this;
  24476. }
  24477. }
  24478. /**
  24479. * A curve representing a 3D line segment.
  24480. *
  24481. * @augments Curve
  24482. */
  24483. class LineCurve3 extends Curve {
  24484. /**
  24485. * Constructs a new line curve.
  24486. *
  24487. * @param {Vector3} [v1] - The start point.
  24488. * @param {Vector3} [v2] - The end point.
  24489. */
  24490. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24491. super();
  24492. /**
  24493. * This flag can be used for type testing.
  24494. *
  24495. * @type {boolean}
  24496. * @readonly
  24497. * @default true
  24498. */
  24499. this.isLineCurve3 = true;
  24500. this.type = 'LineCurve3';
  24501. /**
  24502. * The start point.
  24503. *
  24504. * @type {Vector3}
  24505. */
  24506. this.v1 = v1;
  24507. /**
  24508. * The end point.
  24509. *
  24510. * @type {Vector2}
  24511. */
  24512. this.v2 = v2;
  24513. }
  24514. /**
  24515. * Returns a point on the line.
  24516. *
  24517. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24518. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24519. * @return {Vector3} The position on the line.
  24520. */
  24521. getPoint( t, optionalTarget = new Vector3() ) {
  24522. const point = optionalTarget;
  24523. if ( t === 1 ) {
  24524. point.copy( this.v2 );
  24525. } else {
  24526. point.copy( this.v2 ).sub( this.v1 );
  24527. point.multiplyScalar( t ).add( this.v1 );
  24528. }
  24529. return point;
  24530. }
  24531. // Line curve is linear, so we can overwrite default getPointAt
  24532. getPointAt( u, optionalTarget ) {
  24533. return this.getPoint( u, optionalTarget );
  24534. }
  24535. getTangent( t, optionalTarget = new Vector3() ) {
  24536. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24537. }
  24538. getTangentAt( u, optionalTarget ) {
  24539. return this.getTangent( u, optionalTarget );
  24540. }
  24541. copy( source ) {
  24542. super.copy( source );
  24543. this.v1.copy( source.v1 );
  24544. this.v2.copy( source.v2 );
  24545. return this;
  24546. }
  24547. toJSON() {
  24548. const data = super.toJSON();
  24549. data.v1 = this.v1.toArray();
  24550. data.v2 = this.v2.toArray();
  24551. return data;
  24552. }
  24553. fromJSON( json ) {
  24554. super.fromJSON( json );
  24555. this.v1.fromArray( json.v1 );
  24556. this.v2.fromArray( json.v2 );
  24557. return this;
  24558. }
  24559. }
  24560. /**
  24561. * A curve representing a 2D Quadratic Bezier curve.
  24562. *
  24563. * ```js
  24564. * const curve = new THREE.QuadraticBezierCurve(
  24565. * new THREE.Vector2( - 10, 0 ),
  24566. * new THREE.Vector2( 20, 15 ),
  24567. * new THREE.Vector2( 10, 0 )
  24568. * )
  24569. *
  24570. * const points = curve.getPoints( 50 );
  24571. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24572. *
  24573. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24574. *
  24575. * // Create the final object to add to the scene
  24576. * const curveObject = new THREE.Line( geometry, material );
  24577. * ```
  24578. *
  24579. * @augments Curve
  24580. */
  24581. class QuadraticBezierCurve extends Curve {
  24582. /**
  24583. * Constructs a new Quadratic Bezier curve.
  24584. *
  24585. * @param {Vector2} [v0] - The start point.
  24586. * @param {Vector2} [v1] - The control point.
  24587. * @param {Vector2} [v2] - The end point.
  24588. */
  24589. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24590. super();
  24591. /**
  24592. * This flag can be used for type testing.
  24593. *
  24594. * @type {boolean}
  24595. * @readonly
  24596. * @default true
  24597. */
  24598. this.isQuadraticBezierCurve = true;
  24599. this.type = 'QuadraticBezierCurve';
  24600. /**
  24601. * The start point.
  24602. *
  24603. * @type {Vector2}
  24604. */
  24605. this.v0 = v0;
  24606. /**
  24607. * The control point.
  24608. *
  24609. * @type {Vector2}
  24610. */
  24611. this.v1 = v1;
  24612. /**
  24613. * The end point.
  24614. *
  24615. * @type {Vector2}
  24616. */
  24617. this.v2 = v2;
  24618. }
  24619. /**
  24620. * Returns a point on the curve.
  24621. *
  24622. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24623. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24624. * @return {Vector2} The position on the curve.
  24625. */
  24626. getPoint( t, optionalTarget = new Vector2() ) {
  24627. const point = optionalTarget;
  24628. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24629. point.set(
  24630. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24631. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24632. );
  24633. return point;
  24634. }
  24635. copy( source ) {
  24636. super.copy( source );
  24637. this.v0.copy( source.v0 );
  24638. this.v1.copy( source.v1 );
  24639. this.v2.copy( source.v2 );
  24640. return this;
  24641. }
  24642. toJSON() {
  24643. const data = super.toJSON();
  24644. data.v0 = this.v0.toArray();
  24645. data.v1 = this.v1.toArray();
  24646. data.v2 = this.v2.toArray();
  24647. return data;
  24648. }
  24649. fromJSON( json ) {
  24650. super.fromJSON( json );
  24651. this.v0.fromArray( json.v0 );
  24652. this.v1.fromArray( json.v1 );
  24653. this.v2.fromArray( json.v2 );
  24654. return this;
  24655. }
  24656. }
  24657. /**
  24658. * A curve representing a 3D Quadratic Bezier curve.
  24659. *
  24660. * @augments Curve
  24661. */
  24662. class QuadraticBezierCurve3 extends Curve {
  24663. /**
  24664. * Constructs a new Quadratic Bezier curve.
  24665. *
  24666. * @param {Vector3} [v0] - The start point.
  24667. * @param {Vector3} [v1] - The control point.
  24668. * @param {Vector3} [v2] - The end point.
  24669. */
  24670. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24671. super();
  24672. /**
  24673. * This flag can be used for type testing.
  24674. *
  24675. * @type {boolean}
  24676. * @readonly
  24677. * @default true
  24678. */
  24679. this.isQuadraticBezierCurve3 = true;
  24680. this.type = 'QuadraticBezierCurve3';
  24681. /**
  24682. * The start point.
  24683. *
  24684. * @type {Vector3}
  24685. */
  24686. this.v0 = v0;
  24687. /**
  24688. * The control point.
  24689. *
  24690. * @type {Vector3}
  24691. */
  24692. this.v1 = v1;
  24693. /**
  24694. * The end point.
  24695. *
  24696. * @type {Vector3}
  24697. */
  24698. this.v2 = v2;
  24699. }
  24700. /**
  24701. * Returns a point on the curve.
  24702. *
  24703. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24704. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24705. * @return {Vector3} The position on the curve.
  24706. */
  24707. getPoint( t, optionalTarget = new Vector3() ) {
  24708. const point = optionalTarget;
  24709. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24710. point.set(
  24711. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24712. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24713. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24714. );
  24715. return point;
  24716. }
  24717. copy( source ) {
  24718. super.copy( source );
  24719. this.v0.copy( source.v0 );
  24720. this.v1.copy( source.v1 );
  24721. this.v2.copy( source.v2 );
  24722. return this;
  24723. }
  24724. toJSON() {
  24725. const data = super.toJSON();
  24726. data.v0 = this.v0.toArray();
  24727. data.v1 = this.v1.toArray();
  24728. data.v2 = this.v2.toArray();
  24729. return data;
  24730. }
  24731. fromJSON( json ) {
  24732. super.fromJSON( json );
  24733. this.v0.fromArray( json.v0 );
  24734. this.v1.fromArray( json.v1 );
  24735. this.v2.fromArray( json.v2 );
  24736. return this;
  24737. }
  24738. }
  24739. /**
  24740. * A curve representing a 2D spline curve.
  24741. *
  24742. * ```js
  24743. * // Create a sine-like wave
  24744. * const curve = new THREE.SplineCurve( [
  24745. * new THREE.Vector2( -10, 0 ),
  24746. * new THREE.Vector2( -5, 5 ),
  24747. * new THREE.Vector2( 0, 0 ),
  24748. * new THREE.Vector2( 5, -5 ),
  24749. * new THREE.Vector2( 10, 0 )
  24750. * ] );
  24751. *
  24752. * const points = curve.getPoints( 50 );
  24753. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24754. *
  24755. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24756. *
  24757. * // Create the final object to add to the scene
  24758. * const splineObject = new THREE.Line( geometry, material );
  24759. * ```
  24760. *
  24761. * @augments Curve
  24762. */
  24763. class SplineCurve extends Curve {
  24764. /**
  24765. * Constructs a new 2D spline curve.
  24766. *
  24767. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24768. */
  24769. constructor( points = [] ) {
  24770. super();
  24771. /**
  24772. * This flag can be used for type testing.
  24773. *
  24774. * @type {boolean}
  24775. * @readonly
  24776. * @default true
  24777. */
  24778. this.isSplineCurve = true;
  24779. this.type = 'SplineCurve';
  24780. /**
  24781. * An array of 2D points defining the curve.
  24782. *
  24783. * @type {Array<Vector2>}
  24784. */
  24785. this.points = points;
  24786. }
  24787. /**
  24788. * Returns a point on the curve.
  24789. *
  24790. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24791. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24792. * @return {Vector2} The position on the curve.
  24793. */
  24794. getPoint( t, optionalTarget = new Vector2() ) {
  24795. const point = optionalTarget;
  24796. const points = this.points;
  24797. const p = ( points.length - 1 ) * t;
  24798. const intPoint = Math.floor( p );
  24799. const weight = p - intPoint;
  24800. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24801. const p1 = points[ intPoint ];
  24802. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24803. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24804. point.set(
  24805. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24806. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24807. );
  24808. return point;
  24809. }
  24810. copy( source ) {
  24811. super.copy( source );
  24812. this.points = [];
  24813. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24814. const point = source.points[ i ];
  24815. this.points.push( point.clone() );
  24816. }
  24817. return this;
  24818. }
  24819. toJSON() {
  24820. const data = super.toJSON();
  24821. data.points = [];
  24822. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24823. const point = this.points[ i ];
  24824. data.points.push( point.toArray() );
  24825. }
  24826. return data;
  24827. }
  24828. fromJSON( json ) {
  24829. super.fromJSON( json );
  24830. this.points = [];
  24831. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24832. const point = json.points[ i ];
  24833. this.points.push( new Vector2().fromArray( point ) );
  24834. }
  24835. return this;
  24836. }
  24837. }
  24838. var Curves = /*#__PURE__*/Object.freeze({
  24839. __proto__: null,
  24840. ArcCurve: ArcCurve,
  24841. CatmullRomCurve3: CatmullRomCurve3,
  24842. CubicBezierCurve: CubicBezierCurve,
  24843. CubicBezierCurve3: CubicBezierCurve3,
  24844. EllipseCurve: EllipseCurve,
  24845. LineCurve: LineCurve,
  24846. LineCurve3: LineCurve3,
  24847. QuadraticBezierCurve: QuadraticBezierCurve,
  24848. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24849. SplineCurve: SplineCurve
  24850. });
  24851. /**
  24852. * A base class extending {@link Curve}. `CurvePath` is simply an
  24853. * array of connected curves, but retains the API of a curve.
  24854. *
  24855. * @augments Curve
  24856. */
  24857. class CurvePath extends Curve {
  24858. /**
  24859. * Constructs a new curve path.
  24860. */
  24861. constructor() {
  24862. super();
  24863. this.type = 'CurvePath';
  24864. /**
  24865. * An array of curves defining the
  24866. * path.
  24867. *
  24868. * @type {Array<Curve>}
  24869. */
  24870. this.curves = [];
  24871. /**
  24872. * Whether the path should automatically be closed
  24873. * by a line curve.
  24874. *
  24875. * @type {boolean}
  24876. * @default false
  24877. */
  24878. this.autoClose = false;
  24879. }
  24880. /**
  24881. * Adds a curve to this curve path.
  24882. *
  24883. * @param {Curve} curve - The curve to add.
  24884. */
  24885. add( curve ) {
  24886. this.curves.push( curve );
  24887. }
  24888. /**
  24889. * Adds a line curve to close the path.
  24890. *
  24891. * @return {CurvePath} A reference to this curve path.
  24892. */
  24893. closePath() {
  24894. // Add a line curve if start and end of lines are not connected
  24895. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24896. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24897. if ( ! startPoint.equals( endPoint ) ) {
  24898. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24899. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24900. }
  24901. return this;
  24902. }
  24903. /**
  24904. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24905. * for the given interpolation factor.
  24906. *
  24907. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24908. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24909. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24910. */
  24911. getPoint( t, optionalTarget ) {
  24912. // To get accurate point with reference to
  24913. // entire path distance at time t,
  24914. // following has to be done:
  24915. // 1. Length of each sub path have to be known
  24916. // 2. Locate and identify type of curve
  24917. // 3. Get t for the curve
  24918. // 4. Return curve.getPointAt(t')
  24919. const d = t * this.getLength();
  24920. const curveLengths = this.getCurveLengths();
  24921. let i = 0;
  24922. // To think about boundaries points.
  24923. while ( i < curveLengths.length ) {
  24924. if ( curveLengths[ i ] >= d ) {
  24925. const diff = curveLengths[ i ] - d;
  24926. const curve = this.curves[ i ];
  24927. const segmentLength = curve.getLength();
  24928. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24929. return curve.getPointAt( u, optionalTarget );
  24930. }
  24931. i ++;
  24932. }
  24933. return null;
  24934. // loop where sum != 0, sum > d , sum+1 <d
  24935. }
  24936. getLength() {
  24937. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24938. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24939. // getPoint() depends on getLength
  24940. const lens = this.getCurveLengths();
  24941. return lens[ lens.length - 1 ];
  24942. }
  24943. updateArcLengths() {
  24944. // cacheLengths must be recalculated.
  24945. this.needsUpdate = true;
  24946. this.cacheLengths = null;
  24947. this.getCurveLengths();
  24948. }
  24949. /**
  24950. * Returns list of cumulative curve lengths of the defined curves.
  24951. *
  24952. * @return {Array<number>} The curve lengths.
  24953. */
  24954. getCurveLengths() {
  24955. // Compute lengths and cache them
  24956. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24957. // We use cache values if curves and cache array are same length
  24958. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24959. return this.cacheLengths;
  24960. }
  24961. // Get length of sub-curve
  24962. // Push sums into cached array
  24963. const lengths = [];
  24964. let sums = 0;
  24965. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24966. sums += this.curves[ i ].getLength();
  24967. lengths.push( sums );
  24968. }
  24969. this.cacheLengths = lengths;
  24970. return lengths;
  24971. }
  24972. getSpacedPoints( divisions = 40 ) {
  24973. const points = [];
  24974. for ( let i = 0; i <= divisions; i ++ ) {
  24975. points.push( this.getPoint( i / divisions ) );
  24976. }
  24977. if ( this.autoClose ) {
  24978. points.push( points[ 0 ] );
  24979. }
  24980. return points;
  24981. }
  24982. getPoints( divisions = 12 ) {
  24983. const points = [];
  24984. let last;
  24985. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24986. const curve = curves[ i ];
  24987. const resolution = curve.isEllipseCurve ? divisions * 2
  24988. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24989. : curve.isSplineCurve ? divisions * curve.points.length
  24990. : divisions;
  24991. const pts = curve.getPoints( resolution );
  24992. for ( let j = 0; j < pts.length; j ++ ) {
  24993. const point = pts[ j ];
  24994. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24995. points.push( point );
  24996. last = point;
  24997. }
  24998. }
  24999. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25000. points.push( points[ 0 ] );
  25001. }
  25002. return points;
  25003. }
  25004. copy( source ) {
  25005. super.copy( source );
  25006. this.curves = [];
  25007. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  25008. const curve = source.curves[ i ];
  25009. this.curves.push( curve.clone() );
  25010. }
  25011. this.autoClose = source.autoClose;
  25012. return this;
  25013. }
  25014. toJSON() {
  25015. const data = super.toJSON();
  25016. data.autoClose = this.autoClose;
  25017. data.curves = [];
  25018. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25019. const curve = this.curves[ i ];
  25020. data.curves.push( curve.toJSON() );
  25021. }
  25022. return data;
  25023. }
  25024. fromJSON( json ) {
  25025. super.fromJSON( json );
  25026. this.autoClose = json.autoClose;
  25027. this.curves = [];
  25028. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  25029. const curve = json.curves[ i ];
  25030. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  25031. }
  25032. return this;
  25033. }
  25034. }
  25035. /**
  25036. * A 2D path representation. The class provides methods for creating paths
  25037. * and contours of 2D shapes similar to the 2D Canvas API.
  25038. *
  25039. * ```js
  25040. * const path = new THREE.Path();
  25041. *
  25042. * path.lineTo( 0, 0.8 );
  25043. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  25044. * path.lineTo( 1, 1 );
  25045. *
  25046. * const points = path.getPoints();
  25047. *
  25048. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  25049. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  25050. *
  25051. * const line = new THREE.Line( geometry, material );
  25052. * scene.add( line );
  25053. * ```
  25054. *
  25055. * @augments CurvePath
  25056. */
  25057. class Path extends CurvePath {
  25058. /**
  25059. * Constructs a new path.
  25060. *
  25061. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25062. */
  25063. constructor( points ) {
  25064. super();
  25065. this.type = 'Path';
  25066. /**
  25067. * The current offset of the path. Any new curve added will start here.
  25068. *
  25069. * @type {Vector2}
  25070. */
  25071. this.currentPoint = new Vector2();
  25072. if ( points ) {
  25073. this.setFromPoints( points );
  25074. }
  25075. }
  25076. /**
  25077. * Creates a path from the given list of points. The points are added
  25078. * to the path as instances of {@link LineCurve}.
  25079. *
  25080. * @param {Array<Vector2>} points - An array of 2D points.
  25081. * @return {Path} A reference to this path.
  25082. */
  25083. setFromPoints( points ) {
  25084. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25085. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25086. this.lineTo( points[ i ].x, points[ i ].y );
  25087. }
  25088. return this;
  25089. }
  25090. /**
  25091. * Moves {@link Path#currentPoint} to the given point.
  25092. *
  25093. * @param {number} x - The x coordinate.
  25094. * @param {number} y - The y coordinate.
  25095. * @return {Path} A reference to this path.
  25096. */
  25097. moveTo( x, y ) {
  25098. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25099. return this;
  25100. }
  25101. /**
  25102. * Adds an instance of {@link LineCurve} to the path by connecting
  25103. * the current point with the given one.
  25104. *
  25105. * @param {number} x - The x coordinate of the end point.
  25106. * @param {number} y - The y coordinate of the end point.
  25107. * @return {Path} A reference to this path.
  25108. */
  25109. lineTo( x, y ) {
  25110. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25111. this.curves.push( curve );
  25112. this.currentPoint.set( x, y );
  25113. return this;
  25114. }
  25115. /**
  25116. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25117. * the current point with the given one.
  25118. *
  25119. * @param {number} aCPx - The x coordinate of the control point.
  25120. * @param {number} aCPy - The y coordinate of the control point.
  25121. * @param {number} aX - The x coordinate of the end point.
  25122. * @param {number} aY - The y coordinate of the end point.
  25123. * @return {Path} A reference to this path.
  25124. */
  25125. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25126. const curve = new QuadraticBezierCurve(
  25127. this.currentPoint.clone(),
  25128. new Vector2( aCPx, aCPy ),
  25129. new Vector2( aX, aY )
  25130. );
  25131. this.curves.push( curve );
  25132. this.currentPoint.set( aX, aY );
  25133. return this;
  25134. }
  25135. /**
  25136. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25137. * the current point with the given one.
  25138. *
  25139. * @param {number} aCP1x - The x coordinate of the first control point.
  25140. * @param {number} aCP1y - The y coordinate of the first control point.
  25141. * @param {number} aCP2x - The x coordinate of the second control point.
  25142. * @param {number} aCP2y - The y coordinate of the second control point.
  25143. * @param {number} aX - The x coordinate of the end point.
  25144. * @param {number} aY - The y coordinate of the end point.
  25145. * @return {Path} A reference to this path.
  25146. */
  25147. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25148. const curve = new CubicBezierCurve(
  25149. this.currentPoint.clone(),
  25150. new Vector2( aCP1x, aCP1y ),
  25151. new Vector2( aCP2x, aCP2y ),
  25152. new Vector2( aX, aY )
  25153. );
  25154. this.curves.push( curve );
  25155. this.currentPoint.set( aX, aY );
  25156. return this;
  25157. }
  25158. /**
  25159. * Adds an instance of {@link SplineCurve} to the path by connecting
  25160. * the current point with the given list of points.
  25161. *
  25162. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25163. * @return {Path} A reference to this path.
  25164. */
  25165. splineThru( pts ) {
  25166. const npts = [ this.currentPoint.clone() ].concat( pts );
  25167. const curve = new SplineCurve( npts );
  25168. this.curves.push( curve );
  25169. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25170. return this;
  25171. }
  25172. /**
  25173. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25174. * to the current point.
  25175. *
  25176. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25177. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25178. * @param {number} [aRadius=1] - The radius of the arc.
  25179. * @param {number} [aStartAngle=0] - The start angle in radians.
  25180. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25181. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25182. * @return {Path} A reference to this path.
  25183. */
  25184. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25185. const x0 = this.currentPoint.x;
  25186. const y0 = this.currentPoint.y;
  25187. this.absarc( aX + x0, aY + y0, aRadius,
  25188. aStartAngle, aEndAngle, aClockwise );
  25189. return this;
  25190. }
  25191. /**
  25192. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25193. *
  25194. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25195. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25196. * @param {number} [aRadius=1] - The radius of the arc.
  25197. * @param {number} [aStartAngle=0] - The start angle in radians.
  25198. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25199. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25200. * @return {Path} A reference to this path.
  25201. */
  25202. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25203. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25204. return this;
  25205. }
  25206. /**
  25207. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25208. * to the current point
  25209. *
  25210. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25211. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25212. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25213. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25214. * @param {number} [aStartAngle=0] - The start angle in radians.
  25215. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25216. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25217. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25218. * @return {Path} A reference to this path.
  25219. */
  25220. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25221. const x0 = this.currentPoint.x;
  25222. const y0 = this.currentPoint.y;
  25223. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25224. return this;
  25225. }
  25226. /**
  25227. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25228. *
  25229. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25230. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25231. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25232. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25233. * @param {number} [aStartAngle=0] - The start angle in radians.
  25234. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25235. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25236. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25237. * @return {Path} A reference to this path.
  25238. */
  25239. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25240. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25241. if ( this.curves.length > 0 ) {
  25242. // if a previous curve is present, attempt to join
  25243. const firstPoint = curve.getPoint( 0 );
  25244. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25245. this.lineTo( firstPoint.x, firstPoint.y );
  25246. }
  25247. }
  25248. this.curves.push( curve );
  25249. const lastPoint = curve.getPoint( 1 );
  25250. this.currentPoint.copy( lastPoint );
  25251. return this;
  25252. }
  25253. copy( source ) {
  25254. super.copy( source );
  25255. this.currentPoint.copy( source.currentPoint );
  25256. return this;
  25257. }
  25258. toJSON() {
  25259. const data = super.toJSON();
  25260. data.currentPoint = this.currentPoint.toArray();
  25261. return data;
  25262. }
  25263. fromJSON( json ) {
  25264. super.fromJSON( json );
  25265. this.currentPoint.fromArray( json.currentPoint );
  25266. return this;
  25267. }
  25268. }
  25269. /**
  25270. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25271. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25272. * points, or to get triangulated faces.
  25273. *
  25274. * ```js
  25275. * const heartShape = new THREE.Shape();
  25276. *
  25277. * heartShape.moveTo( 25, 25 );
  25278. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25279. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25280. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25281. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25282. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25283. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25284. *
  25285. * const extrudeSettings = {
  25286. * depth: 8,
  25287. * bevelEnabled: true,
  25288. * bevelSegments: 2,
  25289. * steps: 2,
  25290. * bevelSize: 1,
  25291. * bevelThickness: 1
  25292. * };
  25293. *
  25294. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25295. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25296. * ```
  25297. *
  25298. * @augments Path
  25299. */
  25300. class Shape extends Path {
  25301. /**
  25302. * Constructs a new shape.
  25303. *
  25304. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25305. */
  25306. constructor( points ) {
  25307. super( points );
  25308. /**
  25309. * The UUID of the shape.
  25310. *
  25311. * @type {string}
  25312. * @readonly
  25313. */
  25314. this.uuid = generateUUID();
  25315. this.type = 'Shape';
  25316. /**
  25317. * Defines the holes in the shape. Hole definitions must use the
  25318. * opposite winding order (CW/CCW) than the outer shape.
  25319. *
  25320. * @type {Array<Path>}
  25321. * @readonly
  25322. */
  25323. this.holes = [];
  25324. }
  25325. /**
  25326. * Returns an array representing each contour of the holes
  25327. * as a list of 2D points.
  25328. *
  25329. * @param {number} divisions - The fineness of the result.
  25330. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25331. */
  25332. getPointsHoles( divisions ) {
  25333. const holesPts = [];
  25334. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25335. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25336. }
  25337. return holesPts;
  25338. }
  25339. // get points of shape and holes (keypoints based on segments parameter)
  25340. /**
  25341. * Returns an object that holds contour data for the shape and its holes as
  25342. * arrays of 2D points.
  25343. *
  25344. * @param {number} divisions - The fineness of the result.
  25345. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25346. */
  25347. extractPoints( divisions ) {
  25348. return {
  25349. shape: this.getPoints( divisions ),
  25350. holes: this.getPointsHoles( divisions )
  25351. };
  25352. }
  25353. copy( source ) {
  25354. super.copy( source );
  25355. this.holes = [];
  25356. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25357. const hole = source.holes[ i ];
  25358. this.holes.push( hole.clone() );
  25359. }
  25360. return this;
  25361. }
  25362. toJSON() {
  25363. const data = super.toJSON();
  25364. data.uuid = this.uuid;
  25365. data.holes = [];
  25366. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25367. const hole = this.holes[ i ];
  25368. data.holes.push( hole.toJSON() );
  25369. }
  25370. return data;
  25371. }
  25372. fromJSON( json ) {
  25373. super.fromJSON( json );
  25374. this.uuid = json.uuid;
  25375. this.holes = [];
  25376. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25377. const hole = json.holes[ i ];
  25378. this.holes.push( new Path().fromJSON( hole ) );
  25379. }
  25380. return this;
  25381. }
  25382. }
  25383. /* eslint-disable */
  25384. // copy of mapbox/earcut version 3.0.2
  25385. // https://github.com/mapbox/earcut/tree/v3.0.2
  25386. function earcut(data, holeIndices, dim = 2) {
  25387. const hasHoles = holeIndices && holeIndices.length;
  25388. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25389. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25390. const triangles = [];
  25391. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25392. let minX, minY, invSize;
  25393. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25394. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25395. if (data.length > 80 * dim) {
  25396. minX = data[0];
  25397. minY = data[1];
  25398. let maxX = minX;
  25399. let maxY = minY;
  25400. for (let i = dim; i < outerLen; i += dim) {
  25401. const x = data[i];
  25402. const y = data[i + 1];
  25403. if (x < minX) minX = x;
  25404. if (y < minY) minY = y;
  25405. if (x > maxX) maxX = x;
  25406. if (y > maxY) maxY = y;
  25407. }
  25408. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25409. invSize = Math.max(maxX - minX, maxY - minY);
  25410. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25411. }
  25412. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25413. return triangles;
  25414. }
  25415. // create a circular doubly linked list from polygon points in the specified winding order
  25416. function linkedList(data, start, end, dim, clockwise) {
  25417. let last;
  25418. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25419. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25420. } else {
  25421. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25422. }
  25423. if (last && equals(last, last.next)) {
  25424. removeNode(last);
  25425. last = last.next;
  25426. }
  25427. return last;
  25428. }
  25429. // eliminate colinear or duplicate points
  25430. function filterPoints(start, end) {
  25431. if (!start) return start;
  25432. if (!end) end = start;
  25433. let p = start,
  25434. again;
  25435. do {
  25436. again = false;
  25437. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25438. removeNode(p);
  25439. p = end = p.prev;
  25440. if (p === p.next) break;
  25441. again = true;
  25442. } else {
  25443. p = p.next;
  25444. }
  25445. } while (again || p !== end);
  25446. return end;
  25447. }
  25448. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25449. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25450. if (!ear) return;
  25451. // interlink polygon nodes in z-order
  25452. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25453. let stop = ear;
  25454. // iterate through ears, slicing them one by one
  25455. while (ear.prev !== ear.next) {
  25456. const prev = ear.prev;
  25457. const next = ear.next;
  25458. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25459. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25460. removeNode(ear);
  25461. // skipping the next vertex leads to less sliver triangles
  25462. ear = next.next;
  25463. stop = next.next;
  25464. continue;
  25465. }
  25466. ear = next;
  25467. // if we looped through the whole remaining polygon and can't find any more ears
  25468. if (ear === stop) {
  25469. // try filtering points and slicing again
  25470. if (!pass) {
  25471. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25472. // if this didn't work, try curing all small self-intersections locally
  25473. } else if (pass === 1) {
  25474. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25475. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25476. // as a last resort, try splitting the remaining polygon into two
  25477. } else if (pass === 2) {
  25478. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25479. }
  25480. break;
  25481. }
  25482. }
  25483. }
  25484. // check whether a polygon node forms a valid ear with adjacent nodes
  25485. function isEar(ear) {
  25486. const a = ear.prev,
  25487. b = ear,
  25488. c = ear.next;
  25489. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25490. // now make sure we don't have other points inside the potential ear
  25491. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25492. // triangle bbox
  25493. const x0 = Math.min(ax, bx, cx),
  25494. y0 = Math.min(ay, by, cy),
  25495. x1 = Math.max(ax, bx, cx),
  25496. y1 = Math.max(ay, by, cy);
  25497. let p = c.next;
  25498. while (p !== a) {
  25499. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25500. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25501. area(p.prev, p, p.next) >= 0) return false;
  25502. p = p.next;
  25503. }
  25504. return true;
  25505. }
  25506. function isEarHashed(ear, minX, minY, invSize) {
  25507. const a = ear.prev,
  25508. b = ear,
  25509. c = ear.next;
  25510. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25511. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25512. // triangle bbox
  25513. const x0 = Math.min(ax, bx, cx),
  25514. y0 = Math.min(ay, by, cy),
  25515. x1 = Math.max(ax, bx, cx),
  25516. y1 = Math.max(ay, by, cy);
  25517. // z-order range for the current triangle bbox;
  25518. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25519. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25520. let p = ear.prevZ,
  25521. n = ear.nextZ;
  25522. // look for points inside the triangle in both directions
  25523. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25524. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25525. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25526. p = p.prevZ;
  25527. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25528. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25529. n = n.nextZ;
  25530. }
  25531. // look for remaining points in decreasing z-order
  25532. while (p && p.z >= minZ) {
  25533. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25534. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25535. p = p.prevZ;
  25536. }
  25537. // look for remaining points in increasing z-order
  25538. while (n && n.z <= maxZ) {
  25539. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25540. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25541. n = n.nextZ;
  25542. }
  25543. return true;
  25544. }
  25545. // go through all polygon nodes and cure small local self-intersections
  25546. function cureLocalIntersections(start, triangles) {
  25547. let p = start;
  25548. do {
  25549. const a = p.prev,
  25550. b = p.next.next;
  25551. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25552. triangles.push(a.i, p.i, b.i);
  25553. // remove two nodes involved
  25554. removeNode(p);
  25555. removeNode(p.next);
  25556. p = start = b;
  25557. }
  25558. p = p.next;
  25559. } while (p !== start);
  25560. return filterPoints(p);
  25561. }
  25562. // try splitting polygon into two and triangulate them independently
  25563. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25564. // look for a valid diagonal that divides the polygon into two
  25565. let a = start;
  25566. do {
  25567. let b = a.next.next;
  25568. while (b !== a.prev) {
  25569. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25570. // split the polygon in two by the diagonal
  25571. let c = splitPolygon(a, b);
  25572. // filter colinear points around the cuts
  25573. a = filterPoints(a, a.next);
  25574. c = filterPoints(c, c.next);
  25575. // run earcut on each half
  25576. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25577. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25578. return;
  25579. }
  25580. b = b.next;
  25581. }
  25582. a = a.next;
  25583. } while (a !== start);
  25584. }
  25585. // link every hole into the outer loop, producing a single-ring polygon without holes
  25586. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25587. const queue = [];
  25588. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25589. const start = holeIndices[i] * dim;
  25590. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25591. const list = linkedList(data, start, end, dim, false);
  25592. if (list === list.next) list.steiner = true;
  25593. queue.push(getLeftmost(list));
  25594. }
  25595. queue.sort(compareXYSlope);
  25596. // process holes from left to right
  25597. for (let i = 0; i < queue.length; i++) {
  25598. outerNode = eliminateHole(queue[i], outerNode);
  25599. }
  25600. return outerNode;
  25601. }
  25602. function compareXYSlope(a, b) {
  25603. let result = a.x - b.x;
  25604. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25605. // the bridge to the outer shell is always the point that they meet at.
  25606. if (result === 0) {
  25607. result = a.y - b.y;
  25608. if (result === 0) {
  25609. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25610. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25611. result = aSlope - bSlope;
  25612. }
  25613. }
  25614. return result;
  25615. }
  25616. // find a bridge between vertices that connects hole with an outer ring and link it
  25617. function eliminateHole(hole, outerNode) {
  25618. const bridge = findHoleBridge(hole, outerNode);
  25619. if (!bridge) {
  25620. return outerNode;
  25621. }
  25622. const bridgeReverse = splitPolygon(bridge, hole);
  25623. // filter collinear points around the cuts
  25624. filterPoints(bridgeReverse, bridgeReverse.next);
  25625. return filterPoints(bridge, bridge.next);
  25626. }
  25627. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25628. function findHoleBridge(hole, outerNode) {
  25629. let p = outerNode;
  25630. const hx = hole.x;
  25631. const hy = hole.y;
  25632. let qx = -Infinity;
  25633. let m;
  25634. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25635. // segment's endpoint with lesser x will be potential connection point
  25636. // unless they intersect at a vertex, then choose the vertex
  25637. if (equals(hole, p)) return p;
  25638. do {
  25639. if (equals(hole, p.next)) return p.next;
  25640. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25641. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25642. if (x <= hx && x > qx) {
  25643. qx = x;
  25644. m = p.x < p.next.x ? p : p.next;
  25645. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25646. }
  25647. }
  25648. p = p.next;
  25649. } while (p !== outerNode);
  25650. if (!m) return null;
  25651. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25652. // if there are no points found, we have a valid connection;
  25653. // otherwise choose the point of the minimum angle with the ray as connection point
  25654. const stop = m;
  25655. const mx = m.x;
  25656. const my = m.y;
  25657. let tanMin = Infinity;
  25658. p = m;
  25659. do {
  25660. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25661. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25662. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25663. if (locallyInside(p, hole) &&
  25664. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25665. m = p;
  25666. tanMin = tan;
  25667. }
  25668. }
  25669. p = p.next;
  25670. } while (p !== stop);
  25671. return m;
  25672. }
  25673. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25674. function sectorContainsSector(m, p) {
  25675. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25676. }
  25677. // interlink polygon nodes in z-order
  25678. function indexCurve(start, minX, minY, invSize) {
  25679. let p = start;
  25680. do {
  25681. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25682. p.prevZ = p.prev;
  25683. p.nextZ = p.next;
  25684. p = p.next;
  25685. } while (p !== start);
  25686. p.prevZ.nextZ = null;
  25687. p.prevZ = null;
  25688. sortLinked(p);
  25689. }
  25690. // Simon Tatham's linked list merge sort algorithm
  25691. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25692. function sortLinked(list) {
  25693. let numMerges;
  25694. let inSize = 1;
  25695. do {
  25696. let p = list;
  25697. let e;
  25698. list = null;
  25699. let tail = null;
  25700. numMerges = 0;
  25701. while (p) {
  25702. numMerges++;
  25703. let q = p;
  25704. let pSize = 0;
  25705. for (let i = 0; i < inSize; i++) {
  25706. pSize++;
  25707. q = q.nextZ;
  25708. if (!q) break;
  25709. }
  25710. let qSize = inSize;
  25711. while (pSize > 0 || (qSize > 0 && q)) {
  25712. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25713. e = p;
  25714. p = p.nextZ;
  25715. pSize--;
  25716. } else {
  25717. e = q;
  25718. q = q.nextZ;
  25719. qSize--;
  25720. }
  25721. if (tail) tail.nextZ = e;
  25722. else list = e;
  25723. e.prevZ = tail;
  25724. tail = e;
  25725. }
  25726. p = q;
  25727. }
  25728. tail.nextZ = null;
  25729. inSize *= 2;
  25730. } while (numMerges > 1);
  25731. return list;
  25732. }
  25733. // z-order of a point given coords and inverse of the longer side of data bbox
  25734. function zOrder(x, y, minX, minY, invSize) {
  25735. // coords are transformed into non-negative 15-bit integer range
  25736. x = (x - minX) * invSize | 0;
  25737. y = (y - minY) * invSize | 0;
  25738. x = (x | (x << 8)) & 0x00FF00FF;
  25739. x = (x | (x << 4)) & 0x0F0F0F0F;
  25740. x = (x | (x << 2)) & 0x33333333;
  25741. x = (x | (x << 1)) & 0x55555555;
  25742. y = (y | (y << 8)) & 0x00FF00FF;
  25743. y = (y | (y << 4)) & 0x0F0F0F0F;
  25744. y = (y | (y << 2)) & 0x33333333;
  25745. y = (y | (y << 1)) & 0x55555555;
  25746. return x | (y << 1);
  25747. }
  25748. // find the leftmost node of a polygon ring
  25749. function getLeftmost(start) {
  25750. let p = start,
  25751. leftmost = start;
  25752. do {
  25753. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25754. p = p.next;
  25755. } while (p !== start);
  25756. return leftmost;
  25757. }
  25758. // check if a point lies within a convex triangle
  25759. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25760. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25761. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25762. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25763. }
  25764. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25765. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25766. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25767. }
  25768. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25769. function isValidDiagonal(a, b) {
  25770. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25771. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25772. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25773. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25774. }
  25775. // signed area of a triangle
  25776. function area(p, q, r) {
  25777. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25778. }
  25779. // check if two points are equal
  25780. function equals(p1, p2) {
  25781. return p1.x === p2.x && p1.y === p2.y;
  25782. }
  25783. // check if two segments intersect
  25784. function intersects(p1, q1, p2, q2) {
  25785. const o1 = sign(area(p1, q1, p2));
  25786. const o2 = sign(area(p1, q1, q2));
  25787. const o3 = sign(area(p2, q2, p1));
  25788. const o4 = sign(area(p2, q2, q1));
  25789. if (o1 !== o2 && o3 !== o4) return true; // general case
  25790. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25791. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25792. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25793. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25794. return false;
  25795. }
  25796. // for collinear points p, q, r, check if point q lies on segment pr
  25797. function onSegment(p, q, r) {
  25798. 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);
  25799. }
  25800. function sign(num) {
  25801. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25802. }
  25803. // check if a polygon diagonal intersects any polygon segments
  25804. function intersectsPolygon(a, b) {
  25805. let p = a;
  25806. do {
  25807. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25808. intersects(p, p.next, a, b)) return true;
  25809. p = p.next;
  25810. } while (p !== a);
  25811. return false;
  25812. }
  25813. // check if a polygon diagonal is locally inside the polygon
  25814. function locallyInside(a, b) {
  25815. return area(a.prev, a, a.next) < 0 ?
  25816. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25817. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25818. }
  25819. // check if the middle point of a polygon diagonal is inside the polygon
  25820. function middleInside(a, b) {
  25821. let p = a;
  25822. let inside = false;
  25823. const px = (a.x + b.x) / 2;
  25824. const py = (a.y + b.y) / 2;
  25825. do {
  25826. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25827. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25828. inside = !inside;
  25829. p = p.next;
  25830. } while (p !== a);
  25831. return inside;
  25832. }
  25833. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25834. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25835. function splitPolygon(a, b) {
  25836. const a2 = createNode(a.i, a.x, a.y),
  25837. b2 = createNode(b.i, b.x, b.y),
  25838. an = a.next,
  25839. bp = b.prev;
  25840. a.next = b;
  25841. b.prev = a;
  25842. a2.next = an;
  25843. an.prev = a2;
  25844. b2.next = a2;
  25845. a2.prev = b2;
  25846. bp.next = b2;
  25847. b2.prev = bp;
  25848. return b2;
  25849. }
  25850. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25851. function insertNode(i, x, y, last) {
  25852. const p = createNode(i, x, y);
  25853. if (!last) {
  25854. p.prev = p;
  25855. p.next = p;
  25856. } else {
  25857. p.next = last.next;
  25858. p.prev = last;
  25859. last.next.prev = p;
  25860. last.next = p;
  25861. }
  25862. return p;
  25863. }
  25864. function removeNode(p) {
  25865. p.next.prev = p.prev;
  25866. p.prev.next = p.next;
  25867. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25868. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25869. }
  25870. function createNode(i, x, y) {
  25871. return {
  25872. i, // vertex index in coordinates array
  25873. x, y, // vertex coordinates
  25874. prev: null, // previous and next vertex nodes in a polygon ring
  25875. next: null,
  25876. z: 0, // z-order curve value
  25877. prevZ: null, // previous and next nodes in z-order
  25878. nextZ: null,
  25879. steiner: false // indicates whether this is a steiner point
  25880. };
  25881. }
  25882. function signedArea(data, start, end, dim) {
  25883. let sum = 0;
  25884. for (let i = start, j = end - dim; i < end; i += dim) {
  25885. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25886. j = i;
  25887. }
  25888. return sum;
  25889. }
  25890. /**
  25891. * An implementation of the earcut polygon triangulation algorithm.
  25892. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25893. *
  25894. * @see https://github.com/mapbox/earcut
  25895. */
  25896. class Earcut {
  25897. /**
  25898. * Triangulates the given shape definition by returning an array of triangles.
  25899. *
  25900. * @param {Array<number>} data - An array with 2D points.
  25901. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25902. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25903. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25904. * representing vertex indices.
  25905. */
  25906. static triangulate( data, holeIndices, dim = 2 ) {
  25907. return earcut( data, holeIndices, dim );
  25908. }
  25909. }
  25910. /**
  25911. * A class containing utility functions for shapes.
  25912. *
  25913. * @hideconstructor
  25914. */
  25915. class ShapeUtils {
  25916. /**
  25917. * Calculate area of a ( 2D ) contour polygon.
  25918. *
  25919. * @param {Array<Vector2>} contour - An array of 2D points.
  25920. * @return {number} The area.
  25921. */
  25922. static area( contour ) {
  25923. const n = contour.length;
  25924. let a = 0.0;
  25925. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25926. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25927. }
  25928. return a * 0.5;
  25929. }
  25930. /**
  25931. * Returns `true` if the given contour uses a clockwise winding order.
  25932. *
  25933. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25934. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25935. */
  25936. static isClockWise( pts ) {
  25937. return ShapeUtils.area( pts ) < 0;
  25938. }
  25939. /**
  25940. * Triangulates the given shape definition.
  25941. *
  25942. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25943. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25944. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25945. */
  25946. static triangulateShape( contour, holes ) {
  25947. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25948. const holeIndices = []; // array of hole indices
  25949. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25950. removeDupEndPts( contour );
  25951. addContour( vertices, contour );
  25952. //
  25953. let holeIndex = contour.length;
  25954. holes.forEach( removeDupEndPts );
  25955. for ( let i = 0; i < holes.length; i ++ ) {
  25956. holeIndices.push( holeIndex );
  25957. holeIndex += holes[ i ].length;
  25958. addContour( vertices, holes[ i ] );
  25959. }
  25960. //
  25961. const triangles = Earcut.triangulate( vertices, holeIndices );
  25962. //
  25963. for ( let i = 0; i < triangles.length; i += 3 ) {
  25964. faces.push( triangles.slice( i, i + 3 ) );
  25965. }
  25966. return faces;
  25967. }
  25968. }
  25969. function removeDupEndPts( points ) {
  25970. const l = points.length;
  25971. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25972. points.pop();
  25973. }
  25974. }
  25975. function addContour( vertices, contour ) {
  25976. for ( let i = 0; i < contour.length; i ++ ) {
  25977. vertices.push( contour[ i ].x );
  25978. vertices.push( contour[ i ].y );
  25979. }
  25980. }
  25981. /**
  25982. * Creates extruded geometry from a path shape.
  25983. *
  25984. * ```js
  25985. * const length = 12, width = 8;
  25986. *
  25987. * const shape = new THREE.Shape();
  25988. * shape.moveTo( 0,0 );
  25989. * shape.lineTo( 0, width );
  25990. * shape.lineTo( length, width );
  25991. * shape.lineTo( length, 0 );
  25992. * shape.lineTo( 0, 0 );
  25993. *
  25994. * const geometry = new THREE.ExtrudeGeometry( shape );
  25995. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25996. * const mesh = new THREE.Mesh( geometry, material ) ;
  25997. * scene.add( mesh );
  25998. * ```
  25999. *
  26000. * @augments BufferGeometry
  26001. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  26002. */
  26003. class ExtrudeGeometry extends BufferGeometry {
  26004. /**
  26005. * Constructs a new extrude geometry.
  26006. *
  26007. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26008. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  26009. */
  26010. 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 = {} ) {
  26011. super();
  26012. this.type = 'ExtrudeGeometry';
  26013. /**
  26014. * Holds the constructor parameters that have been
  26015. * used to generate the geometry. Any modification
  26016. * after instantiation does not change the geometry.
  26017. *
  26018. * @type {Object}
  26019. */
  26020. this.parameters = {
  26021. shapes: shapes,
  26022. options: options
  26023. };
  26024. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  26025. const scope = this;
  26026. const verticesArray = [];
  26027. const uvArray = [];
  26028. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26029. const shape = shapes[ i ];
  26030. addShape( shape );
  26031. }
  26032. // build geometry
  26033. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  26034. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  26035. this.computeVertexNormals();
  26036. // functions
  26037. function addShape( shape ) {
  26038. const placeholder = [];
  26039. // options
  26040. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  26041. const steps = options.steps !== undefined ? options.steps : 1;
  26042. const depth = options.depth !== undefined ? options.depth : 1;
  26043. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  26044. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  26045. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  26046. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  26047. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  26048. const extrudePath = options.extrudePath;
  26049. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  26050. //
  26051. let extrudePts, extrudeByPath = false;
  26052. let splineTube, binormal, normal, position2;
  26053. if ( extrudePath ) {
  26054. extrudePts = extrudePath.getSpacedPoints( steps );
  26055. extrudeByPath = true;
  26056. bevelEnabled = false; // bevels not supported for path extrusion
  26057. // SETUP TNB variables
  26058. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26059. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26060. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26061. binormal = new Vector3();
  26062. normal = new Vector3();
  26063. position2 = new Vector3();
  26064. }
  26065. // Safeguards if bevels are not enabled
  26066. if ( ! bevelEnabled ) {
  26067. bevelSegments = 0;
  26068. bevelThickness = 0;
  26069. bevelSize = 0;
  26070. bevelOffset = 0;
  26071. }
  26072. // Variables initialization
  26073. const shapePoints = shape.extractPoints( curveSegments );
  26074. let vertices = shapePoints.shape;
  26075. const holes = shapePoints.holes;
  26076. const reverse = ! ShapeUtils.isClockWise( vertices );
  26077. if ( reverse ) {
  26078. vertices = vertices.reverse();
  26079. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26080. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26081. const ahole = holes[ h ];
  26082. if ( ShapeUtils.isClockWise( ahole ) ) {
  26083. holes[ h ] = ahole.reverse();
  26084. }
  26085. }
  26086. }
  26087. /**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.
  26088. * @param {Array<Vector2>} points
  26089. */
  26090. function mergeOverlappingPoints( points ) {
  26091. const THRESHOLD = 1e-10;
  26092. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26093. let prevPos = points[ 0 ];
  26094. for ( let i = 1; i <= points.length; i ++ ) {
  26095. const currentIndex = i % points.length;
  26096. const currentPos = points[ currentIndex ];
  26097. const dx = currentPos.x - prevPos.x;
  26098. const dy = currentPos.y - prevPos.y;
  26099. const distSq = dx * dx + dy * dy;
  26100. const scalingFactorSqrt = Math.max(
  26101. Math.abs( currentPos.x ),
  26102. Math.abs( currentPos.y ),
  26103. Math.abs( prevPos.x ),
  26104. Math.abs( prevPos.y )
  26105. );
  26106. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26107. if ( distSq <= thresholdSqScaled ) {
  26108. points.splice( currentIndex, 1 );
  26109. i --;
  26110. continue;
  26111. }
  26112. prevPos = currentPos;
  26113. }
  26114. }
  26115. mergeOverlappingPoints( vertices );
  26116. holes.forEach( mergeOverlappingPoints );
  26117. const numHoles = holes.length;
  26118. /* Vertices */
  26119. const contour = vertices; // vertices has all points but contour has only points of circumference
  26120. for ( let h = 0; h < numHoles; h ++ ) {
  26121. const ahole = holes[ h ];
  26122. vertices = vertices.concat( ahole );
  26123. }
  26124. function scalePt2( pt, vec, size ) {
  26125. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26126. return pt.clone().addScaledVector( vec, size );
  26127. }
  26128. const vlen = vertices.length;
  26129. // Find directions for point movement
  26130. function getBevelVec( inPt, inPrev, inNext ) {
  26131. // computes for inPt the corresponding point inPt' on a new contour
  26132. // shifted by 1 unit (length of normalized vector) to the left
  26133. // if we walk along contour clockwise, this new contour is outside the old one
  26134. //
  26135. // inPt' is the intersection of the two lines parallel to the two
  26136. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26137. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26138. // good reading for geometry algorithms (here: line-line intersection)
  26139. // http://geomalgorithms.com/a05-_intersect-1.html
  26140. const v_prev_x = inPt.x - inPrev.x,
  26141. v_prev_y = inPt.y - inPrev.y;
  26142. const v_next_x = inNext.x - inPt.x,
  26143. v_next_y = inNext.y - inPt.y;
  26144. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26145. // check for collinear edges
  26146. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26147. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26148. // not collinear
  26149. // length of vectors for normalizing
  26150. const v_prev_len = Math.sqrt( v_prev_lensq );
  26151. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26152. // shift adjacent points by unit vectors to the left
  26153. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26154. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26155. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26156. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26157. // scaling factor for v_prev to intersection point
  26158. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26159. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26160. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26161. // vector from inPt to intersection point
  26162. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26163. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26164. // Don't normalize!, otherwise sharp corners become ugly
  26165. // but prevent crazy spikes
  26166. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26167. if ( v_trans_lensq <= 2 ) {
  26168. return new Vector2( v_trans_x, v_trans_y );
  26169. } else {
  26170. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26171. }
  26172. } else {
  26173. // handle special case of collinear edges
  26174. let direction_eq = false; // assumes: opposite
  26175. if ( v_prev_x > Number.EPSILON ) {
  26176. if ( v_next_x > Number.EPSILON ) {
  26177. direction_eq = true;
  26178. }
  26179. } else {
  26180. if ( v_prev_x < - Number.EPSILON ) {
  26181. if ( v_next_x < - Number.EPSILON ) {
  26182. direction_eq = true;
  26183. }
  26184. } else {
  26185. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26186. direction_eq = true;
  26187. }
  26188. }
  26189. }
  26190. if ( direction_eq ) {
  26191. // log("Warning: lines are a straight sequence");
  26192. v_trans_x = - v_prev_y;
  26193. v_trans_y = v_prev_x;
  26194. shrink_by = Math.sqrt( v_prev_lensq );
  26195. } else {
  26196. // log("Warning: lines are a straight spike");
  26197. v_trans_x = v_prev_x;
  26198. v_trans_y = v_prev_y;
  26199. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26200. }
  26201. }
  26202. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26203. }
  26204. const contourMovements = [];
  26205. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26206. if ( j === il ) j = 0;
  26207. if ( k === il ) k = 0;
  26208. // (j)---(i)---(k)
  26209. // log('i,j,k', i, j , k)
  26210. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26211. }
  26212. const holesMovements = [];
  26213. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26214. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26215. const ahole = holes[ h ];
  26216. oneHoleMovements = [];
  26217. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26218. if ( j === il ) j = 0;
  26219. if ( k === il ) k = 0;
  26220. // (j)---(i)---(k)
  26221. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26222. }
  26223. holesMovements.push( oneHoleMovements );
  26224. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26225. }
  26226. let faces;
  26227. if ( bevelSegments === 0 ) {
  26228. faces = ShapeUtils.triangulateShape( contour, holes );
  26229. } else {
  26230. const contractedContourVertices = [];
  26231. const expandedHoleVertices = [];
  26232. // Loop bevelSegments, 1 for the front, 1 for the back
  26233. for ( let b = 0; b < bevelSegments; b ++ ) {
  26234. //for ( b = bevelSegments; b > 0; b -- ) {
  26235. const t = b / bevelSegments;
  26236. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26237. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26238. // contract shape
  26239. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26240. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26241. v( vert.x, vert.y, - z );
  26242. if ( t === 0 ) contractedContourVertices.push( vert );
  26243. }
  26244. // expand holes
  26245. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26246. const ahole = holes[ h ];
  26247. oneHoleMovements = holesMovements[ h ];
  26248. const oneHoleVertices = [];
  26249. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26250. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26251. v( vert.x, vert.y, - z );
  26252. if ( t === 0 ) oneHoleVertices.push( vert );
  26253. }
  26254. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26255. }
  26256. }
  26257. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26258. }
  26259. const flen = faces.length;
  26260. const bs = bevelSize + bevelOffset;
  26261. // Back facing vertices
  26262. for ( let i = 0; i < vlen; i ++ ) {
  26263. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26264. if ( ! extrudeByPath ) {
  26265. v( vert.x, vert.y, 0 );
  26266. } else {
  26267. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26268. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26269. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26270. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26271. v( position2.x, position2.y, position2.z );
  26272. }
  26273. }
  26274. // Add stepped vertices...
  26275. // Including front facing vertices
  26276. for ( let s = 1; s <= steps; s ++ ) {
  26277. for ( let i = 0; i < vlen; i ++ ) {
  26278. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26279. if ( ! extrudeByPath ) {
  26280. v( vert.x, vert.y, depth / steps * s );
  26281. } else {
  26282. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26283. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26284. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26285. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26286. v( position2.x, position2.y, position2.z );
  26287. }
  26288. }
  26289. }
  26290. // Add bevel segments planes
  26291. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26292. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26293. const t = b / bevelSegments;
  26294. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26295. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26296. // contract shape
  26297. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26298. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26299. v( vert.x, vert.y, depth + z );
  26300. }
  26301. // expand holes
  26302. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26303. const ahole = holes[ h ];
  26304. oneHoleMovements = holesMovements[ h ];
  26305. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26306. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26307. if ( ! extrudeByPath ) {
  26308. v( vert.x, vert.y, depth + z );
  26309. } else {
  26310. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26311. }
  26312. }
  26313. }
  26314. }
  26315. /* Faces */
  26316. // Top and bottom faces
  26317. buildLidFaces();
  26318. // Sides faces
  26319. buildSideFaces();
  26320. ///// Internal functions
  26321. function buildLidFaces() {
  26322. const start = verticesArray.length / 3;
  26323. if ( bevelEnabled ) {
  26324. let layer = 0; // steps + 1
  26325. let offset = vlen * layer;
  26326. // Bottom faces
  26327. for ( let i = 0; i < flen; i ++ ) {
  26328. const face = faces[ i ];
  26329. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26330. }
  26331. layer = steps + bevelSegments * 2;
  26332. offset = vlen * layer;
  26333. // Top faces
  26334. for ( let i = 0; i < flen; i ++ ) {
  26335. const face = faces[ i ];
  26336. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26337. }
  26338. } else {
  26339. // Bottom faces
  26340. for ( let i = 0; i < flen; i ++ ) {
  26341. const face = faces[ i ];
  26342. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26343. }
  26344. // Top faces
  26345. for ( let i = 0; i < flen; i ++ ) {
  26346. const face = faces[ i ];
  26347. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26348. }
  26349. }
  26350. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26351. }
  26352. // Create faces for the z-sides of the shape
  26353. function buildSideFaces() {
  26354. const start = verticesArray.length / 3;
  26355. let layeroffset = 0;
  26356. sidewalls( contour, layeroffset );
  26357. layeroffset += contour.length;
  26358. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26359. const ahole = holes[ h ];
  26360. sidewalls( ahole, layeroffset );
  26361. //, true
  26362. layeroffset += ahole.length;
  26363. }
  26364. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26365. }
  26366. function sidewalls( contour, layeroffset ) {
  26367. let i = contour.length;
  26368. while ( -- i >= 0 ) {
  26369. const j = i;
  26370. let k = i - 1;
  26371. if ( k < 0 ) k = contour.length - 1;
  26372. //log('b', i,j, i-1, k,vertices.length);
  26373. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26374. const slen1 = vlen * s;
  26375. const slen2 = vlen * ( s + 1 );
  26376. const a = layeroffset + j + slen1,
  26377. b = layeroffset + k + slen1,
  26378. c = layeroffset + k + slen2,
  26379. d = layeroffset + j + slen2;
  26380. f4( a, b, c, d );
  26381. }
  26382. }
  26383. }
  26384. function v( x, y, z ) {
  26385. placeholder.push( x );
  26386. placeholder.push( y );
  26387. placeholder.push( z );
  26388. }
  26389. function f3( a, b, c ) {
  26390. addVertex( a );
  26391. addVertex( b );
  26392. addVertex( c );
  26393. const nextIndex = verticesArray.length / 3;
  26394. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26395. addUV( uvs[ 0 ] );
  26396. addUV( uvs[ 1 ] );
  26397. addUV( uvs[ 2 ] );
  26398. }
  26399. function f4( a, b, c, d ) {
  26400. addVertex( a );
  26401. addVertex( b );
  26402. addVertex( d );
  26403. addVertex( b );
  26404. addVertex( c );
  26405. addVertex( d );
  26406. const nextIndex = verticesArray.length / 3;
  26407. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26408. addUV( uvs[ 0 ] );
  26409. addUV( uvs[ 1 ] );
  26410. addUV( uvs[ 3 ] );
  26411. addUV( uvs[ 1 ] );
  26412. addUV( uvs[ 2 ] );
  26413. addUV( uvs[ 3 ] );
  26414. }
  26415. function addVertex( index ) {
  26416. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26417. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26418. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26419. }
  26420. function addUV( vector2 ) {
  26421. uvArray.push( vector2.x );
  26422. uvArray.push( vector2.y );
  26423. }
  26424. }
  26425. }
  26426. copy( source ) {
  26427. super.copy( source );
  26428. this.parameters = Object.assign( {}, source.parameters );
  26429. return this;
  26430. }
  26431. toJSON() {
  26432. const data = super.toJSON();
  26433. const shapes = this.parameters.shapes;
  26434. const options = this.parameters.options;
  26435. return toJSON$1( shapes, options, data );
  26436. }
  26437. /**
  26438. * Factory method for creating an instance of this class from the given
  26439. * JSON object.
  26440. *
  26441. * @param {Object} data - A JSON object representing the serialized geometry.
  26442. * @param {Array<Shape>} shapes - An array of shapes.
  26443. * @return {ExtrudeGeometry} A new instance.
  26444. */
  26445. static fromJSON( data, shapes ) {
  26446. const geometryShapes = [];
  26447. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26448. const shape = shapes[ data.shapes[ j ] ];
  26449. geometryShapes.push( shape );
  26450. }
  26451. const extrudePath = data.options.extrudePath;
  26452. if ( extrudePath !== undefined ) {
  26453. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26454. }
  26455. return new ExtrudeGeometry( geometryShapes, data.options );
  26456. }
  26457. }
  26458. const WorldUVGenerator = {
  26459. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26460. const a_x = vertices[ indexA * 3 ];
  26461. const a_y = vertices[ indexA * 3 + 1 ];
  26462. const b_x = vertices[ indexB * 3 ];
  26463. const b_y = vertices[ indexB * 3 + 1 ];
  26464. const c_x = vertices[ indexC * 3 ];
  26465. const c_y = vertices[ indexC * 3 + 1 ];
  26466. return [
  26467. new Vector2( a_x, a_y ),
  26468. new Vector2( b_x, b_y ),
  26469. new Vector2( c_x, c_y )
  26470. ];
  26471. },
  26472. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26473. const a_x = vertices[ indexA * 3 ];
  26474. const a_y = vertices[ indexA * 3 + 1 ];
  26475. const a_z = vertices[ indexA * 3 + 2 ];
  26476. const b_x = vertices[ indexB * 3 ];
  26477. const b_y = vertices[ indexB * 3 + 1 ];
  26478. const b_z = vertices[ indexB * 3 + 2 ];
  26479. const c_x = vertices[ indexC * 3 ];
  26480. const c_y = vertices[ indexC * 3 + 1 ];
  26481. const c_z = vertices[ indexC * 3 + 2 ];
  26482. const d_x = vertices[ indexD * 3 ];
  26483. const d_y = vertices[ indexD * 3 + 1 ];
  26484. const d_z = vertices[ indexD * 3 + 2 ];
  26485. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26486. return [
  26487. new Vector2( a_x, 1 - a_z ),
  26488. new Vector2( b_x, 1 - b_z ),
  26489. new Vector2( c_x, 1 - c_z ),
  26490. new Vector2( d_x, 1 - d_z )
  26491. ];
  26492. } else {
  26493. return [
  26494. new Vector2( a_y, 1 - a_z ),
  26495. new Vector2( b_y, 1 - b_z ),
  26496. new Vector2( c_y, 1 - c_z ),
  26497. new Vector2( d_y, 1 - d_z )
  26498. ];
  26499. }
  26500. }
  26501. };
  26502. function toJSON$1( shapes, options, data ) {
  26503. data.shapes = [];
  26504. if ( Array.isArray( shapes ) ) {
  26505. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26506. const shape = shapes[ i ];
  26507. data.shapes.push( shape.uuid );
  26508. }
  26509. } else {
  26510. data.shapes.push( shapes.uuid );
  26511. }
  26512. data.options = Object.assign( {}, options );
  26513. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26514. return data;
  26515. }
  26516. /**
  26517. * A geometry class for representing an icosahedron.
  26518. *
  26519. * ```js
  26520. * const geometry = new THREE.IcosahedronGeometry();
  26521. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26522. * const icosahedron = new THREE.Mesh( geometry, material );
  26523. * scene.add( icosahedron );
  26524. * ```
  26525. *
  26526. * @augments PolyhedronGeometry
  26527. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26528. */
  26529. class IcosahedronGeometry extends PolyhedronGeometry {
  26530. /**
  26531. * Constructs a new icosahedron geometry.
  26532. *
  26533. * @param {number} [radius=1] - Radius of the icosahedron.
  26534. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26535. */
  26536. constructor( radius = 1, detail = 0 ) {
  26537. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26538. const vertices = [
  26539. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26540. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26541. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26542. ];
  26543. const indices = [
  26544. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26545. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26546. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26547. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26548. ];
  26549. super( vertices, indices, radius, detail );
  26550. this.type = 'IcosahedronGeometry';
  26551. /**
  26552. * Holds the constructor parameters that have been
  26553. * used to generate the geometry. Any modification
  26554. * after instantiation does not change the geometry.
  26555. *
  26556. * @type {Object}
  26557. */
  26558. this.parameters = {
  26559. radius: radius,
  26560. detail: detail
  26561. };
  26562. }
  26563. /**
  26564. * Factory method for creating an instance of this class from the given
  26565. * JSON object.
  26566. *
  26567. * @param {Object} data - A JSON object representing the serialized geometry.
  26568. * @return {IcosahedronGeometry} A new instance.
  26569. */
  26570. static fromJSON( data ) {
  26571. return new IcosahedronGeometry( data.radius, data.detail );
  26572. }
  26573. }
  26574. /**
  26575. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26576. *
  26577. * ```js
  26578. * const points = [];
  26579. * for ( let i = 0; i < 10; i ++ ) {
  26580. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26581. * }
  26582. * const geometry = new THREE.LatheGeometry( points );
  26583. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26584. * const lathe = new THREE.Mesh( geometry, material );
  26585. * scene.add( lathe );
  26586. * ```
  26587. *
  26588. * @augments BufferGeometry
  26589. * @demo scenes/geometry-browser.html#LatheGeometry
  26590. */
  26591. class LatheGeometry extends BufferGeometry {
  26592. /**
  26593. * Constructs a new lathe geometry.
  26594. *
  26595. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26596. * must be greater than zero.
  26597. * @param {number} [segments=12] - The number of circumference segments to generate.
  26598. * @param {number} [phiStart=0] - The starting angle in radians.
  26599. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26600. * closed lathe, less than 2PI is a portion.
  26601. */
  26602. 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 ) {
  26603. super();
  26604. this.type = 'LatheGeometry';
  26605. /**
  26606. * Holds the constructor parameters that have been
  26607. * used to generate the geometry. Any modification
  26608. * after instantiation does not change the geometry.
  26609. *
  26610. * @type {Object}
  26611. */
  26612. this.parameters = {
  26613. points: points,
  26614. segments: segments,
  26615. phiStart: phiStart,
  26616. phiLength: phiLength
  26617. };
  26618. segments = Math.floor( segments );
  26619. // clamp phiLength so it's in range of [ 0, 2PI ]
  26620. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26621. // buffers
  26622. const indices = [];
  26623. const vertices = [];
  26624. const uvs = [];
  26625. const initNormals = [];
  26626. const normals = [];
  26627. // helper variables
  26628. const inverseSegments = 1.0 / segments;
  26629. const vertex = new Vector3();
  26630. const uv = new Vector2();
  26631. const normal = new Vector3();
  26632. const curNormal = new Vector3();
  26633. const prevNormal = new Vector3();
  26634. let dx = 0;
  26635. let dy = 0;
  26636. // pre-compute normals for initial "meridian"
  26637. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26638. switch ( j ) {
  26639. case 0: // special handling for 1st vertex on path
  26640. dx = points[ j + 1 ].x - points[ j ].x;
  26641. dy = points[ j + 1 ].y - points[ j ].y;
  26642. normal.x = dy * 1.0;
  26643. normal.y = - dx;
  26644. normal.z = dy * 0.0;
  26645. prevNormal.copy( normal );
  26646. normal.normalize();
  26647. initNormals.push( normal.x, normal.y, normal.z );
  26648. break;
  26649. case ( points.length - 1 ): // special handling for last Vertex on path
  26650. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26651. break;
  26652. default: // default handling for all vertices in between
  26653. dx = points[ j + 1 ].x - points[ j ].x;
  26654. dy = points[ j + 1 ].y - points[ j ].y;
  26655. normal.x = dy * 1.0;
  26656. normal.y = - dx;
  26657. normal.z = dy * 0.0;
  26658. curNormal.copy( normal );
  26659. normal.x += prevNormal.x;
  26660. normal.y += prevNormal.y;
  26661. normal.z += prevNormal.z;
  26662. normal.normalize();
  26663. initNormals.push( normal.x, normal.y, normal.z );
  26664. prevNormal.copy( curNormal );
  26665. }
  26666. }
  26667. // generate vertices, uvs and normals
  26668. for ( let i = 0; i <= segments; i ++ ) {
  26669. const phi = phiStart + i * inverseSegments * phiLength;
  26670. const sin = Math.sin( phi );
  26671. const cos = Math.cos( phi );
  26672. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26673. // vertex
  26674. vertex.x = points[ j ].x * sin;
  26675. vertex.y = points[ j ].y;
  26676. vertex.z = points[ j ].x * cos;
  26677. vertices.push( vertex.x, vertex.y, vertex.z );
  26678. // uv
  26679. uv.x = i / segments;
  26680. uv.y = j / ( points.length - 1 );
  26681. uvs.push( uv.x, uv.y );
  26682. // normal
  26683. const x = initNormals[ 3 * j + 0 ] * sin;
  26684. const y = initNormals[ 3 * j + 1 ];
  26685. const z = initNormals[ 3 * j + 0 ] * cos;
  26686. normals.push( x, y, z );
  26687. }
  26688. }
  26689. // indices
  26690. for ( let i = 0; i < segments; i ++ ) {
  26691. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26692. const base = j + i * points.length;
  26693. const a = base;
  26694. const b = base + points.length;
  26695. const c = base + points.length + 1;
  26696. const d = base + 1;
  26697. // faces
  26698. indices.push( a, b, d );
  26699. indices.push( c, d, b );
  26700. }
  26701. }
  26702. // build geometry
  26703. this.setIndex( indices );
  26704. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26705. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26706. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26707. }
  26708. copy( source ) {
  26709. super.copy( source );
  26710. this.parameters = Object.assign( {}, source.parameters );
  26711. return this;
  26712. }
  26713. /**
  26714. * Factory method for creating an instance of this class from the given
  26715. * JSON object.
  26716. *
  26717. * @param {Object} data - A JSON object representing the serialized geometry.
  26718. * @return {LatheGeometry} A new instance.
  26719. */
  26720. static fromJSON( data ) {
  26721. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26722. }
  26723. }
  26724. /**
  26725. * A geometry class for representing an octahedron.
  26726. *
  26727. * ```js
  26728. * const geometry = new THREE.OctahedronGeometry();
  26729. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26730. * const octahedron = new THREE.Mesh( geometry, material );
  26731. * scene.add( octahedron );
  26732. * ```
  26733. *
  26734. * @augments PolyhedronGeometry
  26735. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26736. */
  26737. class OctahedronGeometry extends PolyhedronGeometry {
  26738. /**
  26739. * Constructs a new octahedron geometry.
  26740. *
  26741. * @param {number} [radius=1] - Radius of the octahedron.
  26742. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26743. */
  26744. constructor( radius = 1, detail = 0 ) {
  26745. const vertices = [
  26746. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26747. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26748. ];
  26749. const indices = [
  26750. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26751. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26752. 1, 3, 4, 1, 4, 2
  26753. ];
  26754. super( vertices, indices, radius, detail );
  26755. this.type = 'OctahedronGeometry';
  26756. /**
  26757. * Holds the constructor parameters that have been
  26758. * used to generate the geometry. Any modification
  26759. * after instantiation does not change the geometry.
  26760. *
  26761. * @type {Object}
  26762. */
  26763. this.parameters = {
  26764. radius: radius,
  26765. detail: detail
  26766. };
  26767. }
  26768. /**
  26769. * Factory method for creating an instance of this class from the given
  26770. * JSON object.
  26771. *
  26772. * @param {Object} data - A JSON object representing the serialized geometry.
  26773. * @return {OctahedronGeometry} A new instance.
  26774. */
  26775. static fromJSON( data ) {
  26776. return new OctahedronGeometry( data.radius, data.detail );
  26777. }
  26778. }
  26779. /**
  26780. * A geometry class for representing a plane.
  26781. *
  26782. * ```js
  26783. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26784. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26785. * const plane = new THREE.Mesh( geometry, material );
  26786. * scene.add( plane );
  26787. * ```
  26788. *
  26789. * @augments BufferGeometry
  26790. * @demo scenes/geometry-browser.html#PlaneGeometry
  26791. */
  26792. class PlaneGeometry extends BufferGeometry {
  26793. /**
  26794. * Constructs a new plane geometry.
  26795. *
  26796. * @param {number} [width=1] - The width along the X axis.
  26797. * @param {number} [height=1] - The height along the Y axis
  26798. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26799. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26800. */
  26801. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26802. super();
  26803. this.type = 'PlaneGeometry';
  26804. /**
  26805. * Holds the constructor parameters that have been
  26806. * used to generate the geometry. Any modification
  26807. * after instantiation does not change the geometry.
  26808. *
  26809. * @type {Object}
  26810. */
  26811. this.parameters = {
  26812. width: width,
  26813. height: height,
  26814. widthSegments: widthSegments,
  26815. heightSegments: heightSegments
  26816. };
  26817. const width_half = width / 2;
  26818. const height_half = height / 2;
  26819. const gridX = Math.floor( widthSegments );
  26820. const gridY = Math.floor( heightSegments );
  26821. const gridX1 = gridX + 1;
  26822. const gridY1 = gridY + 1;
  26823. const segment_width = width / gridX;
  26824. const segment_height = height / gridY;
  26825. //
  26826. const indices = [];
  26827. const vertices = [];
  26828. const normals = [];
  26829. const uvs = [];
  26830. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26831. const y = iy * segment_height - height_half;
  26832. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26833. const x = ix * segment_width - width_half;
  26834. vertices.push( x, - y, 0 );
  26835. normals.push( 0, 0, 1 );
  26836. uvs.push( ix / gridX );
  26837. uvs.push( 1 - ( iy / gridY ) );
  26838. }
  26839. }
  26840. for ( let iy = 0; iy < gridY; iy ++ ) {
  26841. for ( let ix = 0; ix < gridX; ix ++ ) {
  26842. const a = ix + gridX1 * iy;
  26843. const b = ix + gridX1 * ( iy + 1 );
  26844. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26845. const d = ( ix + 1 ) + gridX1 * iy;
  26846. indices.push( a, b, d );
  26847. indices.push( b, c, d );
  26848. }
  26849. }
  26850. this.setIndex( indices );
  26851. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26852. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26853. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26854. }
  26855. copy( source ) {
  26856. super.copy( source );
  26857. this.parameters = Object.assign( {}, source.parameters );
  26858. return this;
  26859. }
  26860. /**
  26861. * Factory method for creating an instance of this class from the given
  26862. * JSON object.
  26863. *
  26864. * @param {Object} data - A JSON object representing the serialized geometry.
  26865. * @return {PlaneGeometry} A new instance.
  26866. */
  26867. static fromJSON( data ) {
  26868. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26869. }
  26870. }
  26871. /**
  26872. * A class for generating a two-dimensional ring geometry.
  26873. *
  26874. * ```js
  26875. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26876. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26877. * const mesh = new THREE.Mesh( geometry, material );
  26878. * scene.add( mesh );
  26879. * ```
  26880. *
  26881. * @augments BufferGeometry
  26882. * @demo scenes/geometry-browser.html#RingGeometry
  26883. */
  26884. class RingGeometry extends BufferGeometry {
  26885. /**
  26886. * Constructs a new ring geometry.
  26887. *
  26888. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26889. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26890. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26891. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26892. * @param {number} [thetaStart=0] - Starting angle in radians.
  26893. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26894. */
  26895. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26896. super();
  26897. this.type = 'RingGeometry';
  26898. /**
  26899. * Holds the constructor parameters that have been
  26900. * used to generate the geometry. Any modification
  26901. * after instantiation does not change the geometry.
  26902. *
  26903. * @type {Object}
  26904. */
  26905. this.parameters = {
  26906. innerRadius: innerRadius,
  26907. outerRadius: outerRadius,
  26908. thetaSegments: thetaSegments,
  26909. phiSegments: phiSegments,
  26910. thetaStart: thetaStart,
  26911. thetaLength: thetaLength
  26912. };
  26913. thetaSegments = Math.max( 3, thetaSegments );
  26914. phiSegments = Math.max( 1, phiSegments );
  26915. // buffers
  26916. const indices = [];
  26917. const vertices = [];
  26918. const normals = [];
  26919. const uvs = [];
  26920. // some helper variables
  26921. let radius = innerRadius;
  26922. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26923. const vertex = new Vector3();
  26924. const uv = new Vector2();
  26925. // generate vertices, normals and uvs
  26926. for ( let j = 0; j <= phiSegments; j ++ ) {
  26927. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26928. // values are generate from the inside of the ring to the outside
  26929. const segment = thetaStart + i / thetaSegments * thetaLength;
  26930. // vertex
  26931. vertex.x = radius * Math.cos( segment );
  26932. vertex.y = radius * Math.sin( segment );
  26933. vertices.push( vertex.x, vertex.y, vertex.z );
  26934. // normal
  26935. normals.push( 0, 0, 1 );
  26936. // uv
  26937. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26938. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26939. uvs.push( uv.x, uv.y );
  26940. }
  26941. // increase the radius for next row of vertices
  26942. radius += radiusStep;
  26943. }
  26944. // indices
  26945. for ( let j = 0; j < phiSegments; j ++ ) {
  26946. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26947. for ( let i = 0; i < thetaSegments; i ++ ) {
  26948. const segment = i + thetaSegmentLevel;
  26949. const a = segment;
  26950. const b = segment + thetaSegments + 1;
  26951. const c = segment + thetaSegments + 2;
  26952. const d = segment + 1;
  26953. // faces
  26954. indices.push( a, b, d );
  26955. indices.push( b, c, d );
  26956. }
  26957. }
  26958. // build geometry
  26959. this.setIndex( indices );
  26960. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26961. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26962. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26963. }
  26964. copy( source ) {
  26965. super.copy( source );
  26966. this.parameters = Object.assign( {}, source.parameters );
  26967. return this;
  26968. }
  26969. /**
  26970. * Factory method for creating an instance of this class from the given
  26971. * JSON object.
  26972. *
  26973. * @param {Object} data - A JSON object representing the serialized geometry.
  26974. * @return {RingGeometry} A new instance.
  26975. */
  26976. static fromJSON( data ) {
  26977. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26978. }
  26979. }
  26980. /**
  26981. * Creates an one-sided polygonal geometry from one or more path shapes.
  26982. *
  26983. * ```js
  26984. * const arcShape = new THREE.Shape()
  26985. * .moveTo( 5, 1 )
  26986. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26987. *
  26988. * const geometry = new THREE.ShapeGeometry( arcShape );
  26989. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26990. * const mesh = new THREE.Mesh( geometry, material ) ;
  26991. * scene.add( mesh );
  26992. * ```
  26993. *
  26994. * @augments BufferGeometry
  26995. * @demo scenes/geometry-browser.html#ShapeGeometry
  26996. */
  26997. class ShapeGeometry extends BufferGeometry {
  26998. /**
  26999. * Constructs a new shape geometry.
  27000. *
  27001. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  27002. * @param {number} [curveSegments=12] - Number of segments per shape.
  27003. */
  27004. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  27005. super();
  27006. this.type = 'ShapeGeometry';
  27007. /**
  27008. * Holds the constructor parameters that have been
  27009. * used to generate the geometry. Any modification
  27010. * after instantiation does not change the geometry.
  27011. *
  27012. * @type {Object}
  27013. */
  27014. this.parameters = {
  27015. shapes: shapes,
  27016. curveSegments: curveSegments
  27017. };
  27018. // buffers
  27019. const indices = [];
  27020. const vertices = [];
  27021. const normals = [];
  27022. const uvs = [];
  27023. // helper variables
  27024. let groupStart = 0;
  27025. let groupCount = 0;
  27026. // allow single and array values for "shapes" parameter
  27027. if ( Array.isArray( shapes ) === false ) {
  27028. addShape( shapes );
  27029. } else {
  27030. for ( let i = 0; i < shapes.length; i ++ ) {
  27031. addShape( shapes[ i ] );
  27032. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  27033. groupStart += groupCount;
  27034. groupCount = 0;
  27035. }
  27036. }
  27037. // build geometry
  27038. this.setIndex( indices );
  27039. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27040. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27041. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27042. // helper functions
  27043. function addShape( shape ) {
  27044. const indexOffset = vertices.length / 3;
  27045. const points = shape.extractPoints( curveSegments );
  27046. let shapeVertices = points.shape;
  27047. const shapeHoles = points.holes;
  27048. // check direction of vertices
  27049. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  27050. shapeVertices = shapeVertices.reverse();
  27051. }
  27052. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27053. const shapeHole = shapeHoles[ i ];
  27054. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27055. shapeHoles[ i ] = shapeHole.reverse();
  27056. }
  27057. }
  27058. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27059. // join vertices of inner and outer paths to a single array
  27060. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27061. const shapeHole = shapeHoles[ i ];
  27062. shapeVertices = shapeVertices.concat( shapeHole );
  27063. }
  27064. // vertices, normals, uvs
  27065. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27066. const vertex = shapeVertices[ i ];
  27067. vertices.push( vertex.x, vertex.y, 0 );
  27068. normals.push( 0, 0, 1 );
  27069. uvs.push( vertex.x, vertex.y ); // world uvs
  27070. }
  27071. // indices
  27072. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27073. const face = faces[ i ];
  27074. const a = face[ 0 ] + indexOffset;
  27075. const b = face[ 1 ] + indexOffset;
  27076. const c = face[ 2 ] + indexOffset;
  27077. indices.push( a, b, c );
  27078. groupCount += 3;
  27079. }
  27080. }
  27081. }
  27082. copy( source ) {
  27083. super.copy( source );
  27084. this.parameters = Object.assign( {}, source.parameters );
  27085. return this;
  27086. }
  27087. toJSON() {
  27088. const data = super.toJSON();
  27089. const shapes = this.parameters.shapes;
  27090. return toJSON( shapes, data );
  27091. }
  27092. /**
  27093. * Factory method for creating an instance of this class from the given
  27094. * JSON object.
  27095. *
  27096. * @param {Object} data - A JSON object representing the serialized geometry.
  27097. * @param {Array<Shape>} shapes - An array of shapes.
  27098. * @return {ShapeGeometry} A new instance.
  27099. */
  27100. static fromJSON( data, shapes ) {
  27101. const geometryShapes = [];
  27102. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27103. const shape = shapes[ data.shapes[ j ] ];
  27104. geometryShapes.push( shape );
  27105. }
  27106. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27107. }
  27108. }
  27109. function toJSON( shapes, data ) {
  27110. data.shapes = [];
  27111. if ( Array.isArray( shapes ) ) {
  27112. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27113. const shape = shapes[ i ];
  27114. data.shapes.push( shape.uuid );
  27115. }
  27116. } else {
  27117. data.shapes.push( shapes.uuid );
  27118. }
  27119. return data;
  27120. }
  27121. /**
  27122. * A class for generating a sphere geometry.
  27123. *
  27124. * ```js
  27125. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27126. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27127. * const sphere = new THREE.Mesh( geometry, material );
  27128. * scene.add( sphere );
  27129. * ```
  27130. *
  27131. * @augments BufferGeometry
  27132. * @demo scenes/geometry-browser.html#SphereGeometry
  27133. */
  27134. class SphereGeometry extends BufferGeometry {
  27135. /**
  27136. * Constructs a new sphere geometry.
  27137. *
  27138. * @param {number} [radius=1] - The sphere radius.
  27139. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27140. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27141. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27142. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27143. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27144. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27145. */
  27146. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27147. super();
  27148. this.type = 'SphereGeometry';
  27149. /**
  27150. * Holds the constructor parameters that have been
  27151. * used to generate the geometry. Any modification
  27152. * after instantiation does not change the geometry.
  27153. *
  27154. * @type {Object}
  27155. */
  27156. this.parameters = {
  27157. radius: radius,
  27158. widthSegments: widthSegments,
  27159. heightSegments: heightSegments,
  27160. phiStart: phiStart,
  27161. phiLength: phiLength,
  27162. thetaStart: thetaStart,
  27163. thetaLength: thetaLength
  27164. };
  27165. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27166. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27167. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27168. let index = 0;
  27169. const grid = [];
  27170. const vertex = new Vector3();
  27171. const normal = new Vector3();
  27172. // buffers
  27173. const indices = [];
  27174. const vertices = [];
  27175. const normals = [];
  27176. const uvs = [];
  27177. // generate vertices, normals and uvs
  27178. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27179. const verticesRow = [];
  27180. const v = iy / heightSegments;
  27181. // special case for the poles
  27182. let uOffset = 0;
  27183. if ( iy === 0 && thetaStart === 0 ) {
  27184. uOffset = 0.5 / widthSegments;
  27185. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27186. uOffset = -0.5 / widthSegments;
  27187. }
  27188. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27189. const u = ix / widthSegments;
  27190. // vertex
  27191. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27192. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27193. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27194. vertices.push( vertex.x, vertex.y, vertex.z );
  27195. // normal
  27196. normal.copy( vertex ).normalize();
  27197. normals.push( normal.x, normal.y, normal.z );
  27198. // uv
  27199. uvs.push( u + uOffset, 1 - v );
  27200. verticesRow.push( index ++ );
  27201. }
  27202. grid.push( verticesRow );
  27203. }
  27204. // indices
  27205. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27206. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27207. const a = grid[ iy ][ ix + 1 ];
  27208. const b = grid[ iy ][ ix ];
  27209. const c = grid[ iy + 1 ][ ix ];
  27210. const d = grid[ iy + 1 ][ ix + 1 ];
  27211. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27212. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27213. }
  27214. }
  27215. // build geometry
  27216. this.setIndex( indices );
  27217. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27218. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27219. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27220. }
  27221. copy( source ) {
  27222. super.copy( source );
  27223. this.parameters = Object.assign( {}, source.parameters );
  27224. return this;
  27225. }
  27226. /**
  27227. * Factory method for creating an instance of this class from the given
  27228. * JSON object.
  27229. *
  27230. * @param {Object} data - A JSON object representing the serialized geometry.
  27231. * @return {SphereGeometry} A new instance.
  27232. */
  27233. static fromJSON( data ) {
  27234. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27235. }
  27236. }
  27237. /**
  27238. * A geometry class for representing an tetrahedron.
  27239. *
  27240. * ```js
  27241. * const geometry = new THREE.TetrahedronGeometry();
  27242. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27243. * const tetrahedron = new THREE.Mesh( geometry, material );
  27244. * scene.add( tetrahedron );
  27245. * ```
  27246. *
  27247. * @augments PolyhedronGeometry
  27248. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27249. */
  27250. class TetrahedronGeometry extends PolyhedronGeometry {
  27251. /**
  27252. * Constructs a new tetrahedron geometry.
  27253. *
  27254. * @param {number} [radius=1] - Radius of the tetrahedron.
  27255. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27256. */
  27257. constructor( radius = 1, detail = 0 ) {
  27258. const vertices = [
  27259. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27260. ];
  27261. const indices = [
  27262. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27263. ];
  27264. super( vertices, indices, radius, detail );
  27265. this.type = 'TetrahedronGeometry';
  27266. /**
  27267. * Holds the constructor parameters that have been
  27268. * used to generate the geometry. Any modification
  27269. * after instantiation does not change the geometry.
  27270. *
  27271. * @type {Object}
  27272. */
  27273. this.parameters = {
  27274. radius: radius,
  27275. detail: detail
  27276. };
  27277. }
  27278. /**
  27279. * Factory method for creating an instance of this class from the given
  27280. * JSON object.
  27281. *
  27282. * @param {Object} data - A JSON object representing the serialized geometry.
  27283. * @return {TetrahedronGeometry} A new instance.
  27284. */
  27285. static fromJSON( data ) {
  27286. return new TetrahedronGeometry( data.radius, data.detail );
  27287. }
  27288. }
  27289. /**
  27290. * A geometry class for representing an torus.
  27291. *
  27292. * ```js
  27293. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27294. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27295. * const torus = new THREE.Mesh( geometry, material );
  27296. * scene.add( torus );
  27297. * ```
  27298. *
  27299. * @augments BufferGeometry
  27300. * @demo scenes/geometry-browser.html#TorusGeometry
  27301. */
  27302. class TorusGeometry extends BufferGeometry {
  27303. /**
  27304. * Constructs a new torus geometry.
  27305. *
  27306. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27307. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27308. * @param {number} [radialSegments=12] - The number of radial segments.
  27309. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27310. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27311. */
  27312. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27313. super();
  27314. this.type = 'TorusGeometry';
  27315. /**
  27316. * Holds the constructor parameters that have been
  27317. * used to generate the geometry. Any modification
  27318. * after instantiation does not change the geometry.
  27319. *
  27320. * @type {Object}
  27321. */
  27322. this.parameters = {
  27323. radius: radius,
  27324. tube: tube,
  27325. radialSegments: radialSegments,
  27326. tubularSegments: tubularSegments,
  27327. arc: arc
  27328. };
  27329. radialSegments = Math.floor( radialSegments );
  27330. tubularSegments = Math.floor( tubularSegments );
  27331. // buffers
  27332. const indices = [];
  27333. const vertices = [];
  27334. const normals = [];
  27335. const uvs = [];
  27336. // helper variables
  27337. const center = new Vector3();
  27338. const vertex = new Vector3();
  27339. const normal = new Vector3();
  27340. // generate vertices, normals and uvs
  27341. for ( let j = 0; j <= radialSegments; j ++ ) {
  27342. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27343. const u = i / tubularSegments * arc;
  27344. const v = j / radialSegments * Math.PI * 2;
  27345. // vertex
  27346. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27347. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27348. vertex.z = tube * Math.sin( v );
  27349. vertices.push( vertex.x, vertex.y, vertex.z );
  27350. // normal
  27351. center.x = radius * Math.cos( u );
  27352. center.y = radius * Math.sin( u );
  27353. normal.subVectors( vertex, center ).normalize();
  27354. normals.push( normal.x, normal.y, normal.z );
  27355. // uv
  27356. uvs.push( i / tubularSegments );
  27357. uvs.push( j / radialSegments );
  27358. }
  27359. }
  27360. // generate indices
  27361. for ( let j = 1; j <= radialSegments; j ++ ) {
  27362. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27363. // indices
  27364. const a = ( tubularSegments + 1 ) * j + i - 1;
  27365. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27366. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27367. const d = ( tubularSegments + 1 ) * j + i;
  27368. // faces
  27369. indices.push( a, b, d );
  27370. indices.push( b, c, d );
  27371. }
  27372. }
  27373. // build geometry
  27374. this.setIndex( indices );
  27375. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27376. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27377. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27378. }
  27379. copy( source ) {
  27380. super.copy( source );
  27381. this.parameters = Object.assign( {}, source.parameters );
  27382. return this;
  27383. }
  27384. /**
  27385. * Factory method for creating an instance of this class from the given
  27386. * JSON object.
  27387. *
  27388. * @param {Object} data - A JSON object representing the serialized geometry.
  27389. * @return {TorusGeometry} A new instance.
  27390. */
  27391. static fromJSON( data ) {
  27392. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27393. }
  27394. }
  27395. /**
  27396. * Creates a torus knot, the particular shape of which is defined by a pair
  27397. * of coprime integers, p and q. If p and q are not coprime, the result will
  27398. * be a torus link.
  27399. *
  27400. * ```js
  27401. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27402. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27403. * const torusKnot = new THREE.Mesh( geometry, material );
  27404. * scene.add( torusKnot );
  27405. * ```
  27406. *
  27407. * @augments BufferGeometry
  27408. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27409. */
  27410. class TorusKnotGeometry extends BufferGeometry {
  27411. /**
  27412. * Constructs a new torus knot geometry.
  27413. *
  27414. * @param {number} [radius=1] - Radius of the torus knot.
  27415. * @param {number} [tube=0.4] - Radius of the tube.
  27416. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27417. * @param {number} [radialSegments=8] - The number of radial segments.
  27418. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27419. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27420. */
  27421. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27422. super();
  27423. this.type = 'TorusKnotGeometry';
  27424. /**
  27425. * Holds the constructor parameters that have been
  27426. * used to generate the geometry. Any modification
  27427. * after instantiation does not change the geometry.
  27428. *
  27429. * @type {Object}
  27430. */
  27431. this.parameters = {
  27432. radius: radius,
  27433. tube: tube,
  27434. tubularSegments: tubularSegments,
  27435. radialSegments: radialSegments,
  27436. p: p,
  27437. q: q
  27438. };
  27439. tubularSegments = Math.floor( tubularSegments );
  27440. radialSegments = Math.floor( radialSegments );
  27441. // buffers
  27442. const indices = [];
  27443. const vertices = [];
  27444. const normals = [];
  27445. const uvs = [];
  27446. // helper variables
  27447. const vertex = new Vector3();
  27448. const normal = new Vector3();
  27449. const P1 = new Vector3();
  27450. const P2 = new Vector3();
  27451. const B = new Vector3();
  27452. const T = new Vector3();
  27453. const N = new Vector3();
  27454. // generate vertices, normals and uvs
  27455. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27456. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27457. const u = i / tubularSegments * p * Math.PI * 2;
  27458. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27459. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27460. calculatePositionOnCurve( u, p, q, radius, P1 );
  27461. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27462. // calculate orthonormal basis
  27463. T.subVectors( P2, P1 );
  27464. N.addVectors( P2, P1 );
  27465. B.crossVectors( T, N );
  27466. N.crossVectors( B, T );
  27467. // normalize B, N. T can be ignored, we don't use it
  27468. B.normalize();
  27469. N.normalize();
  27470. for ( let j = 0; j <= radialSegments; ++ j ) {
  27471. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27472. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27473. const v = j / radialSegments * Math.PI * 2;
  27474. const cx = - tube * Math.cos( v );
  27475. const cy = tube * Math.sin( v );
  27476. // now calculate the final vertex position.
  27477. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27478. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27479. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27480. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27481. vertices.push( vertex.x, vertex.y, vertex.z );
  27482. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27483. normal.subVectors( vertex, P1 ).normalize();
  27484. normals.push( normal.x, normal.y, normal.z );
  27485. // uv
  27486. uvs.push( i / tubularSegments );
  27487. uvs.push( j / radialSegments );
  27488. }
  27489. }
  27490. // generate indices
  27491. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27492. for ( let i = 1; i <= radialSegments; i ++ ) {
  27493. // indices
  27494. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27495. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27496. const c = ( radialSegments + 1 ) * j + i;
  27497. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27498. // faces
  27499. indices.push( a, b, d );
  27500. indices.push( b, c, d );
  27501. }
  27502. }
  27503. // build geometry
  27504. this.setIndex( indices );
  27505. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27506. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27507. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27508. // this function calculates the current position on the torus curve
  27509. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27510. const cu = Math.cos( u );
  27511. const su = Math.sin( u );
  27512. const quOverP = q / p * u;
  27513. const cs = Math.cos( quOverP );
  27514. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27515. position.y = radius * ( 2 + cs ) * su * 0.5;
  27516. position.z = radius * Math.sin( quOverP ) * 0.5;
  27517. }
  27518. }
  27519. copy( source ) {
  27520. super.copy( source );
  27521. this.parameters = Object.assign( {}, source.parameters );
  27522. return this;
  27523. }
  27524. /**
  27525. * Factory method for creating an instance of this class from the given
  27526. * JSON object.
  27527. *
  27528. * @param {Object} data - A JSON object representing the serialized geometry.
  27529. * @return {TorusKnotGeometry} A new instance.
  27530. */
  27531. static fromJSON( data ) {
  27532. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27533. }
  27534. }
  27535. /**
  27536. * Creates a tube that extrudes along a 3D curve.
  27537. *
  27538. * ```js
  27539. * class CustomSinCurve extends THREE.Curve {
  27540. *
  27541. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27542. *
  27543. * const tx = t * 3 - 1.5;
  27544. * const ty = Math.sin( 2 * Math.PI * t );
  27545. * const tz = 0;
  27546. *
  27547. * return optionalTarget.set( tx, ty, tz );
  27548. * }
  27549. *
  27550. * }
  27551. *
  27552. * const path = new CustomSinCurve( 10 );
  27553. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27554. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27555. * const mesh = new THREE.Mesh( geometry, material );
  27556. * scene.add( mesh );
  27557. * ```
  27558. *
  27559. * @augments BufferGeometry
  27560. * @demo scenes/geometry-browser.html#TubeGeometry
  27561. */
  27562. class TubeGeometry extends BufferGeometry {
  27563. /**
  27564. * Constructs a new tube geometry.
  27565. *
  27566. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27567. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27568. * @param {number} [radius=1] -The radius of the tube.
  27569. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27570. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27571. */
  27572. 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 ) {
  27573. super();
  27574. this.type = 'TubeGeometry';
  27575. /**
  27576. * Holds the constructor parameters that have been
  27577. * used to generate the geometry. Any modification
  27578. * after instantiation does not change the geometry.
  27579. *
  27580. * @type {Object}
  27581. */
  27582. this.parameters = {
  27583. path: path,
  27584. tubularSegments: tubularSegments,
  27585. radius: radius,
  27586. radialSegments: radialSegments,
  27587. closed: closed
  27588. };
  27589. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27590. // expose internals
  27591. this.tangents = frames.tangents;
  27592. this.normals = frames.normals;
  27593. this.binormals = frames.binormals;
  27594. // helper variables
  27595. const vertex = new Vector3();
  27596. const normal = new Vector3();
  27597. const uv = new Vector2();
  27598. let P = new Vector3();
  27599. // buffer
  27600. const vertices = [];
  27601. const normals = [];
  27602. const uvs = [];
  27603. const indices = [];
  27604. // create buffer data
  27605. generateBufferData();
  27606. // build geometry
  27607. this.setIndex( indices );
  27608. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27609. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27610. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27611. // functions
  27612. function generateBufferData() {
  27613. for ( let i = 0; i < tubularSegments; i ++ ) {
  27614. generateSegment( i );
  27615. }
  27616. // if the geometry is not closed, generate the last row of vertices and normals
  27617. // at the regular position on the given path
  27618. //
  27619. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27620. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27621. // uvs are generated in a separate function.
  27622. // this makes it easy compute correct values for closed geometries
  27623. generateUVs();
  27624. // finally create faces
  27625. generateIndices();
  27626. }
  27627. function generateSegment( i ) {
  27628. // we use getPointAt to sample evenly distributed points from the given path
  27629. P = path.getPointAt( i / tubularSegments, P );
  27630. // retrieve corresponding normal and binormal
  27631. const N = frames.normals[ i ];
  27632. const B = frames.binormals[ i ];
  27633. // generate normals and vertices for the current segment
  27634. for ( let j = 0; j <= radialSegments; j ++ ) {
  27635. const v = j / radialSegments * Math.PI * 2;
  27636. const sin = Math.sin( v );
  27637. const cos = - Math.cos( v );
  27638. // normal
  27639. normal.x = ( cos * N.x + sin * B.x );
  27640. normal.y = ( cos * N.y + sin * B.y );
  27641. normal.z = ( cos * N.z + sin * B.z );
  27642. normal.normalize();
  27643. normals.push( normal.x, normal.y, normal.z );
  27644. // vertex
  27645. vertex.x = P.x + radius * normal.x;
  27646. vertex.y = P.y + radius * normal.y;
  27647. vertex.z = P.z + radius * normal.z;
  27648. vertices.push( vertex.x, vertex.y, vertex.z );
  27649. }
  27650. }
  27651. function generateIndices() {
  27652. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27653. for ( let i = 1; i <= radialSegments; i ++ ) {
  27654. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27655. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27656. const c = ( radialSegments + 1 ) * j + i;
  27657. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27658. // faces
  27659. indices.push( a, b, d );
  27660. indices.push( b, c, d );
  27661. }
  27662. }
  27663. }
  27664. function generateUVs() {
  27665. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27666. for ( let j = 0; j <= radialSegments; j ++ ) {
  27667. uv.x = i / tubularSegments;
  27668. uv.y = j / radialSegments;
  27669. uvs.push( uv.x, uv.y );
  27670. }
  27671. }
  27672. }
  27673. }
  27674. copy( source ) {
  27675. super.copy( source );
  27676. this.parameters = Object.assign( {}, source.parameters );
  27677. return this;
  27678. }
  27679. toJSON() {
  27680. const data = super.toJSON();
  27681. data.path = this.parameters.path.toJSON();
  27682. return data;
  27683. }
  27684. /**
  27685. * Factory method for creating an instance of this class from the given
  27686. * JSON object.
  27687. *
  27688. * @param {Object} data - A JSON object representing the serialized geometry.
  27689. * @return {TubeGeometry} A new instance.
  27690. */
  27691. static fromJSON( data ) {
  27692. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27693. // User defined curves or instances of CurvePath will not be deserialized.
  27694. return new TubeGeometry(
  27695. new Curves[ data.path.type ]().fromJSON( data.path ),
  27696. data.tubularSegments,
  27697. data.radius,
  27698. data.radialSegments,
  27699. data.closed
  27700. );
  27701. }
  27702. }
  27703. /**
  27704. * Can be used as a helper object to visualize a geometry as a wireframe.
  27705. *
  27706. * ```js
  27707. * const geometry = new THREE.SphereGeometry();
  27708. *
  27709. * const wireframe = new THREE.WireframeGeometry( geometry );
  27710. *
  27711. * const line = new THREE.LineSegments( wireframe );
  27712. * line.material.depthWrite = false;
  27713. * line.material.opacity = 0.25;
  27714. * line.material.transparent = true;
  27715. *
  27716. * scene.add( line );
  27717. * ```
  27718. *
  27719. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27720. *
  27721. * @augments BufferGeometry
  27722. */
  27723. class WireframeGeometry extends BufferGeometry {
  27724. /**
  27725. * Constructs a new wireframe geometry.
  27726. *
  27727. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27728. */
  27729. constructor( geometry = null ) {
  27730. super();
  27731. this.type = 'WireframeGeometry';
  27732. /**
  27733. * Holds the constructor parameters that have been
  27734. * used to generate the geometry. Any modification
  27735. * after instantiation does not change the geometry.
  27736. *
  27737. * @type {Object}
  27738. */
  27739. this.parameters = {
  27740. geometry: geometry
  27741. };
  27742. if ( geometry !== null ) {
  27743. // buffer
  27744. const vertices = [];
  27745. const edges = new Set();
  27746. // helper variables
  27747. const start = new Vector3();
  27748. const end = new Vector3();
  27749. if ( geometry.index !== null ) {
  27750. // indexed BufferGeometry
  27751. const position = geometry.attributes.position;
  27752. const indices = geometry.index;
  27753. let groups = geometry.groups;
  27754. if ( groups.length === 0 ) {
  27755. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27756. }
  27757. // create a data structure that contains all edges without duplicates
  27758. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27759. const group = groups[ o ];
  27760. const groupStart = group.start;
  27761. const groupCount = group.count;
  27762. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27763. for ( let j = 0; j < 3; j ++ ) {
  27764. const index1 = indices.getX( i + j );
  27765. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27766. start.fromBufferAttribute( position, index1 );
  27767. end.fromBufferAttribute( position, index2 );
  27768. if ( isUniqueEdge( start, end, edges ) === true ) {
  27769. vertices.push( start.x, start.y, start.z );
  27770. vertices.push( end.x, end.y, end.z );
  27771. }
  27772. }
  27773. }
  27774. }
  27775. } else {
  27776. // non-indexed BufferGeometry
  27777. const position = geometry.attributes.position;
  27778. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27779. for ( let j = 0; j < 3; j ++ ) {
  27780. // three edges per triangle, an edge is represented as (index1, index2)
  27781. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27782. const index1 = 3 * i + j;
  27783. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27784. start.fromBufferAttribute( position, index1 );
  27785. end.fromBufferAttribute( position, index2 );
  27786. if ( isUniqueEdge( start, end, edges ) === true ) {
  27787. vertices.push( start.x, start.y, start.z );
  27788. vertices.push( end.x, end.y, end.z );
  27789. }
  27790. }
  27791. }
  27792. }
  27793. // build geometry
  27794. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27795. }
  27796. }
  27797. copy( source ) {
  27798. super.copy( source );
  27799. this.parameters = Object.assign( {}, source.parameters );
  27800. return this;
  27801. }
  27802. }
  27803. function isUniqueEdge( start, end, edges ) {
  27804. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27805. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27806. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27807. return false;
  27808. } else {
  27809. edges.add( hash1 );
  27810. edges.add( hash2 );
  27811. return true;
  27812. }
  27813. }
  27814. var Geometries = /*#__PURE__*/Object.freeze({
  27815. __proto__: null,
  27816. BoxGeometry: BoxGeometry,
  27817. CapsuleGeometry: CapsuleGeometry,
  27818. CircleGeometry: CircleGeometry,
  27819. ConeGeometry: ConeGeometry,
  27820. CylinderGeometry: CylinderGeometry,
  27821. DodecahedronGeometry: DodecahedronGeometry,
  27822. EdgesGeometry: EdgesGeometry,
  27823. ExtrudeGeometry: ExtrudeGeometry,
  27824. IcosahedronGeometry: IcosahedronGeometry,
  27825. LatheGeometry: LatheGeometry,
  27826. OctahedronGeometry: OctahedronGeometry,
  27827. PlaneGeometry: PlaneGeometry,
  27828. PolyhedronGeometry: PolyhedronGeometry,
  27829. RingGeometry: RingGeometry,
  27830. ShapeGeometry: ShapeGeometry,
  27831. SphereGeometry: SphereGeometry,
  27832. TetrahedronGeometry: TetrahedronGeometry,
  27833. TorusGeometry: TorusGeometry,
  27834. TorusKnotGeometry: TorusKnotGeometry,
  27835. TubeGeometry: TubeGeometry,
  27836. WireframeGeometry: WireframeGeometry
  27837. });
  27838. /**
  27839. * This material can receive shadows, but otherwise is completely transparent.
  27840. *
  27841. * ```js
  27842. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27843. * geometry.rotateX( - Math.PI / 2 );
  27844. *
  27845. * const material = new THREE.ShadowMaterial();
  27846. * material.opacity = 0.2;
  27847. *
  27848. * const plane = new THREE.Mesh( geometry, material );
  27849. * plane.position.y = -200;
  27850. * plane.receiveShadow = true;
  27851. * scene.add( plane );
  27852. * ```
  27853. *
  27854. * @augments Material
  27855. */
  27856. class ShadowMaterial extends Material {
  27857. /**
  27858. * Constructs a new shadow material.
  27859. *
  27860. * @param {Object} [parameters] - An object with one or more properties
  27861. * defining the material's appearance. Any property of the material
  27862. * (including any property from inherited materials) can be passed
  27863. * in here. Color values can be passed any type of value accepted
  27864. * by {@link Color#set}.
  27865. */
  27866. constructor( parameters ) {
  27867. super();
  27868. /**
  27869. * This flag can be used for type testing.
  27870. *
  27871. * @type {boolean}
  27872. * @readonly
  27873. * @default true
  27874. */
  27875. this.isShadowMaterial = true;
  27876. this.type = 'ShadowMaterial';
  27877. /**
  27878. * Color of the material.
  27879. *
  27880. * @type {Color}
  27881. * @default (0,0,0)
  27882. */
  27883. this.color = new Color( 0x000000 );
  27884. /**
  27885. * Overwritten since shadow materials are transparent
  27886. * by default.
  27887. *
  27888. * @type {boolean}
  27889. * @default true
  27890. */
  27891. this.transparent = true;
  27892. /**
  27893. * Whether the material is affected by fog or not.
  27894. *
  27895. * @type {boolean}
  27896. * @default true
  27897. */
  27898. this.fog = true;
  27899. this.setValues( parameters );
  27900. }
  27901. copy( source ) {
  27902. super.copy( source );
  27903. this.color.copy( source.color );
  27904. this.fog = source.fog;
  27905. return this;
  27906. }
  27907. }
  27908. /**
  27909. * This class works just like {@link ShaderMaterial}, except that definitions
  27910. * of built-in uniforms and attributes are not automatically prepended to the
  27911. * GLSL shader code.
  27912. *
  27913. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27914. *
  27915. * @augments ShaderMaterial
  27916. */
  27917. class RawShaderMaterial extends ShaderMaterial {
  27918. /**
  27919. * Constructs a new raw shader material.
  27920. *
  27921. * @param {Object} [parameters] - An object with one or more properties
  27922. * defining the material's appearance. Any property of the material
  27923. * (including any property from inherited materials) can be passed
  27924. * in here. Color values can be passed any type of value accepted
  27925. * by {@link Color#set}.
  27926. */
  27927. constructor( parameters ) {
  27928. super( parameters );
  27929. /**
  27930. * This flag can be used for type testing.
  27931. *
  27932. * @type {boolean}
  27933. * @readonly
  27934. * @default true
  27935. */
  27936. this.isRawShaderMaterial = true;
  27937. this.type = 'RawShaderMaterial';
  27938. }
  27939. }
  27940. /**
  27941. * A standard physically based material, using Metallic-Roughness workflow.
  27942. *
  27943. * Physically based rendering (PBR) has recently become the standard in many
  27944. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27945. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27946. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27947. *
  27948. * This approach differs from older approaches in that instead of using
  27949. * approximations for the way in which light interacts with a surface, a
  27950. * physically correct model is used. The idea is that, instead of tweaking
  27951. * materials to look good under specific lighting, a material can be created
  27952. * that will react 'correctly' under all lighting scenarios.
  27953. *
  27954. * In practice this gives a more accurate and realistic looking result than
  27955. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27956. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27957. * shading.
  27958. *
  27959. * Note that for best results you should always specify an environment map when using this material.
  27960. *
  27961. * For a non-technical introduction to the concept of PBR and how to set up a
  27962. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27963. *
  27964. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27965. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27966. *
  27967. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27968. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27969. * (pdf), by Brent Burley.
  27970. *
  27971. * @augments Material
  27972. * @demo scenes/material-browser.html#MeshStandardMaterial
  27973. */
  27974. class MeshStandardMaterial extends Material {
  27975. /**
  27976. * Constructs a new mesh standard material.
  27977. *
  27978. * @param {Object} [parameters] - An object with one or more properties
  27979. * defining the material's appearance. Any property of the material
  27980. * (including any property from inherited materials) can be passed
  27981. * in here. Color values can be passed any type of value accepted
  27982. * by {@link Color#set}.
  27983. */
  27984. constructor( parameters ) {
  27985. super();
  27986. /**
  27987. * This flag can be used for type testing.
  27988. *
  27989. * @type {boolean}
  27990. * @readonly
  27991. * @default true
  27992. */
  27993. this.isMeshStandardMaterial = true;
  27994. this.type = 'MeshStandardMaterial';
  27995. this.defines = { 'STANDARD': '' };
  27996. /**
  27997. * Color of the material.
  27998. *
  27999. * @type {Color}
  28000. * @default (1,1,1)
  28001. */
  28002. this.color = new Color( 0xffffff ); // diffuse
  28003. /**
  28004. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  28005. * means fully diffuse. If `roughnessMap` is also provided,
  28006. * both values are multiplied.
  28007. *
  28008. * @type {number}
  28009. * @default 1
  28010. */
  28011. this.roughness = 1.0;
  28012. /**
  28013. * How much the material is like a metal. Non-metallic materials such as wood
  28014. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  28015. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  28016. * If `metalnessMap` is also provided, both values are multiplied.
  28017. *
  28018. * @type {number}
  28019. * @default 0
  28020. */
  28021. this.metalness = 0.0;
  28022. /**
  28023. * The color map. May optionally include an alpha channel, typically combined
  28024. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28025. * color is modulated by the diffuse `color`.
  28026. *
  28027. * @type {?Texture}
  28028. * @default null
  28029. */
  28030. this.map = null;
  28031. /**
  28032. * The light map. Requires a second set of UVs.
  28033. *
  28034. * @type {?Texture}
  28035. * @default null
  28036. */
  28037. this.lightMap = null;
  28038. /**
  28039. * Intensity of the baked light.
  28040. *
  28041. * @type {number}
  28042. * @default 1
  28043. */
  28044. this.lightMapIntensity = 1.0;
  28045. /**
  28046. * The red channel of this texture is used as the ambient occlusion map.
  28047. * Requires a second set of UVs.
  28048. *
  28049. * @type {?Texture}
  28050. * @default null
  28051. */
  28052. this.aoMap = null;
  28053. /**
  28054. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28055. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28056. * red channel is also `1`, ambient light is fully occluded on a surface.
  28057. *
  28058. * @type {number}
  28059. * @default 1
  28060. */
  28061. this.aoMapIntensity = 1.0;
  28062. /**
  28063. * Emissive (light) color of the material, essentially a solid color
  28064. * unaffected by other lighting.
  28065. *
  28066. * @type {Color}
  28067. * @default (0,0,0)
  28068. */
  28069. this.emissive = new Color( 0x000000 );
  28070. /**
  28071. * Intensity of the emissive light. Modulates the emissive color.
  28072. *
  28073. * @type {number}
  28074. * @default 1
  28075. */
  28076. this.emissiveIntensity = 1.0;
  28077. /**
  28078. * Set emissive (glow) map. The emissive map color is modulated by the
  28079. * emissive color and the emissive intensity. If you have an emissive map,
  28080. * be sure to set the emissive color to something other than black.
  28081. *
  28082. * @type {?Texture}
  28083. * @default null
  28084. */
  28085. this.emissiveMap = null;
  28086. /**
  28087. * The texture to create a bump map. The black and white values map to the
  28088. * perceived depth in relation to the lights. Bump doesn't actually affect
  28089. * the geometry of the object, only the lighting. If a normal map is defined
  28090. * this will be ignored.
  28091. *
  28092. * @type {?Texture}
  28093. * @default null
  28094. */
  28095. this.bumpMap = null;
  28096. /**
  28097. * How much the bump map affects the material. Typical range is `[0,1]`.
  28098. *
  28099. * @type {number}
  28100. * @default 1
  28101. */
  28102. this.bumpScale = 1;
  28103. /**
  28104. * The texture to create a normal map. The RGB values affect the surface
  28105. * normal for each pixel fragment and change the way the color is lit. Normal
  28106. * maps do not change the actual shape of the surface, only the lighting. In
  28107. * case the material has a normal map authored using the left handed
  28108. * convention, the `y` component of `normalScale` should be negated to compensate
  28109. * for the different handedness.
  28110. *
  28111. * @type {?Texture}
  28112. * @default null
  28113. */
  28114. this.normalMap = null;
  28115. /**
  28116. * The type of normal map.
  28117. *
  28118. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28119. * @default TangentSpaceNormalMap
  28120. */
  28121. this.normalMapType = TangentSpaceNormalMap;
  28122. /**
  28123. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28124. *
  28125. * @type {Vector2}
  28126. * @default (1,1)
  28127. */
  28128. this.normalScale = new Vector2( 1, 1 );
  28129. /**
  28130. * The displacement map affects the position of the mesh's vertices. Unlike
  28131. * other maps which only affect the light and shade of the material the
  28132. * displaced vertices can cast shadows, block other objects, and otherwise
  28133. * act as real geometry. The displacement texture is an image where the value
  28134. * of each pixel (white being the highest) is mapped against, and
  28135. * repositions, the vertices of the mesh.
  28136. *
  28137. * @type {?Texture}
  28138. * @default null
  28139. */
  28140. this.displacementMap = null;
  28141. /**
  28142. * How much the displacement map affects the mesh (where black is no
  28143. * displacement, and white is maximum displacement). Without a displacement
  28144. * map set, this value is not applied.
  28145. *
  28146. * @type {number}
  28147. * @default 0
  28148. */
  28149. this.displacementScale = 1;
  28150. /**
  28151. * The offset of the displacement map's values on the mesh's vertices.
  28152. * The bias is added to the scaled sample of the displacement map.
  28153. * Without a displacement map set, this value is not applied.
  28154. *
  28155. * @type {number}
  28156. * @default 0
  28157. */
  28158. this.displacementBias = 0;
  28159. /**
  28160. * The green channel of this texture is used to alter the roughness of the
  28161. * material.
  28162. *
  28163. * @type {?Texture}
  28164. * @default null
  28165. */
  28166. this.roughnessMap = null;
  28167. /**
  28168. * The blue channel of this texture is used to alter the metalness of the
  28169. * material.
  28170. *
  28171. * @type {?Texture}
  28172. * @default null
  28173. */
  28174. this.metalnessMap = null;
  28175. /**
  28176. * The alpha map is a grayscale texture that controls the opacity across the
  28177. * surface (black: fully transparent; white: fully opaque).
  28178. *
  28179. * Only the color of the texture is used, ignoring the alpha channel if one
  28180. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28181. * when sampling this texture due to the extra bit of precision provided for
  28182. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28183. * luminance/alpha textures will also still work as expected.
  28184. *
  28185. * @type {?Texture}
  28186. * @default null
  28187. */
  28188. this.alphaMap = null;
  28189. /**
  28190. * The environment map. To ensure a physically correct rendering, environment maps
  28191. * are internally pre-processed with {@link PMREMGenerator}.
  28192. *
  28193. * @type {?Texture}
  28194. * @default null
  28195. */
  28196. this.envMap = null;
  28197. /**
  28198. * The rotation of the environment map in radians.
  28199. *
  28200. * @type {Euler}
  28201. * @default (0,0,0)
  28202. */
  28203. this.envMapRotation = new Euler();
  28204. /**
  28205. * Scales the effect of the environment map by multiplying its color.
  28206. *
  28207. * @type {number}
  28208. * @default 1
  28209. */
  28210. this.envMapIntensity = 1.0;
  28211. /**
  28212. * Renders the geometry as a wireframe.
  28213. *
  28214. * @type {boolean}
  28215. * @default false
  28216. */
  28217. this.wireframe = false;
  28218. /**
  28219. * Controls the thickness of the wireframe.
  28220. *
  28221. * Can only be used with {@link SVGRenderer}.
  28222. *
  28223. * @type {number}
  28224. * @default 1
  28225. */
  28226. this.wireframeLinewidth = 1;
  28227. /**
  28228. * Defines appearance of wireframe ends.
  28229. *
  28230. * Can only be used with {@link SVGRenderer}.
  28231. *
  28232. * @type {('round'|'bevel'|'miter')}
  28233. * @default 'round'
  28234. */
  28235. this.wireframeLinecap = 'round';
  28236. /**
  28237. * Defines appearance of wireframe joints.
  28238. *
  28239. * Can only be used with {@link SVGRenderer}.
  28240. *
  28241. * @type {('round'|'bevel'|'miter')}
  28242. * @default 'round'
  28243. */
  28244. this.wireframeLinejoin = 'round';
  28245. /**
  28246. * Whether the material is rendered with flat shading or not.
  28247. *
  28248. * @type {boolean}
  28249. * @default false
  28250. */
  28251. this.flatShading = false;
  28252. /**
  28253. * Whether the material is affected by fog or not.
  28254. *
  28255. * @type {boolean}
  28256. * @default true
  28257. */
  28258. this.fog = true;
  28259. this.setValues( parameters );
  28260. }
  28261. copy( source ) {
  28262. super.copy( source );
  28263. this.defines = { 'STANDARD': '' };
  28264. this.color.copy( source.color );
  28265. this.roughness = source.roughness;
  28266. this.metalness = source.metalness;
  28267. this.map = source.map;
  28268. this.lightMap = source.lightMap;
  28269. this.lightMapIntensity = source.lightMapIntensity;
  28270. this.aoMap = source.aoMap;
  28271. this.aoMapIntensity = source.aoMapIntensity;
  28272. this.emissive.copy( source.emissive );
  28273. this.emissiveMap = source.emissiveMap;
  28274. this.emissiveIntensity = source.emissiveIntensity;
  28275. this.bumpMap = source.bumpMap;
  28276. this.bumpScale = source.bumpScale;
  28277. this.normalMap = source.normalMap;
  28278. this.normalMapType = source.normalMapType;
  28279. this.normalScale.copy( source.normalScale );
  28280. this.displacementMap = source.displacementMap;
  28281. this.displacementScale = source.displacementScale;
  28282. this.displacementBias = source.displacementBias;
  28283. this.roughnessMap = source.roughnessMap;
  28284. this.metalnessMap = source.metalnessMap;
  28285. this.alphaMap = source.alphaMap;
  28286. this.envMap = source.envMap;
  28287. this.envMapRotation.copy( source.envMapRotation );
  28288. this.envMapIntensity = source.envMapIntensity;
  28289. this.wireframe = source.wireframe;
  28290. this.wireframeLinewidth = source.wireframeLinewidth;
  28291. this.wireframeLinecap = source.wireframeLinecap;
  28292. this.wireframeLinejoin = source.wireframeLinejoin;
  28293. this.flatShading = source.flatShading;
  28294. this.fog = source.fog;
  28295. return this;
  28296. }
  28297. }
  28298. /**
  28299. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28300. * physically-based rendering properties:
  28301. *
  28302. * - Anisotropy: Ability to represent the anisotropic property of materials
  28303. * as observable with brushed metals.
  28304. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28305. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28306. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28307. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28308. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28309. * wings of many insects.
  28310. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28311. * transparent materials are less reflective. Physically-based transmission provides a more
  28312. * realistic option for thin, transparent surfaces like glass.
  28313. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28314. * - Sheen: Can be used for representing cloth and fabric materials.
  28315. *
  28316. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28317. * higher performance cost, per pixel, than other three.js materials. Most
  28318. * effects are disabled by default, and add cost as they are enabled. For
  28319. * best results, always specify an environment map when using this material.
  28320. *
  28321. * @augments MeshStandardMaterial
  28322. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28323. */
  28324. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28325. /**
  28326. * Constructs a new mesh physical material.
  28327. *
  28328. * @param {Object} [parameters] - An object with one or more properties
  28329. * defining the material's appearance. Any property of the material
  28330. * (including any property from inherited materials) can be passed
  28331. * in here. Color values can be passed any type of value accepted
  28332. * by {@link Color#set}.
  28333. */
  28334. constructor( parameters ) {
  28335. super();
  28336. /**
  28337. * This flag can be used for type testing.
  28338. *
  28339. * @type {boolean}
  28340. * @readonly
  28341. * @default true
  28342. */
  28343. this.isMeshPhysicalMaterial = true;
  28344. this.defines = {
  28345. 'STANDARD': '',
  28346. 'PHYSICAL': ''
  28347. };
  28348. this.type = 'MeshPhysicalMaterial';
  28349. /**
  28350. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28351. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28352. * property provides additional rotation to the vectors in the texture.
  28353. *
  28354. * @type {number}
  28355. * @default 1
  28356. */
  28357. this.anisotropyRotation = 0;
  28358. /**
  28359. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28360. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28361. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28362. *
  28363. * @type {?Texture}
  28364. * @default null
  28365. */
  28366. this.anisotropyMap = null;
  28367. /**
  28368. * The red channel of this texture is multiplied against `clearcoat`,
  28369. * for per-pixel control over a coating's intensity.
  28370. *
  28371. * @type {?Texture}
  28372. * @default null
  28373. */
  28374. this.clearcoatMap = null;
  28375. /**
  28376. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28377. *
  28378. * @type {number}
  28379. * @default 0
  28380. */
  28381. this.clearcoatRoughness = 0.0;
  28382. /**
  28383. * The green channel of this texture is multiplied against
  28384. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28385. *
  28386. * @type {?Texture}
  28387. * @default null
  28388. */
  28389. this.clearcoatRoughnessMap = null;
  28390. /**
  28391. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28392. * `(0,0)` to `(1,1)`.
  28393. *
  28394. * @type {Vector2}
  28395. * @default (1,1)
  28396. */
  28397. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28398. /**
  28399. * Can be used to enable independent normals for the clear coat layer.
  28400. *
  28401. * @type {?Texture}
  28402. * @default null
  28403. */
  28404. this.clearcoatNormalMap = null;
  28405. /**
  28406. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28407. *
  28408. * @type {number}
  28409. * @default 1.5
  28410. */
  28411. this.ior = 1.5;
  28412. /**
  28413. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28414. * corresponds to an index-of-refraction of `1.5`.
  28415. *
  28416. * This models the reflectivity of non-metallic materials. It has no effect
  28417. * when `metalness` is `1.0`
  28418. *
  28419. * @name MeshPhysicalMaterial#reflectivity
  28420. * @type {number}
  28421. * @default 0.5
  28422. */
  28423. Object.defineProperty( this, 'reflectivity', {
  28424. get: function () {
  28425. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28426. },
  28427. set: function ( reflectivity ) {
  28428. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28429. }
  28430. } );
  28431. /**
  28432. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28433. * control over iridescence.
  28434. *
  28435. * @type {?Texture}
  28436. * @default null
  28437. */
  28438. this.iridescenceMap = null;
  28439. /**
  28440. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28441. * Between `1.0` to `2.333`.
  28442. *
  28443. * @type {number}
  28444. * @default 1.3
  28445. */
  28446. this.iridescenceIOR = 1.3;
  28447. /**
  28448. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28449. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28450. *
  28451. * @type {Array<number,number>}
  28452. * @default [100,400]
  28453. */
  28454. this.iridescenceThicknessRange = [ 100, 400 ];
  28455. /**
  28456. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28457. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28458. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28459. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28460. * - Values in-between will linearly interpolate between the elements of the array.
  28461. *
  28462. * @type {?Texture}
  28463. * @default null
  28464. */
  28465. this.iridescenceThicknessMap = null;
  28466. /**
  28467. * The sheen tint.
  28468. *
  28469. * @type {Color}
  28470. * @default (0,0,0)
  28471. */
  28472. this.sheenColor = new Color( 0x000000 );
  28473. /**
  28474. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28475. * over sheen tint.
  28476. *
  28477. * @type {?Texture}
  28478. * @default null
  28479. */
  28480. this.sheenColorMap = null;
  28481. /**
  28482. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28483. *
  28484. * @type {number}
  28485. * @default 1
  28486. */
  28487. this.sheenRoughness = 1.0;
  28488. /**
  28489. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28490. * over sheen roughness.
  28491. *
  28492. * @type {?Texture}
  28493. * @default null
  28494. */
  28495. this.sheenRoughnessMap = null;
  28496. /**
  28497. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28498. * optical transparency.
  28499. *
  28500. * @type {?Texture}
  28501. * @default null
  28502. */
  28503. this.transmissionMap = null;
  28504. /**
  28505. * The thickness of the volume beneath the surface. The value is given in the
  28506. * coordinate space of the mesh. If the value is `0` the material is
  28507. * thin-walled. Otherwise the material is a volume boundary.
  28508. *
  28509. * @type {number}
  28510. * @default 0
  28511. */
  28512. this.thickness = 0;
  28513. /**
  28514. * A texture that defines the thickness, stored in the green channel. This will
  28515. * be multiplied by `thickness`.
  28516. *
  28517. * @type {?Texture}
  28518. * @default null
  28519. */
  28520. this.thicknessMap = null;
  28521. /**
  28522. * Density of the medium given as the average distance that light travels in
  28523. * the medium before interacting with a particle. The value is given in world
  28524. * space units, and must be greater than zero.
  28525. *
  28526. * @type {number}
  28527. * @default Infinity
  28528. */
  28529. this.attenuationDistance = Infinity;
  28530. /**
  28531. * The color that white light turns into due to absorption when reaching the
  28532. * attenuation distance.
  28533. *
  28534. * @type {Color}
  28535. * @default (1,1,1)
  28536. */
  28537. this.attenuationColor = new Color( 1, 1, 1 );
  28538. /**
  28539. * A float that scales the amount of specular reflection for non-metals only.
  28540. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28541. *
  28542. * @type {number}
  28543. * @default 1
  28544. */
  28545. this.specularIntensity = 1.0;
  28546. /**
  28547. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28548. * for per-pixel control over specular intensity.
  28549. *
  28550. * @type {?Texture}
  28551. * @default null
  28552. */
  28553. this.specularIntensityMap = null;
  28554. /**
  28555. * Tints the specular reflection at normal incidence for non-metals only.
  28556. *
  28557. * @type {Color}
  28558. * @default (1,1,1)
  28559. */
  28560. this.specularColor = new Color( 1, 1, 1 );
  28561. /**
  28562. * The RGB channels of this texture are multiplied against `specularColor`,
  28563. * for per-pixel control over specular color.
  28564. *
  28565. * @type {?Texture}
  28566. * @default null
  28567. */
  28568. this.specularColorMap = null;
  28569. this._anisotropy = 0;
  28570. this._clearcoat = 0;
  28571. this._dispersion = 0;
  28572. this._iridescence = 0;
  28573. this._sheen = 0.0;
  28574. this._transmission = 0;
  28575. this.setValues( parameters );
  28576. }
  28577. /**
  28578. * The anisotropy strength, from `0.0` to `1.0`.
  28579. *
  28580. * @type {number}
  28581. * @default 0
  28582. */
  28583. get anisotropy() {
  28584. return this._anisotropy;
  28585. }
  28586. set anisotropy( value ) {
  28587. if ( this._anisotropy > 0 !== value > 0 ) {
  28588. this.version ++;
  28589. }
  28590. this._anisotropy = value;
  28591. }
  28592. /**
  28593. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28594. * clear coat related properties to enable multilayer materials that have a
  28595. * thin translucent layer over the base layer.
  28596. *
  28597. * @type {number}
  28598. * @default 0
  28599. */
  28600. get clearcoat() {
  28601. return this._clearcoat;
  28602. }
  28603. set clearcoat( value ) {
  28604. if ( this._clearcoat > 0 !== value > 0 ) {
  28605. this.version ++;
  28606. }
  28607. this._clearcoat = value;
  28608. }
  28609. /**
  28610. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28611. * the surface and the viewer, from `0.0` to `1.0`.
  28612. *
  28613. * @type {number}
  28614. * @default 0
  28615. */
  28616. get iridescence() {
  28617. return this._iridescence;
  28618. }
  28619. set iridescence( value ) {
  28620. if ( this._iridescence > 0 !== value > 0 ) {
  28621. this.version ++;
  28622. }
  28623. this._iridescence = value;
  28624. }
  28625. /**
  28626. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28627. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28628. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28629. *
  28630. * @type {number}
  28631. * @default 0
  28632. */
  28633. get dispersion() {
  28634. return this._dispersion;
  28635. }
  28636. set dispersion( value ) {
  28637. if ( this._dispersion > 0 !== value > 0 ) {
  28638. this.version ++;
  28639. }
  28640. this._dispersion = value;
  28641. }
  28642. /**
  28643. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28644. *
  28645. * @type {number}
  28646. * @default 0
  28647. */
  28648. get sheen() {
  28649. return this._sheen;
  28650. }
  28651. set sheen( value ) {
  28652. if ( this._sheen > 0 !== value > 0 ) {
  28653. this.version ++;
  28654. }
  28655. this._sheen = value;
  28656. }
  28657. /**
  28658. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28659. *
  28660. * Thin, transparent or semitransparent, plastic or glass materials remain
  28661. * largely reflective even if they are fully transmissive. The transmission
  28662. * property can be used to model these materials.
  28663. *
  28664. * When transmission is non-zero, `opacity` should be set to `1`.
  28665. *
  28666. * @type {number}
  28667. * @default 0
  28668. */
  28669. get transmission() {
  28670. return this._transmission;
  28671. }
  28672. set transmission( value ) {
  28673. if ( this._transmission > 0 !== value > 0 ) {
  28674. this.version ++;
  28675. }
  28676. this._transmission = value;
  28677. }
  28678. copy( source ) {
  28679. super.copy( source );
  28680. this.defines = {
  28681. 'STANDARD': '',
  28682. 'PHYSICAL': ''
  28683. };
  28684. this.anisotropy = source.anisotropy;
  28685. this.anisotropyRotation = source.anisotropyRotation;
  28686. this.anisotropyMap = source.anisotropyMap;
  28687. this.clearcoat = source.clearcoat;
  28688. this.clearcoatMap = source.clearcoatMap;
  28689. this.clearcoatRoughness = source.clearcoatRoughness;
  28690. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28691. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28692. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28693. this.dispersion = source.dispersion;
  28694. this.ior = source.ior;
  28695. this.iridescence = source.iridescence;
  28696. this.iridescenceMap = source.iridescenceMap;
  28697. this.iridescenceIOR = source.iridescenceIOR;
  28698. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28699. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28700. this.sheen = source.sheen;
  28701. this.sheenColor.copy( source.sheenColor );
  28702. this.sheenColorMap = source.sheenColorMap;
  28703. this.sheenRoughness = source.sheenRoughness;
  28704. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28705. this.transmission = source.transmission;
  28706. this.transmissionMap = source.transmissionMap;
  28707. this.thickness = source.thickness;
  28708. this.thicknessMap = source.thicknessMap;
  28709. this.attenuationDistance = source.attenuationDistance;
  28710. this.attenuationColor.copy( source.attenuationColor );
  28711. this.specularIntensity = source.specularIntensity;
  28712. this.specularIntensityMap = source.specularIntensityMap;
  28713. this.specularColor.copy( source.specularColor );
  28714. this.specularColorMap = source.specularColorMap;
  28715. return this;
  28716. }
  28717. }
  28718. /**
  28719. * A material for shiny surfaces with specular highlights.
  28720. *
  28721. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28722. * model for calculating reflectance. Unlike the Lambertian model used in the
  28723. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28724. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28725. *
  28726. * Performance will generally be greater when using this material over the
  28727. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28728. * some graphical accuracy.
  28729. *
  28730. * @augments Material
  28731. * @demo scenes/material-browser.html#MeshPhongMaterial
  28732. */
  28733. class MeshPhongMaterial extends Material {
  28734. /**
  28735. * Constructs a new mesh phong material.
  28736. *
  28737. * @param {Object} [parameters] - An object with one or more properties
  28738. * defining the material's appearance. Any property of the material
  28739. * (including any property from inherited materials) can be passed
  28740. * in here. Color values can be passed any type of value accepted
  28741. * by {@link Color#set}.
  28742. */
  28743. constructor( parameters ) {
  28744. super();
  28745. /**
  28746. * This flag can be used for type testing.
  28747. *
  28748. * @type {boolean}
  28749. * @readonly
  28750. * @default true
  28751. */
  28752. this.isMeshPhongMaterial = true;
  28753. this.type = 'MeshPhongMaterial';
  28754. /**
  28755. * Color of the material.
  28756. *
  28757. * @type {Color}
  28758. * @default (1,1,1)
  28759. */
  28760. this.color = new Color( 0xffffff ); // diffuse
  28761. /**
  28762. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28763. *
  28764. * This defines how shiny the material is and the color of its shine.
  28765. *
  28766. * @type {Color}
  28767. */
  28768. this.specular = new Color( 0x111111 );
  28769. /**
  28770. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28771. *
  28772. * @type {number}
  28773. * @default 30
  28774. */
  28775. this.shininess = 30;
  28776. /**
  28777. * The color map. May optionally include an alpha channel, typically combined
  28778. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28779. * color is modulated by the diffuse `color`.
  28780. *
  28781. * @type {?Texture}
  28782. * @default null
  28783. */
  28784. this.map = null;
  28785. /**
  28786. * The light map. Requires a second set of UVs.
  28787. *
  28788. * @type {?Texture}
  28789. * @default null
  28790. */
  28791. this.lightMap = null;
  28792. /**
  28793. * Intensity of the baked light.
  28794. *
  28795. * @type {number}
  28796. * @default 1
  28797. */
  28798. this.lightMapIntensity = 1.0;
  28799. /**
  28800. * The red channel of this texture is used as the ambient occlusion map.
  28801. * Requires a second set of UVs.
  28802. *
  28803. * @type {?Texture}
  28804. * @default null
  28805. */
  28806. this.aoMap = null;
  28807. /**
  28808. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28809. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28810. * red channel is also `1`, ambient light is fully occluded on a surface.
  28811. *
  28812. * @type {number}
  28813. * @default 1
  28814. */
  28815. this.aoMapIntensity = 1.0;
  28816. /**
  28817. * Emissive (light) color of the material, essentially a solid color
  28818. * unaffected by other lighting.
  28819. *
  28820. * @type {Color}
  28821. * @default (0,0,0)
  28822. */
  28823. this.emissive = new Color( 0x000000 );
  28824. /**
  28825. * Intensity of the emissive light. Modulates the emissive color.
  28826. *
  28827. * @type {number}
  28828. * @default 1
  28829. */
  28830. this.emissiveIntensity = 1.0;
  28831. /**
  28832. * Set emissive (glow) map. The emissive map color is modulated by the
  28833. * emissive color and the emissive intensity. If you have an emissive map,
  28834. * be sure to set the emissive color to something other than black.
  28835. *
  28836. * @type {?Texture}
  28837. * @default null
  28838. */
  28839. this.emissiveMap = null;
  28840. /**
  28841. * The texture to create a bump map. The black and white values map to the
  28842. * perceived depth in relation to the lights. Bump doesn't actually affect
  28843. * the geometry of the object, only the lighting. If a normal map is defined
  28844. * this will be ignored.
  28845. *
  28846. * @type {?Texture}
  28847. * @default null
  28848. */
  28849. this.bumpMap = null;
  28850. /**
  28851. * How much the bump map affects the material. Typical range is `[0,1]`.
  28852. *
  28853. * @type {number}
  28854. * @default 1
  28855. */
  28856. this.bumpScale = 1;
  28857. /**
  28858. * The texture to create a normal map. The RGB values affect the surface
  28859. * normal for each pixel fragment and change the way the color is lit. Normal
  28860. * maps do not change the actual shape of the surface, only the lighting. In
  28861. * case the material has a normal map authored using the left handed
  28862. * convention, the `y` component of `normalScale` should be negated to compensate
  28863. * for the different handedness.
  28864. *
  28865. * @type {?Texture}
  28866. * @default null
  28867. */
  28868. this.normalMap = null;
  28869. /**
  28870. * The type of normal map.
  28871. *
  28872. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28873. * @default TangentSpaceNormalMap
  28874. */
  28875. this.normalMapType = TangentSpaceNormalMap;
  28876. /**
  28877. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28878. *
  28879. * @type {Vector2}
  28880. * @default (1,1)
  28881. */
  28882. this.normalScale = new Vector2( 1, 1 );
  28883. /**
  28884. * The displacement map affects the position of the mesh's vertices. Unlike
  28885. * other maps which only affect the light and shade of the material the
  28886. * displaced vertices can cast shadows, block other objects, and otherwise
  28887. * act as real geometry. The displacement texture is an image where the value
  28888. * of each pixel (white being the highest) is mapped against, and
  28889. * repositions, the vertices of the mesh.
  28890. *
  28891. * @type {?Texture}
  28892. * @default null
  28893. */
  28894. this.displacementMap = null;
  28895. /**
  28896. * How much the displacement map affects the mesh (where black is no
  28897. * displacement, and white is maximum displacement). Without a displacement
  28898. * map set, this value is not applied.
  28899. *
  28900. * @type {number}
  28901. * @default 0
  28902. */
  28903. this.displacementScale = 1;
  28904. /**
  28905. * The offset of the displacement map's values on the mesh's vertices.
  28906. * The bias is added to the scaled sample of the displacement map.
  28907. * Without a displacement map set, this value is not applied.
  28908. *
  28909. * @type {number}
  28910. * @default 0
  28911. */
  28912. this.displacementBias = 0;
  28913. /**
  28914. * The specular map value affects both how much the specular surface
  28915. * highlight contributes and how much of the environment map affects the
  28916. * surface.
  28917. *
  28918. * @type {?Texture}
  28919. * @default null
  28920. */
  28921. this.specularMap = null;
  28922. /**
  28923. * The alpha map is a grayscale texture that controls the opacity across the
  28924. * surface (black: fully transparent; white: fully opaque).
  28925. *
  28926. * Only the color of the texture is used, ignoring the alpha channel if one
  28927. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28928. * when sampling this texture due to the extra bit of precision provided for
  28929. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28930. * luminance/alpha textures will also still work as expected.
  28931. *
  28932. * @type {?Texture}
  28933. * @default null
  28934. */
  28935. this.alphaMap = null;
  28936. /**
  28937. * The environment map.
  28938. *
  28939. * @type {?Texture}
  28940. * @default null
  28941. */
  28942. this.envMap = null;
  28943. /**
  28944. * The rotation of the environment map in radians.
  28945. *
  28946. * @type {Euler}
  28947. * @default (0,0,0)
  28948. */
  28949. this.envMapRotation = new Euler();
  28950. /**
  28951. * How to combine the result of the surface's color with the environment map, if any.
  28952. *
  28953. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28954. * blend between the two colors.
  28955. *
  28956. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28957. * @default MultiplyOperation
  28958. */
  28959. this.combine = MultiplyOperation;
  28960. /**
  28961. * How much the environment map affects the surface.
  28962. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28963. *
  28964. * @type {number}
  28965. * @default 1
  28966. */
  28967. this.reflectivity = 1;
  28968. /**
  28969. * The index of refraction (IOR) of air (approximately 1) divided by the
  28970. * index of refraction of the material. It is used with environment mapping
  28971. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28972. * The refraction ratio should not exceed `1`.
  28973. *
  28974. * @type {number}
  28975. * @default 0.98
  28976. */
  28977. this.refractionRatio = 0.98;
  28978. /**
  28979. * Renders the geometry as a wireframe.
  28980. *
  28981. * @type {boolean}
  28982. * @default false
  28983. */
  28984. this.wireframe = false;
  28985. /**
  28986. * Controls the thickness of the wireframe.
  28987. *
  28988. * Can only be used with {@link SVGRenderer}.
  28989. *
  28990. * @type {number}
  28991. * @default 1
  28992. */
  28993. this.wireframeLinewidth = 1;
  28994. /**
  28995. * Defines appearance of wireframe ends.
  28996. *
  28997. * Can only be used with {@link SVGRenderer}.
  28998. *
  28999. * @type {('round'|'bevel'|'miter')}
  29000. * @default 'round'
  29001. */
  29002. this.wireframeLinecap = 'round';
  29003. /**
  29004. * Defines appearance of wireframe joints.
  29005. *
  29006. * Can only be used with {@link SVGRenderer}.
  29007. *
  29008. * @type {('round'|'bevel'|'miter')}
  29009. * @default 'round'
  29010. */
  29011. this.wireframeLinejoin = 'round';
  29012. /**
  29013. * Whether the material is rendered with flat shading or not.
  29014. *
  29015. * @type {boolean}
  29016. * @default false
  29017. */
  29018. this.flatShading = false;
  29019. /**
  29020. * Whether the material is affected by fog or not.
  29021. *
  29022. * @type {boolean}
  29023. * @default true
  29024. */
  29025. this.fog = true;
  29026. this.setValues( parameters );
  29027. }
  29028. copy( source ) {
  29029. super.copy( source );
  29030. this.color.copy( source.color );
  29031. this.specular.copy( source.specular );
  29032. this.shininess = source.shininess;
  29033. this.map = source.map;
  29034. this.lightMap = source.lightMap;
  29035. this.lightMapIntensity = source.lightMapIntensity;
  29036. this.aoMap = source.aoMap;
  29037. this.aoMapIntensity = source.aoMapIntensity;
  29038. this.emissive.copy( source.emissive );
  29039. this.emissiveMap = source.emissiveMap;
  29040. this.emissiveIntensity = source.emissiveIntensity;
  29041. this.bumpMap = source.bumpMap;
  29042. this.bumpScale = source.bumpScale;
  29043. this.normalMap = source.normalMap;
  29044. this.normalMapType = source.normalMapType;
  29045. this.normalScale.copy( source.normalScale );
  29046. this.displacementMap = source.displacementMap;
  29047. this.displacementScale = source.displacementScale;
  29048. this.displacementBias = source.displacementBias;
  29049. this.specularMap = source.specularMap;
  29050. this.alphaMap = source.alphaMap;
  29051. this.envMap = source.envMap;
  29052. this.envMapRotation.copy( source.envMapRotation );
  29053. this.combine = source.combine;
  29054. this.reflectivity = source.reflectivity;
  29055. this.refractionRatio = source.refractionRatio;
  29056. this.wireframe = source.wireframe;
  29057. this.wireframeLinewidth = source.wireframeLinewidth;
  29058. this.wireframeLinecap = source.wireframeLinecap;
  29059. this.wireframeLinejoin = source.wireframeLinejoin;
  29060. this.flatShading = source.flatShading;
  29061. this.fog = source.fog;
  29062. return this;
  29063. }
  29064. }
  29065. /**
  29066. * A material implementing toon shading.
  29067. *
  29068. * @augments Material
  29069. * @demo scenes/material-browser.html#MeshToonMaterial
  29070. */
  29071. class MeshToonMaterial extends Material {
  29072. /**
  29073. * Constructs a new mesh toon material.
  29074. *
  29075. * @param {Object} [parameters] - An object with one or more properties
  29076. * defining the material's appearance. Any property of the material
  29077. * (including any property from inherited materials) can be passed
  29078. * in here. Color values can be passed any type of value accepted
  29079. * by {@link Color#set}.
  29080. */
  29081. constructor( parameters ) {
  29082. super();
  29083. /**
  29084. * This flag can be used for type testing.
  29085. *
  29086. * @type {boolean}
  29087. * @readonly
  29088. * @default true
  29089. */
  29090. this.isMeshToonMaterial = true;
  29091. this.defines = { 'TOON': '' };
  29092. this.type = 'MeshToonMaterial';
  29093. /**
  29094. * Color of the material.
  29095. *
  29096. * @type {Color}
  29097. * @default (1,1,1)
  29098. */
  29099. this.color = new Color( 0xffffff );
  29100. /**
  29101. * The color map. May optionally include an alpha channel, typically combined
  29102. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29103. * color is modulated by the diffuse `color`.
  29104. *
  29105. * @type {?Texture}
  29106. * @default null
  29107. */
  29108. this.map = null;
  29109. /**
  29110. * Gradient map for toon shading. It's required to set
  29111. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29112. * when using this type of texture.
  29113. *
  29114. * @type {?Texture}
  29115. * @default null
  29116. */
  29117. this.gradientMap = null;
  29118. /**
  29119. * The light map. Requires a second set of UVs.
  29120. *
  29121. * @type {?Texture}
  29122. * @default null
  29123. */
  29124. this.lightMap = null;
  29125. /**
  29126. * Intensity of the baked light.
  29127. *
  29128. * @type {number}
  29129. * @default 1
  29130. */
  29131. this.lightMapIntensity = 1.0;
  29132. /**
  29133. * The red channel of this texture is used as the ambient occlusion map.
  29134. * Requires a second set of UVs.
  29135. *
  29136. * @type {?Texture}
  29137. * @default null
  29138. */
  29139. this.aoMap = null;
  29140. /**
  29141. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29142. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29143. * red channel is also `1`, ambient light is fully occluded on a surface.
  29144. *
  29145. * @type {number}
  29146. * @default 1
  29147. */
  29148. this.aoMapIntensity = 1.0;
  29149. /**
  29150. * Emissive (light) color of the material, essentially a solid color
  29151. * unaffected by other lighting.
  29152. *
  29153. * @type {Color}
  29154. * @default (0,0,0)
  29155. */
  29156. this.emissive = new Color( 0x000000 );
  29157. /**
  29158. * Intensity of the emissive light. Modulates the emissive color.
  29159. *
  29160. * @type {number}
  29161. * @default 1
  29162. */
  29163. this.emissiveIntensity = 1.0;
  29164. /**
  29165. * Set emissive (glow) map. The emissive map color is modulated by the
  29166. * emissive color and the emissive intensity. If you have an emissive map,
  29167. * be sure to set the emissive color to something other than black.
  29168. *
  29169. * @type {?Texture}
  29170. * @default null
  29171. */
  29172. this.emissiveMap = null;
  29173. /**
  29174. * The texture to create a bump map. The black and white values map to the
  29175. * perceived depth in relation to the lights. Bump doesn't actually affect
  29176. * the geometry of the object, only the lighting. If a normal map is defined
  29177. * this will be ignored.
  29178. *
  29179. * @type {?Texture}
  29180. * @default null
  29181. */
  29182. this.bumpMap = null;
  29183. /**
  29184. * How much the bump map affects the material. Typical range is `[0,1]`.
  29185. *
  29186. * @type {number}
  29187. * @default 1
  29188. */
  29189. this.bumpScale = 1;
  29190. /**
  29191. * The texture to create a normal map. The RGB values affect the surface
  29192. * normal for each pixel fragment and change the way the color is lit. Normal
  29193. * maps do not change the actual shape of the surface, only the lighting. In
  29194. * case the material has a normal map authored using the left handed
  29195. * convention, the `y` component of `normalScale` should be negated to compensate
  29196. * for the different handedness.
  29197. *
  29198. * @type {?Texture}
  29199. * @default null
  29200. */
  29201. this.normalMap = null;
  29202. /**
  29203. * The type of normal map.
  29204. *
  29205. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29206. * @default TangentSpaceNormalMap
  29207. */
  29208. this.normalMapType = TangentSpaceNormalMap;
  29209. /**
  29210. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29211. *
  29212. * @type {Vector2}
  29213. * @default (1,1)
  29214. */
  29215. this.normalScale = new Vector2( 1, 1 );
  29216. /**
  29217. * The displacement map affects the position of the mesh's vertices. Unlike
  29218. * other maps which only affect the light and shade of the material the
  29219. * displaced vertices can cast shadows, block other objects, and otherwise
  29220. * act as real geometry. The displacement texture is an image where the value
  29221. * of each pixel (white being the highest) is mapped against, and
  29222. * repositions, the vertices of the mesh.
  29223. *
  29224. * @type {?Texture}
  29225. * @default null
  29226. */
  29227. this.displacementMap = null;
  29228. /**
  29229. * How much the displacement map affects the mesh (where black is no
  29230. * displacement, and white is maximum displacement). Without a displacement
  29231. * map set, this value is not applied.
  29232. *
  29233. * @type {number}
  29234. * @default 0
  29235. */
  29236. this.displacementScale = 1;
  29237. /**
  29238. * The offset of the displacement map's values on the mesh's vertices.
  29239. * The bias is added to the scaled sample of the displacement map.
  29240. * Without a displacement map set, this value is not applied.
  29241. *
  29242. * @type {number}
  29243. * @default 0
  29244. */
  29245. this.displacementBias = 0;
  29246. /**
  29247. * The alpha map is a grayscale texture that controls the opacity across the
  29248. * surface (black: fully transparent; white: fully opaque).
  29249. *
  29250. * Only the color of the texture is used, ignoring the alpha channel if one
  29251. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29252. * when sampling this texture due to the extra bit of precision provided for
  29253. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29254. * luminance/alpha textures will also still work as expected.
  29255. *
  29256. * @type {?Texture}
  29257. * @default null
  29258. */
  29259. this.alphaMap = null;
  29260. /**
  29261. * Renders the geometry as a wireframe.
  29262. *
  29263. * @type {boolean}
  29264. * @default false
  29265. */
  29266. this.wireframe = false;
  29267. /**
  29268. * Controls the thickness of the wireframe.
  29269. *
  29270. * Can only be used with {@link SVGRenderer}.
  29271. *
  29272. * @type {number}
  29273. * @default 1
  29274. */
  29275. this.wireframeLinewidth = 1;
  29276. /**
  29277. * Defines appearance of wireframe ends.
  29278. *
  29279. * Can only be used with {@link SVGRenderer}.
  29280. *
  29281. * @type {('round'|'bevel'|'miter')}
  29282. * @default 'round'
  29283. */
  29284. this.wireframeLinecap = 'round';
  29285. /**
  29286. * Defines appearance of wireframe joints.
  29287. *
  29288. * Can only be used with {@link SVGRenderer}.
  29289. *
  29290. * @type {('round'|'bevel'|'miter')}
  29291. * @default 'round'
  29292. */
  29293. this.wireframeLinejoin = 'round';
  29294. /**
  29295. * Whether the material is affected by fog or not.
  29296. *
  29297. * @type {boolean}
  29298. * @default true
  29299. */
  29300. this.fog = true;
  29301. this.setValues( parameters );
  29302. }
  29303. copy( source ) {
  29304. super.copy( source );
  29305. this.color.copy( source.color );
  29306. this.map = source.map;
  29307. this.gradientMap = source.gradientMap;
  29308. this.lightMap = source.lightMap;
  29309. this.lightMapIntensity = source.lightMapIntensity;
  29310. this.aoMap = source.aoMap;
  29311. this.aoMapIntensity = source.aoMapIntensity;
  29312. this.emissive.copy( source.emissive );
  29313. this.emissiveMap = source.emissiveMap;
  29314. this.emissiveIntensity = source.emissiveIntensity;
  29315. this.bumpMap = source.bumpMap;
  29316. this.bumpScale = source.bumpScale;
  29317. this.normalMap = source.normalMap;
  29318. this.normalMapType = source.normalMapType;
  29319. this.normalScale.copy( source.normalScale );
  29320. this.displacementMap = source.displacementMap;
  29321. this.displacementScale = source.displacementScale;
  29322. this.displacementBias = source.displacementBias;
  29323. this.alphaMap = source.alphaMap;
  29324. this.wireframe = source.wireframe;
  29325. this.wireframeLinewidth = source.wireframeLinewidth;
  29326. this.wireframeLinecap = source.wireframeLinecap;
  29327. this.wireframeLinejoin = source.wireframeLinejoin;
  29328. this.fog = source.fog;
  29329. return this;
  29330. }
  29331. }
  29332. /**
  29333. * A material that maps the normal vectors to RGB colors.
  29334. *
  29335. * @augments Material
  29336. * @demo scenes/material-browser.html#MeshNormalMaterial
  29337. */
  29338. class MeshNormalMaterial extends Material {
  29339. /**
  29340. * Constructs a new mesh normal material.
  29341. *
  29342. * @param {Object} [parameters] - An object with one or more properties
  29343. * defining the material's appearance. Any property of the material
  29344. * (including any property from inherited materials) can be passed
  29345. * in here. Color values can be passed any type of value accepted
  29346. * by {@link Color#set}.
  29347. */
  29348. constructor( parameters ) {
  29349. super();
  29350. /**
  29351. * This flag can be used for type testing.
  29352. *
  29353. * @type {boolean}
  29354. * @readonly
  29355. * @default true
  29356. */
  29357. this.isMeshNormalMaterial = true;
  29358. this.type = 'MeshNormalMaterial';
  29359. /**
  29360. * The texture to create a bump map. The black and white values map to the
  29361. * perceived depth in relation to the lights. Bump doesn't actually affect
  29362. * the geometry of the object, only the lighting. If a normal map is defined
  29363. * this will be ignored.
  29364. *
  29365. * @type {?Texture}
  29366. * @default null
  29367. */
  29368. this.bumpMap = null;
  29369. /**
  29370. * How much the bump map affects the material. Typical range is `[0,1]`.
  29371. *
  29372. * @type {number}
  29373. * @default 1
  29374. */
  29375. this.bumpScale = 1;
  29376. /**
  29377. * The texture to create a normal map. The RGB values affect the surface
  29378. * normal for each pixel fragment and change the way the color is lit. Normal
  29379. * maps do not change the actual shape of the surface, only the lighting. In
  29380. * case the material has a normal map authored using the left handed
  29381. * convention, the `y` component of `normalScale` should be negated to compensate
  29382. * for the different handedness.
  29383. *
  29384. * @type {?Texture}
  29385. * @default null
  29386. */
  29387. this.normalMap = null;
  29388. /**
  29389. * The type of normal map.
  29390. *
  29391. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29392. * @default TangentSpaceNormalMap
  29393. */
  29394. this.normalMapType = TangentSpaceNormalMap;
  29395. /**
  29396. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29397. *
  29398. * @type {Vector2}
  29399. * @default (1,1)
  29400. */
  29401. this.normalScale = new Vector2( 1, 1 );
  29402. /**
  29403. * The displacement map affects the position of the mesh's vertices. Unlike
  29404. * other maps which only affect the light and shade of the material the
  29405. * displaced vertices can cast shadows, block other objects, and otherwise
  29406. * act as real geometry. The displacement texture is an image where the value
  29407. * of each pixel (white being the highest) is mapped against, and
  29408. * repositions, the vertices of the mesh.
  29409. *
  29410. * @type {?Texture}
  29411. * @default null
  29412. */
  29413. this.displacementMap = null;
  29414. /**
  29415. * How much the displacement map affects the mesh (where black is no
  29416. * displacement, and white is maximum displacement). Without a displacement
  29417. * map set, this value is not applied.
  29418. *
  29419. * @type {number}
  29420. * @default 0
  29421. */
  29422. this.displacementScale = 1;
  29423. /**
  29424. * The offset of the displacement map's values on the mesh's vertices.
  29425. * The bias is added to the scaled sample of the displacement map.
  29426. * Without a displacement map set, this value is not applied.
  29427. *
  29428. * @type {number}
  29429. * @default 0
  29430. */
  29431. this.displacementBias = 0;
  29432. /**
  29433. * Renders the geometry as a wireframe.
  29434. *
  29435. * @type {boolean}
  29436. * @default false
  29437. */
  29438. this.wireframe = false;
  29439. /**
  29440. * Controls the thickness of the wireframe.
  29441. *
  29442. * WebGL and WebGPU ignore this property and always render
  29443. * 1 pixel wide lines.
  29444. *
  29445. * @type {number}
  29446. * @default 1
  29447. */
  29448. this.wireframeLinewidth = 1;
  29449. /**
  29450. * Whether the material is rendered with flat shading or not.
  29451. *
  29452. * @type {boolean}
  29453. * @default false
  29454. */
  29455. this.flatShading = false;
  29456. this.setValues( parameters );
  29457. }
  29458. copy( source ) {
  29459. super.copy( source );
  29460. this.bumpMap = source.bumpMap;
  29461. this.bumpScale = source.bumpScale;
  29462. this.normalMap = source.normalMap;
  29463. this.normalMapType = source.normalMapType;
  29464. this.normalScale.copy( source.normalScale );
  29465. this.displacementMap = source.displacementMap;
  29466. this.displacementScale = source.displacementScale;
  29467. this.displacementBias = source.displacementBias;
  29468. this.wireframe = source.wireframe;
  29469. this.wireframeLinewidth = source.wireframeLinewidth;
  29470. this.flatShading = source.flatShading;
  29471. return this;
  29472. }
  29473. }
  29474. /**
  29475. * A material for non-shiny surfaces, without specular highlights.
  29476. *
  29477. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29478. * model for calculating reflectance. This can simulate some surfaces (such
  29479. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29480. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29481. * shading.
  29482. *
  29483. * Due to the simplicity of the reflectance and illumination models,
  29484. * performance will be greater when using this material over the
  29485. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29486. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29487. *
  29488. * @augments Material
  29489. * @demo scenes/material-browser.html#MeshLambertMaterial
  29490. */
  29491. class MeshLambertMaterial extends Material {
  29492. /**
  29493. * Constructs a new mesh lambert material.
  29494. *
  29495. * @param {Object} [parameters] - An object with one or more properties
  29496. * defining the material's appearance. Any property of the material
  29497. * (including any property from inherited materials) can be passed
  29498. * in here. Color values can be passed any type of value accepted
  29499. * by {@link Color#set}.
  29500. */
  29501. constructor( parameters ) {
  29502. super();
  29503. /**
  29504. * This flag can be used for type testing.
  29505. *
  29506. * @type {boolean}
  29507. * @readonly
  29508. * @default true
  29509. */
  29510. this.isMeshLambertMaterial = true;
  29511. this.type = 'MeshLambertMaterial';
  29512. /**
  29513. * Color of the material.
  29514. *
  29515. * @type {Color}
  29516. * @default (1,1,1)
  29517. */
  29518. this.color = new Color( 0xffffff ); // diffuse
  29519. /**
  29520. * The color map. May optionally include an alpha channel, typically combined
  29521. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29522. * color is modulated by the diffuse `color`.
  29523. *
  29524. * @type {?Texture}
  29525. * @default null
  29526. */
  29527. this.map = null;
  29528. /**
  29529. * The light map. Requires a second set of UVs.
  29530. *
  29531. * @type {?Texture}
  29532. * @default null
  29533. */
  29534. this.lightMap = null;
  29535. /**
  29536. * Intensity of the baked light.
  29537. *
  29538. * @type {number}
  29539. * @default 1
  29540. */
  29541. this.lightMapIntensity = 1.0;
  29542. /**
  29543. * The red channel of this texture is used as the ambient occlusion map.
  29544. * Requires a second set of UVs.
  29545. *
  29546. * @type {?Texture}
  29547. * @default null
  29548. */
  29549. this.aoMap = null;
  29550. /**
  29551. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29552. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29553. * red channel is also `1`, ambient light is fully occluded on a surface.
  29554. *
  29555. * @type {number}
  29556. * @default 1
  29557. */
  29558. this.aoMapIntensity = 1.0;
  29559. /**
  29560. * Emissive (light) color of the material, essentially a solid color
  29561. * unaffected by other lighting.
  29562. *
  29563. * @type {Color}
  29564. * @default (0,0,0)
  29565. */
  29566. this.emissive = new Color( 0x000000 );
  29567. /**
  29568. * Intensity of the emissive light. Modulates the emissive color.
  29569. *
  29570. * @type {number}
  29571. * @default 1
  29572. */
  29573. this.emissiveIntensity = 1.0;
  29574. /**
  29575. * Set emissive (glow) map. The emissive map color is modulated by the
  29576. * emissive color and the emissive intensity. If you have an emissive map,
  29577. * be sure to set the emissive color to something other than black.
  29578. *
  29579. * @type {?Texture}
  29580. * @default null
  29581. */
  29582. this.emissiveMap = null;
  29583. /**
  29584. * The texture to create a bump map. The black and white values map to the
  29585. * perceived depth in relation to the lights. Bump doesn't actually affect
  29586. * the geometry of the object, only the lighting. If a normal map is defined
  29587. * this will be ignored.
  29588. *
  29589. * @type {?Texture}
  29590. * @default null
  29591. */
  29592. this.bumpMap = null;
  29593. /**
  29594. * How much the bump map affects the material. Typical range is `[0,1]`.
  29595. *
  29596. * @type {number}
  29597. * @default 1
  29598. */
  29599. this.bumpScale = 1;
  29600. /**
  29601. * The texture to create a normal map. The RGB values affect the surface
  29602. * normal for each pixel fragment and change the way the color is lit. Normal
  29603. * maps do not change the actual shape of the surface, only the lighting. In
  29604. * case the material has a normal map authored using the left handed
  29605. * convention, the `y` component of `normalScale` should be negated to compensate
  29606. * for the different handedness.
  29607. *
  29608. * @type {?Texture}
  29609. * @default null
  29610. */
  29611. this.normalMap = null;
  29612. /**
  29613. * The type of normal map.
  29614. *
  29615. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29616. * @default TangentSpaceNormalMap
  29617. */
  29618. this.normalMapType = TangentSpaceNormalMap;
  29619. /**
  29620. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29621. *
  29622. * @type {Vector2}
  29623. * @default (1,1)
  29624. */
  29625. this.normalScale = new Vector2( 1, 1 );
  29626. /**
  29627. * The displacement map affects the position of the mesh's vertices. Unlike
  29628. * other maps which only affect the light and shade of the material the
  29629. * displaced vertices can cast shadows, block other objects, and otherwise
  29630. * act as real geometry. The displacement texture is an image where the value
  29631. * of each pixel (white being the highest) is mapped against, and
  29632. * repositions, the vertices of the mesh.
  29633. *
  29634. * @type {?Texture}
  29635. * @default null
  29636. */
  29637. this.displacementMap = null;
  29638. /**
  29639. * How much the displacement map affects the mesh (where black is no
  29640. * displacement, and white is maximum displacement). Without a displacement
  29641. * map set, this value is not applied.
  29642. *
  29643. * @type {number}
  29644. * @default 0
  29645. */
  29646. this.displacementScale = 1;
  29647. /**
  29648. * The offset of the displacement map's values on the mesh's vertices.
  29649. * The bias is added to the scaled sample of the displacement map.
  29650. * Without a displacement map set, this value is not applied.
  29651. *
  29652. * @type {number}
  29653. * @default 0
  29654. */
  29655. this.displacementBias = 0;
  29656. /**
  29657. * Specular map used by the material.
  29658. *
  29659. * @type {?Texture}
  29660. * @default null
  29661. */
  29662. this.specularMap = null;
  29663. /**
  29664. * The alpha map is a grayscale texture that controls the opacity across the
  29665. * surface (black: fully transparent; white: fully opaque).
  29666. *
  29667. * Only the color of the texture is used, ignoring the alpha channel if one
  29668. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29669. * when sampling this texture due to the extra bit of precision provided for
  29670. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29671. * luminance/alpha textures will also still work as expected.
  29672. *
  29673. * @type {?Texture}
  29674. * @default null
  29675. */
  29676. this.alphaMap = null;
  29677. /**
  29678. * The environment map.
  29679. *
  29680. * @type {?Texture}
  29681. * @default null
  29682. */
  29683. this.envMap = null;
  29684. /**
  29685. * The rotation of the environment map in radians.
  29686. *
  29687. * @type {Euler}
  29688. * @default (0,0,0)
  29689. */
  29690. this.envMapRotation = new Euler();
  29691. /**
  29692. * How to combine the result of the surface's color with the environment map, if any.
  29693. *
  29694. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29695. * blend between the two colors.
  29696. *
  29697. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29698. * @default MultiplyOperation
  29699. */
  29700. this.combine = MultiplyOperation;
  29701. /**
  29702. * How much the environment map affects the surface.
  29703. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29704. *
  29705. * @type {number}
  29706. * @default 1
  29707. */
  29708. this.reflectivity = 1;
  29709. /**
  29710. * The index of refraction (IOR) of air (approximately 1) divided by the
  29711. * index of refraction of the material. It is used with environment mapping
  29712. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29713. * The refraction ratio should not exceed `1`.
  29714. *
  29715. * @type {number}
  29716. * @default 0.98
  29717. */
  29718. this.refractionRatio = 0.98;
  29719. /**
  29720. * Renders the geometry as a wireframe.
  29721. *
  29722. * @type {boolean}
  29723. * @default false
  29724. */
  29725. this.wireframe = false;
  29726. /**
  29727. * Controls the thickness of the wireframe.
  29728. *
  29729. * Can only be used with {@link SVGRenderer}.
  29730. *
  29731. * @type {number}
  29732. * @default 1
  29733. */
  29734. this.wireframeLinewidth = 1;
  29735. /**
  29736. * Defines appearance of wireframe ends.
  29737. *
  29738. * Can only be used with {@link SVGRenderer}.
  29739. *
  29740. * @type {('round'|'bevel'|'miter')}
  29741. * @default 'round'
  29742. */
  29743. this.wireframeLinecap = 'round';
  29744. /**
  29745. * Defines appearance of wireframe joints.
  29746. *
  29747. * Can only be used with {@link SVGRenderer}.
  29748. *
  29749. * @type {('round'|'bevel'|'miter')}
  29750. * @default 'round'
  29751. */
  29752. this.wireframeLinejoin = 'round';
  29753. /**
  29754. * Whether the material is rendered with flat shading or not.
  29755. *
  29756. * @type {boolean}
  29757. * @default false
  29758. */
  29759. this.flatShading = false;
  29760. /**
  29761. * Whether the material is affected by fog or not.
  29762. *
  29763. * @type {boolean}
  29764. * @default true
  29765. */
  29766. this.fog = true;
  29767. this.setValues( parameters );
  29768. }
  29769. copy( source ) {
  29770. super.copy( source );
  29771. this.color.copy( source.color );
  29772. this.map = source.map;
  29773. this.lightMap = source.lightMap;
  29774. this.lightMapIntensity = source.lightMapIntensity;
  29775. this.aoMap = source.aoMap;
  29776. this.aoMapIntensity = source.aoMapIntensity;
  29777. this.emissive.copy( source.emissive );
  29778. this.emissiveMap = source.emissiveMap;
  29779. this.emissiveIntensity = source.emissiveIntensity;
  29780. this.bumpMap = source.bumpMap;
  29781. this.bumpScale = source.bumpScale;
  29782. this.normalMap = source.normalMap;
  29783. this.normalMapType = source.normalMapType;
  29784. this.normalScale.copy( source.normalScale );
  29785. this.displacementMap = source.displacementMap;
  29786. this.displacementScale = source.displacementScale;
  29787. this.displacementBias = source.displacementBias;
  29788. this.specularMap = source.specularMap;
  29789. this.alphaMap = source.alphaMap;
  29790. this.envMap = source.envMap;
  29791. this.envMapRotation.copy( source.envMapRotation );
  29792. this.combine = source.combine;
  29793. this.reflectivity = source.reflectivity;
  29794. this.refractionRatio = source.refractionRatio;
  29795. this.wireframe = source.wireframe;
  29796. this.wireframeLinewidth = source.wireframeLinewidth;
  29797. this.wireframeLinecap = source.wireframeLinecap;
  29798. this.wireframeLinejoin = source.wireframeLinejoin;
  29799. this.flatShading = source.flatShading;
  29800. this.fog = source.fog;
  29801. return this;
  29802. }
  29803. }
  29804. /**
  29805. * A material for drawing geometry by depth. Depth is based off of the camera
  29806. * near and far plane. White is nearest, black is farthest.
  29807. *
  29808. * @augments Material
  29809. * @demo scenes/material-browser.html#MeshDepthMaterial
  29810. */
  29811. class MeshDepthMaterial extends Material {
  29812. /**
  29813. * Constructs a new mesh depth material.
  29814. *
  29815. * @param {Object} [parameters] - An object with one or more properties
  29816. * defining the material's appearance. Any property of the material
  29817. * (including any property from inherited materials) can be passed
  29818. * in here. Color values can be passed any type of value accepted
  29819. * by {@link Color#set}.
  29820. */
  29821. constructor( parameters ) {
  29822. super();
  29823. /**
  29824. * This flag can be used for type testing.
  29825. *
  29826. * @type {boolean}
  29827. * @readonly
  29828. * @default true
  29829. */
  29830. this.isMeshDepthMaterial = true;
  29831. this.type = 'MeshDepthMaterial';
  29832. /**
  29833. * Type for depth packing.
  29834. *
  29835. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29836. * @default BasicDepthPacking
  29837. */
  29838. this.depthPacking = BasicDepthPacking;
  29839. /**
  29840. * The color map. May optionally include an alpha channel, typically combined
  29841. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29842. *
  29843. * @type {?Texture}
  29844. * @default null
  29845. */
  29846. this.map = null;
  29847. /**
  29848. * The alpha map is a grayscale texture that controls the opacity across the
  29849. * surface (black: fully transparent; white: fully opaque).
  29850. *
  29851. * Only the color of the texture is used, ignoring the alpha channel if one
  29852. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29853. * when sampling this texture due to the extra bit of precision provided for
  29854. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29855. * luminance/alpha textures will also still work as expected.
  29856. *
  29857. * @type {?Texture}
  29858. * @default null
  29859. */
  29860. this.alphaMap = null;
  29861. /**
  29862. * The displacement map affects the position of the mesh's vertices. Unlike
  29863. * other maps which only affect the light and shade of the material the
  29864. * displaced vertices can cast shadows, block other objects, and otherwise
  29865. * act as real geometry. The displacement texture is an image where the value
  29866. * of each pixel (white being the highest) is mapped against, and
  29867. * repositions, the vertices of the mesh.
  29868. *
  29869. * @type {?Texture}
  29870. * @default null
  29871. */
  29872. this.displacementMap = null;
  29873. /**
  29874. * How much the displacement map affects the mesh (where black is no
  29875. * displacement, and white is maximum displacement). Without a displacement
  29876. * map set, this value is not applied.
  29877. *
  29878. * @type {number}
  29879. * @default 0
  29880. */
  29881. this.displacementScale = 1;
  29882. /**
  29883. * The offset of the displacement map's values on the mesh's vertices.
  29884. * The bias is added to the scaled sample of the displacement map.
  29885. * Without a displacement map set, this value is not applied.
  29886. *
  29887. * @type {number}
  29888. * @default 0
  29889. */
  29890. this.displacementBias = 0;
  29891. /**
  29892. * Renders the geometry as a wireframe.
  29893. *
  29894. * @type {boolean}
  29895. * @default false
  29896. */
  29897. this.wireframe = false;
  29898. /**
  29899. * Controls the thickness of the wireframe.
  29900. *
  29901. * WebGL and WebGPU ignore this property and always render
  29902. * 1 pixel wide lines.
  29903. *
  29904. * @type {number}
  29905. * @default 1
  29906. */
  29907. this.wireframeLinewidth = 1;
  29908. this.setValues( parameters );
  29909. }
  29910. copy( source ) {
  29911. super.copy( source );
  29912. this.depthPacking = source.depthPacking;
  29913. this.map = source.map;
  29914. this.alphaMap = source.alphaMap;
  29915. this.displacementMap = source.displacementMap;
  29916. this.displacementScale = source.displacementScale;
  29917. this.displacementBias = source.displacementBias;
  29918. this.wireframe = source.wireframe;
  29919. this.wireframeLinewidth = source.wireframeLinewidth;
  29920. return this;
  29921. }
  29922. }
  29923. /**
  29924. * A material used internally for implementing shadow mapping with
  29925. * point lights.
  29926. *
  29927. * Can also be used to customize the shadow casting of an object by assigning
  29928. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29929. * The following examples demonstrates this approach in order to ensure
  29930. * transparent parts of objects do not cast shadows.
  29931. *
  29932. * @augments Material
  29933. */
  29934. class MeshDistanceMaterial extends Material {
  29935. /**
  29936. * Constructs a new mesh distance material.
  29937. *
  29938. * @param {Object} [parameters] - An object with one or more properties
  29939. * defining the material's appearance. Any property of the material
  29940. * (including any property from inherited materials) can be passed
  29941. * in here. Color values can be passed any type of value accepted
  29942. * by {@link Color#set}.
  29943. */
  29944. constructor( parameters ) {
  29945. super();
  29946. /**
  29947. * This flag can be used for type testing.
  29948. *
  29949. * @type {boolean}
  29950. * @readonly
  29951. * @default true
  29952. */
  29953. this.isMeshDistanceMaterial = true;
  29954. this.type = 'MeshDistanceMaterial';
  29955. /**
  29956. * The color map. May optionally include an alpha channel, typically combined
  29957. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29958. *
  29959. * @type {?Texture}
  29960. * @default null
  29961. */
  29962. this.map = null;
  29963. /**
  29964. * The alpha map is a grayscale texture that controls the opacity across the
  29965. * surface (black: fully transparent; white: fully opaque).
  29966. *
  29967. * Only the color of the texture is used, ignoring the alpha channel if one
  29968. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29969. * when sampling this texture due to the extra bit of precision provided for
  29970. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29971. * luminance/alpha textures will also still work as expected.
  29972. *
  29973. * @type {?Texture}
  29974. * @default null
  29975. */
  29976. this.alphaMap = null;
  29977. /**
  29978. * The displacement map affects the position of the mesh's vertices. Unlike
  29979. * other maps which only affect the light and shade of the material the
  29980. * displaced vertices can cast shadows, block other objects, and otherwise
  29981. * act as real geometry. The displacement texture is an image where the value
  29982. * of each pixel (white being the highest) is mapped against, and
  29983. * repositions, the vertices of the mesh.
  29984. *
  29985. * @type {?Texture}
  29986. * @default null
  29987. */
  29988. this.displacementMap = null;
  29989. /**
  29990. * How much the displacement map affects the mesh (where black is no
  29991. * displacement, and white is maximum displacement). Without a displacement
  29992. * map set, this value is not applied.
  29993. *
  29994. * @type {number}
  29995. * @default 0
  29996. */
  29997. this.displacementScale = 1;
  29998. /**
  29999. * The offset of the displacement map's values on the mesh's vertices.
  30000. * The bias is added to the scaled sample of the displacement map.
  30001. * Without a displacement map set, this value is not applied.
  30002. *
  30003. * @type {number}
  30004. * @default 0
  30005. */
  30006. this.displacementBias = 0;
  30007. this.setValues( parameters );
  30008. }
  30009. copy( source ) {
  30010. super.copy( source );
  30011. this.map = source.map;
  30012. this.alphaMap = source.alphaMap;
  30013. this.displacementMap = source.displacementMap;
  30014. this.displacementScale = source.displacementScale;
  30015. this.displacementBias = source.displacementBias;
  30016. return this;
  30017. }
  30018. }
  30019. /**
  30020. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30021. * material color and shading.
  30022. *
  30023. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30024. * baked lighting. It will cast a shadow onto an object that receives shadows
  30025. * (and shadow clipping works), but it will not self-shadow or receive
  30026. * shadows.
  30027. *
  30028. * @augments Material
  30029. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30030. */
  30031. class MeshMatcapMaterial extends Material {
  30032. /**
  30033. * Constructs a new mesh matcap material.
  30034. *
  30035. * @param {Object} [parameters] - An object with one or more properties
  30036. * defining the material's appearance. Any property of the material
  30037. * (including any property from inherited materials) can be passed
  30038. * in here. Color values can be passed any type of value accepted
  30039. * by {@link Color#set}.
  30040. */
  30041. constructor( parameters ) {
  30042. super();
  30043. /**
  30044. * This flag can be used for type testing.
  30045. *
  30046. * @type {boolean}
  30047. * @readonly
  30048. * @default true
  30049. */
  30050. this.isMeshMatcapMaterial = true;
  30051. this.defines = { 'MATCAP': '' };
  30052. this.type = 'MeshMatcapMaterial';
  30053. /**
  30054. * Color of the material.
  30055. *
  30056. * @type {Color}
  30057. * @default (1,1,1)
  30058. */
  30059. this.color = new Color( 0xffffff ); // diffuse
  30060. /**
  30061. * The matcap map.
  30062. *
  30063. * @type {?Texture}
  30064. * @default null
  30065. */
  30066. this.matcap = null;
  30067. /**
  30068. * The color map. May optionally include an alpha channel, typically combined
  30069. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30070. * color is modulated by the diffuse `color`.
  30071. *
  30072. * @type {?Texture}
  30073. * @default null
  30074. */
  30075. this.map = null;
  30076. /**
  30077. * The texture to create a bump map. The black and white values map to the
  30078. * perceived depth in relation to the lights. Bump doesn't actually affect
  30079. * the geometry of the object, only the lighting. If a normal map is defined
  30080. * this will be ignored.
  30081. *
  30082. * @type {?Texture}
  30083. * @default null
  30084. */
  30085. this.bumpMap = null;
  30086. /**
  30087. * How much the bump map affects the material. Typical range is `[0,1]`.
  30088. *
  30089. * @type {number}
  30090. * @default 1
  30091. */
  30092. this.bumpScale = 1;
  30093. /**
  30094. * The texture to create a normal map. The RGB values affect the surface
  30095. * normal for each pixel fragment and change the way the color is lit. Normal
  30096. * maps do not change the actual shape of the surface, only the lighting. In
  30097. * case the material has a normal map authored using the left handed
  30098. * convention, the `y` component of `normalScale` should be negated to compensate
  30099. * for the different handedness.
  30100. *
  30101. * @type {?Texture}
  30102. * @default null
  30103. */
  30104. this.normalMap = null;
  30105. /**
  30106. * The type of normal map.
  30107. *
  30108. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30109. * @default TangentSpaceNormalMap
  30110. */
  30111. this.normalMapType = TangentSpaceNormalMap;
  30112. /**
  30113. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30114. *
  30115. * @type {Vector2}
  30116. * @default (1,1)
  30117. */
  30118. this.normalScale = new Vector2( 1, 1 );
  30119. /**
  30120. * The displacement map affects the position of the mesh's vertices. Unlike
  30121. * other maps which only affect the light and shade of the material the
  30122. * displaced vertices can cast shadows, block other objects, and otherwise
  30123. * act as real geometry. The displacement texture is an image where the value
  30124. * of each pixel (white being the highest) is mapped against, and
  30125. * repositions, the vertices of the mesh.
  30126. *
  30127. * @type {?Texture}
  30128. * @default null
  30129. */
  30130. this.displacementMap = null;
  30131. /**
  30132. * How much the displacement map affects the mesh (where black is no
  30133. * displacement, and white is maximum displacement). Without a displacement
  30134. * map set, this value is not applied.
  30135. *
  30136. * @type {number}
  30137. * @default 0
  30138. */
  30139. this.displacementScale = 1;
  30140. /**
  30141. * The offset of the displacement map's values on the mesh's vertices.
  30142. * The bias is added to the scaled sample of the displacement map.
  30143. * Without a displacement map set, this value is not applied.
  30144. *
  30145. * @type {number}
  30146. * @default 0
  30147. */
  30148. this.displacementBias = 0;
  30149. /**
  30150. * The alpha map is a grayscale texture that controls the opacity across the
  30151. * surface (black: fully transparent; white: fully opaque).
  30152. *
  30153. * Only the color of the texture is used, ignoring the alpha channel if one
  30154. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30155. * when sampling this texture due to the extra bit of precision provided for
  30156. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30157. * luminance/alpha textures will also still work as expected.
  30158. *
  30159. * @type {?Texture}
  30160. * @default null
  30161. */
  30162. this.alphaMap = null;
  30163. /**
  30164. * Renders the geometry as a wireframe.
  30165. *
  30166. * @type {boolean}
  30167. * @default false
  30168. */
  30169. this.wireframe = false;
  30170. /**
  30171. * Controls the thickness of the wireframe.
  30172. *
  30173. * Can only be used with {@link SVGRenderer}.
  30174. *
  30175. * @type {number}
  30176. * @default 1
  30177. */
  30178. this.wireframeLinewidth = 1;
  30179. /**
  30180. * Whether the material is rendered with flat shading or not.
  30181. *
  30182. * @type {boolean}
  30183. * @default false
  30184. */
  30185. this.flatShading = false;
  30186. /**
  30187. * Whether the material is affected by fog or not.
  30188. *
  30189. * @type {boolean}
  30190. * @default true
  30191. */
  30192. this.fog = true;
  30193. this.setValues( parameters );
  30194. }
  30195. copy( source ) {
  30196. super.copy( source );
  30197. this.defines = { 'MATCAP': '' };
  30198. this.color.copy( source.color );
  30199. this.matcap = source.matcap;
  30200. this.map = source.map;
  30201. this.bumpMap = source.bumpMap;
  30202. this.bumpScale = source.bumpScale;
  30203. this.normalMap = source.normalMap;
  30204. this.normalMapType = source.normalMapType;
  30205. this.normalScale.copy( source.normalScale );
  30206. this.displacementMap = source.displacementMap;
  30207. this.displacementScale = source.displacementScale;
  30208. this.displacementBias = source.displacementBias;
  30209. this.alphaMap = source.alphaMap;
  30210. this.wireframe = source.wireframe;
  30211. this.wireframeLinewidth = source.wireframeLinewidth;
  30212. this.flatShading = source.flatShading;
  30213. this.fog = source.fog;
  30214. return this;
  30215. }
  30216. }
  30217. /**
  30218. * A material for rendering line primitives.
  30219. *
  30220. * Materials define the appearance of renderable 3D objects.
  30221. *
  30222. * ```js
  30223. * const material = new THREE.LineDashedMaterial( {
  30224. * color: 0xffffff,
  30225. * scale: 1,
  30226. * dashSize: 3,
  30227. * gapSize: 1,
  30228. * } );
  30229. * ```
  30230. *
  30231. * @augments LineBasicMaterial
  30232. */
  30233. class LineDashedMaterial extends LineBasicMaterial {
  30234. /**
  30235. * Constructs a new line dashed material.
  30236. *
  30237. * @param {Object} [parameters] - An object with one or more properties
  30238. * defining the material's appearance. Any property of the material
  30239. * (including any property from inherited materials) can be passed
  30240. * in here. Color values can be passed any type of value accepted
  30241. * by {@link Color#set}.
  30242. */
  30243. constructor( parameters ) {
  30244. super();
  30245. /**
  30246. * This flag can be used for type testing.
  30247. *
  30248. * @type {boolean}
  30249. * @readonly
  30250. * @default true
  30251. */
  30252. this.isLineDashedMaterial = true;
  30253. this.type = 'LineDashedMaterial';
  30254. /**
  30255. * The scale of the dashed part of a line.
  30256. *
  30257. * @type {number}
  30258. * @default 1
  30259. */
  30260. this.scale = 1;
  30261. /**
  30262. * The size of the dash. This is both the gap with the stroke.
  30263. *
  30264. * @type {number}
  30265. * @default 3
  30266. */
  30267. this.dashSize = 3;
  30268. /**
  30269. * The size of the gap.
  30270. *
  30271. * @type {number}
  30272. * @default 1
  30273. */
  30274. this.gapSize = 1;
  30275. this.setValues( parameters );
  30276. }
  30277. copy( source ) {
  30278. super.copy( source );
  30279. this.scale = source.scale;
  30280. this.dashSize = source.dashSize;
  30281. this.gapSize = source.gapSize;
  30282. return this;
  30283. }
  30284. }
  30285. /**
  30286. * Converts an array to a specific type.
  30287. *
  30288. * @param {TypedArray|Array} array - The array to convert.
  30289. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30290. * @return {TypedArray} The converted array.
  30291. */
  30292. function convertArray( array, type ) {
  30293. if ( ! array || array.constructor === type ) return array;
  30294. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30295. return new type( array ); // create typed array
  30296. }
  30297. return Array.prototype.slice.call( array ); // create Array
  30298. }
  30299. /**
  30300. * Returns an array by which times and values can be sorted.
  30301. *
  30302. * @param {Array<number>} times - The keyframe time values.
  30303. * @return {Array<number>} The array.
  30304. */
  30305. function getKeyframeOrder( times ) {
  30306. function compareTime( i, j ) {
  30307. return times[ i ] - times[ j ];
  30308. }
  30309. const n = times.length;
  30310. const result = new Array( n );
  30311. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30312. result.sort( compareTime );
  30313. return result;
  30314. }
  30315. /**
  30316. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30317. *
  30318. * @param {Array<number>} values - The values to sort.
  30319. * @param {number} stride - The stride.
  30320. * @param {Array<number>} order - The sort order.
  30321. * @return {Array<number>} The sorted values.
  30322. */
  30323. function sortedArray( values, stride, order ) {
  30324. const nValues = values.length;
  30325. const result = new values.constructor( nValues );
  30326. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30327. const srcOffset = order[ i ] * stride;
  30328. for ( let j = 0; j !== stride; ++ j ) {
  30329. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30330. }
  30331. }
  30332. return result;
  30333. }
  30334. /**
  30335. * Used for parsing AOS keyframe formats.
  30336. *
  30337. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30338. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30339. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30340. * @param {string} valuePropertyName - The name of the property to use.
  30341. */
  30342. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30343. let i = 1, key = jsonKeys[ 0 ];
  30344. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30345. key = jsonKeys[ i ++ ];
  30346. }
  30347. if ( key === undefined ) return; // no data
  30348. let value = key[ valuePropertyName ];
  30349. if ( value === undefined ) return; // no data
  30350. if ( Array.isArray( value ) ) {
  30351. do {
  30352. value = key[ valuePropertyName ];
  30353. if ( value !== undefined ) {
  30354. times.push( key.time );
  30355. values.push( ...value ); // push all elements
  30356. }
  30357. key = jsonKeys[ i ++ ];
  30358. } while ( key !== undefined );
  30359. } else if ( value.toArray !== undefined ) {
  30360. // ...assume THREE.Math-ish
  30361. do {
  30362. value = key[ valuePropertyName ];
  30363. if ( value !== undefined ) {
  30364. times.push( key.time );
  30365. value.toArray( values, values.length );
  30366. }
  30367. key = jsonKeys[ i ++ ];
  30368. } while ( key !== undefined );
  30369. } else {
  30370. // otherwise push as-is
  30371. do {
  30372. value = key[ valuePropertyName ];
  30373. if ( value !== undefined ) {
  30374. times.push( key.time );
  30375. values.push( value );
  30376. }
  30377. key = jsonKeys[ i ++ ];
  30378. } while ( key !== undefined );
  30379. }
  30380. }
  30381. /**
  30382. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30383. *
  30384. * @param {AnimationClip} sourceClip - The values to sort.
  30385. * @param {string} name - The name of the clip.
  30386. * @param {number} startFrame - The start frame.
  30387. * @param {number} endFrame - The end frame.
  30388. * @param {number} [fps=30] - The FPS.
  30389. * @return {AnimationClip} The new sub clip.
  30390. */
  30391. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30392. const clip = sourceClip.clone();
  30393. clip.name = name;
  30394. const tracks = [];
  30395. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30396. const track = clip.tracks[ i ];
  30397. const valueSize = track.getValueSize();
  30398. const times = [];
  30399. const values = [];
  30400. for ( let j = 0; j < track.times.length; ++ j ) {
  30401. const frame = track.times[ j ] * fps;
  30402. if ( frame < startFrame || frame >= endFrame ) continue;
  30403. times.push( track.times[ j ] );
  30404. for ( let k = 0; k < valueSize; ++ k ) {
  30405. values.push( track.values[ j * valueSize + k ] );
  30406. }
  30407. }
  30408. if ( times.length === 0 ) continue;
  30409. track.times = convertArray( times, track.times.constructor );
  30410. track.values = convertArray( values, track.values.constructor );
  30411. tracks.push( track );
  30412. }
  30413. clip.tracks = tracks;
  30414. // find minimum .times value across all tracks in the trimmed clip
  30415. let minStartTime = Infinity;
  30416. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30417. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30418. minStartTime = clip.tracks[ i ].times[ 0 ];
  30419. }
  30420. }
  30421. // shift all tracks such that clip begins at t=0
  30422. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30423. clip.tracks[ i ].shift( -1 * minStartTime );
  30424. }
  30425. clip.resetDuration();
  30426. return clip;
  30427. }
  30428. /**
  30429. * Converts the keyframes of the given animation clip to an additive format.
  30430. *
  30431. * @param {AnimationClip} targetClip - The clip to make additive.
  30432. * @param {number} [referenceFrame=0] - The reference frame.
  30433. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30434. * @param {number} [fps=30] - The FPS.
  30435. * @return {AnimationClip} The updated clip which is now additive.
  30436. */
  30437. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30438. if ( fps <= 0 ) fps = 30;
  30439. const numTracks = referenceClip.tracks.length;
  30440. const referenceTime = referenceFrame / fps;
  30441. // Make each track's values relative to the values at the reference frame
  30442. for ( let i = 0; i < numTracks; ++ i ) {
  30443. const referenceTrack = referenceClip.tracks[ i ];
  30444. const referenceTrackType = referenceTrack.ValueTypeName;
  30445. // Skip this track if it's non-numeric
  30446. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30447. // Find the track in the target clip whose name and type matches the reference track
  30448. const targetTrack = targetClip.tracks.find( function ( track ) {
  30449. return track.name === referenceTrack.name
  30450. && track.ValueTypeName === referenceTrackType;
  30451. } );
  30452. if ( targetTrack === undefined ) continue;
  30453. let referenceOffset = 0;
  30454. const referenceValueSize = referenceTrack.getValueSize();
  30455. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30456. referenceOffset = referenceValueSize / 3;
  30457. }
  30458. let targetOffset = 0;
  30459. const targetValueSize = targetTrack.getValueSize();
  30460. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30461. targetOffset = targetValueSize / 3;
  30462. }
  30463. const lastIndex = referenceTrack.times.length - 1;
  30464. let referenceValue;
  30465. // Find the value to subtract out of the track
  30466. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30467. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30468. const startIndex = referenceOffset;
  30469. const endIndex = referenceValueSize - referenceOffset;
  30470. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30471. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30472. // Reference frame is after the last keyframe, so just use the last keyframe
  30473. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30474. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30475. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30476. } else {
  30477. // Interpolate to the reference value
  30478. const interpolant = referenceTrack.createInterpolant();
  30479. const startIndex = referenceOffset;
  30480. const endIndex = referenceValueSize - referenceOffset;
  30481. interpolant.evaluate( referenceTime );
  30482. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30483. }
  30484. // Conjugate the quaternion
  30485. if ( referenceTrackType === 'quaternion' ) {
  30486. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30487. referenceQuat.toArray( referenceValue );
  30488. }
  30489. // Subtract the reference value from all of the track values
  30490. const numTimes = targetTrack.times.length;
  30491. for ( let j = 0; j < numTimes; ++ j ) {
  30492. const valueStart = j * targetValueSize + targetOffset;
  30493. if ( referenceTrackType === 'quaternion' ) {
  30494. // Multiply the conjugate for quaternion track types
  30495. Quaternion.multiplyQuaternionsFlat(
  30496. targetTrack.values,
  30497. valueStart,
  30498. referenceValue,
  30499. 0,
  30500. targetTrack.values,
  30501. valueStart
  30502. );
  30503. } else {
  30504. const valueEnd = targetValueSize - targetOffset * 2;
  30505. // Subtract each value for all other numeric track types
  30506. for ( let k = 0; k < valueEnd; ++ k ) {
  30507. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30508. }
  30509. }
  30510. }
  30511. }
  30512. targetClip.blendMode = AdditiveAnimationBlendMode;
  30513. return targetClip;
  30514. }
  30515. /**
  30516. * A class with various methods to assist with animations.
  30517. *
  30518. * @hideconstructor
  30519. */
  30520. class AnimationUtils {
  30521. /**
  30522. * Converts an array to a specific type
  30523. *
  30524. * @static
  30525. * @param {TypedArray|Array} array - The array to convert.
  30526. * @param {TypedArray.constructor} type - The constructor of a type array.
  30527. * @return {TypedArray} The converted array
  30528. */
  30529. static convertArray( array, type ) {
  30530. return convertArray( array, type );
  30531. }
  30532. /**
  30533. * Returns `true` if the given object is a typed array.
  30534. *
  30535. * @static
  30536. * @param {any} object - The object to check.
  30537. * @return {boolean} Whether the given object is a typed array.
  30538. */
  30539. static isTypedArray( object ) {
  30540. return isTypedArray( object );
  30541. }
  30542. /**
  30543. * Returns an array by which times and values can be sorted.
  30544. *
  30545. * @static
  30546. * @param {Array<number>} times - The keyframe time values.
  30547. * @return {Array<number>} The array.
  30548. */
  30549. static getKeyframeOrder( times ) {
  30550. return getKeyframeOrder( times );
  30551. }
  30552. /**
  30553. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30554. *
  30555. * @static
  30556. * @param {Array<number>} values - The values to sort.
  30557. * @param {number} stride - The stride.
  30558. * @param {Array<number>} order - The sort order.
  30559. * @return {Array<number>} The sorted values.
  30560. */
  30561. static sortedArray( values, stride, order ) {
  30562. return sortedArray( values, stride, order );
  30563. }
  30564. /**
  30565. * Used for parsing AOS keyframe formats.
  30566. *
  30567. * @static
  30568. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30569. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30570. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30571. * @param {string} valuePropertyName - The name of the property to use.
  30572. */
  30573. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30574. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30575. }
  30576. /**
  30577. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30578. *
  30579. * @static
  30580. * @param {AnimationClip} sourceClip - The values to sort.
  30581. * @param {string} name - The name of the clip.
  30582. * @param {number} startFrame - The start frame.
  30583. * @param {number} endFrame - The end frame.
  30584. * @param {number} [fps=30] - The FPS.
  30585. * @return {AnimationClip} The new sub clip.
  30586. */
  30587. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30588. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30589. }
  30590. /**
  30591. * Converts the keyframes of the given animation clip to an additive format.
  30592. *
  30593. * @static
  30594. * @param {AnimationClip} targetClip - The clip to make additive.
  30595. * @param {number} [referenceFrame=0] - The reference frame.
  30596. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30597. * @param {number} [fps=30] - The FPS.
  30598. * @return {AnimationClip} The updated clip which is now additive.
  30599. */
  30600. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30601. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30602. }
  30603. }
  30604. /**
  30605. * Abstract base class of interpolants over parametric samples.
  30606. *
  30607. * The parameter domain is one dimensional, typically the time or a path
  30608. * along a curve defined by the data.
  30609. *
  30610. * The sample values can have any dimensionality and derived classes may
  30611. * apply special interpretations to the data.
  30612. *
  30613. * This class provides the interval seek in a Template Method, deferring
  30614. * the actual interpolation to derived classes.
  30615. *
  30616. * Time complexity is O(1) for linear access crossing at most two points
  30617. * and O(log N) for random access, where N is the number of positions.
  30618. *
  30619. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30620. *
  30621. * @abstract
  30622. */
  30623. class Interpolant {
  30624. /**
  30625. * Constructs a new interpolant.
  30626. *
  30627. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30628. * @param {TypedArray} sampleValues - The sample values.
  30629. * @param {number} sampleSize - The sample size
  30630. * @param {TypedArray} [resultBuffer] - The result buffer.
  30631. */
  30632. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30633. /**
  30634. * The parameter positions.
  30635. *
  30636. * @type {TypedArray}
  30637. */
  30638. this.parameterPositions = parameterPositions;
  30639. /**
  30640. * A cache index.
  30641. *
  30642. * @private
  30643. * @type {number}
  30644. * @default 0
  30645. */
  30646. this._cachedIndex = 0;
  30647. /**
  30648. * The result buffer.
  30649. *
  30650. * @type {TypedArray}
  30651. */
  30652. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30653. /**
  30654. * The sample values.
  30655. *
  30656. * @type {TypedArray}
  30657. */
  30658. this.sampleValues = sampleValues;
  30659. /**
  30660. * The value size.
  30661. *
  30662. * @type {TypedArray}
  30663. */
  30664. this.valueSize = sampleSize;
  30665. /**
  30666. * The interpolation settings.
  30667. *
  30668. * @type {?Object}
  30669. * @default null
  30670. */
  30671. this.settings = null;
  30672. /**
  30673. * The default settings object.
  30674. *
  30675. * @type {Object}
  30676. */
  30677. this.DefaultSettings_ = {};
  30678. }
  30679. /**
  30680. * Evaluate the interpolant at position `t`.
  30681. *
  30682. * @param {number} t - The interpolation factor.
  30683. * @return {TypedArray} The result buffer.
  30684. */
  30685. evaluate( t ) {
  30686. const pp = this.parameterPositions;
  30687. let i1 = this._cachedIndex,
  30688. t1 = pp[ i1 ],
  30689. t0 = pp[ i1 - 1 ];
  30690. validate_interval: {
  30691. seek: {
  30692. let right;
  30693. linear_scan: {
  30694. //- See http://jsperf.com/comparison-to-undefined/3
  30695. //- slower code:
  30696. //-
  30697. //- if ( t >= t1 || t1 === undefined ) {
  30698. forward_scan: if ( ! ( t < t1 ) ) {
  30699. for ( let giveUpAt = i1 + 2; ; ) {
  30700. if ( t1 === undefined ) {
  30701. if ( t < t0 ) break forward_scan;
  30702. // after end
  30703. i1 = pp.length;
  30704. this._cachedIndex = i1;
  30705. return this.copySampleValue_( i1 - 1 );
  30706. }
  30707. if ( i1 === giveUpAt ) break; // this loop
  30708. t0 = t1;
  30709. t1 = pp[ ++ i1 ];
  30710. if ( t < t1 ) {
  30711. // we have arrived at the sought interval
  30712. break seek;
  30713. }
  30714. }
  30715. // prepare binary search on the right side of the index
  30716. right = pp.length;
  30717. break linear_scan;
  30718. }
  30719. //- slower code:
  30720. //- if ( t < t0 || t0 === undefined ) {
  30721. if ( ! ( t >= t0 ) ) {
  30722. // looping?
  30723. const t1global = pp[ 1 ];
  30724. if ( t < t1global ) {
  30725. i1 = 2; // + 1, using the scan for the details
  30726. t0 = t1global;
  30727. }
  30728. // linear reverse scan
  30729. for ( let giveUpAt = i1 - 2; ; ) {
  30730. if ( t0 === undefined ) {
  30731. // before start
  30732. this._cachedIndex = 0;
  30733. return this.copySampleValue_( 0 );
  30734. }
  30735. if ( i1 === giveUpAt ) break; // this loop
  30736. t1 = t0;
  30737. t0 = pp[ -- i1 - 1 ];
  30738. if ( t >= t0 ) {
  30739. // we have arrived at the sought interval
  30740. break seek;
  30741. }
  30742. }
  30743. // prepare binary search on the left side of the index
  30744. right = i1;
  30745. i1 = 0;
  30746. break linear_scan;
  30747. }
  30748. // the interval is valid
  30749. break validate_interval;
  30750. } // linear scan
  30751. // binary search
  30752. while ( i1 < right ) {
  30753. const mid = ( i1 + right ) >>> 1;
  30754. if ( t < pp[ mid ] ) {
  30755. right = mid;
  30756. } else {
  30757. i1 = mid + 1;
  30758. }
  30759. }
  30760. t1 = pp[ i1 ];
  30761. t0 = pp[ i1 - 1 ];
  30762. // check boundary cases, again
  30763. if ( t0 === undefined ) {
  30764. this._cachedIndex = 0;
  30765. return this.copySampleValue_( 0 );
  30766. }
  30767. if ( t1 === undefined ) {
  30768. i1 = pp.length;
  30769. this._cachedIndex = i1;
  30770. return this.copySampleValue_( i1 - 1 );
  30771. }
  30772. } // seek
  30773. this._cachedIndex = i1;
  30774. this.intervalChanged_( i1, t0, t1 );
  30775. } // validate_interval
  30776. return this.interpolate_( i1, t0, t, t1 );
  30777. }
  30778. /**
  30779. * Returns the interpolation settings.
  30780. *
  30781. * @return {Object} The interpolation settings.
  30782. */
  30783. getSettings_() {
  30784. return this.settings || this.DefaultSettings_;
  30785. }
  30786. /**
  30787. * Copies a sample value to the result buffer.
  30788. *
  30789. * @param {number} index - An index into the sample value buffer.
  30790. * @return {TypedArray} The result buffer.
  30791. */
  30792. copySampleValue_( index ) {
  30793. // copies a sample value to the result buffer
  30794. const result = this.resultBuffer,
  30795. values = this.sampleValues,
  30796. stride = this.valueSize,
  30797. offset = index * stride;
  30798. for ( let i = 0; i !== stride; ++ i ) {
  30799. result[ i ] = values[ offset + i ];
  30800. }
  30801. return result;
  30802. }
  30803. /**
  30804. * Copies a sample value to the result buffer.
  30805. *
  30806. * @abstract
  30807. * @param {number} i1 - An index into the sample value buffer.
  30808. * @param {number} t0 - The previous interpolation factor.
  30809. * @param {number} t - The current interpolation factor.
  30810. * @param {number} t1 - The next interpolation factor.
  30811. * @return {TypedArray} The result buffer.
  30812. */
  30813. interpolate_( /* i1, t0, t, t1 */ ) {
  30814. throw new Error( 'call to abstract method' );
  30815. // implementations shall return this.resultBuffer
  30816. }
  30817. /**
  30818. * Optional method that is executed when the interval has changed.
  30819. *
  30820. * @param {number} i1 - An index into the sample value buffer.
  30821. * @param {number} t0 - The previous interpolation factor.
  30822. * @param {number} t - The current interpolation factor.
  30823. */
  30824. intervalChanged_( /* i1, t0, t1 */ ) {
  30825. // empty
  30826. }
  30827. }
  30828. /**
  30829. * Fast and simple cubic spline interpolant.
  30830. *
  30831. * It was derived from a Hermitian construction setting the first derivative
  30832. * at each sample position to the linear slope between neighboring positions
  30833. * over their parameter interval.
  30834. *
  30835. * @augments Interpolant
  30836. */
  30837. class CubicInterpolant extends Interpolant {
  30838. /**
  30839. * Constructs a new cubic interpolant.
  30840. *
  30841. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30842. * @param {TypedArray} sampleValues - The sample values.
  30843. * @param {number} sampleSize - The sample size
  30844. * @param {TypedArray} [resultBuffer] - The result buffer.
  30845. */
  30846. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30847. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30848. this._weightPrev = -0;
  30849. this._offsetPrev = -0;
  30850. this._weightNext = -0;
  30851. this._offsetNext = -0;
  30852. this.DefaultSettings_ = {
  30853. endingStart: ZeroCurvatureEnding,
  30854. endingEnd: ZeroCurvatureEnding
  30855. };
  30856. }
  30857. intervalChanged_( i1, t0, t1 ) {
  30858. const pp = this.parameterPositions;
  30859. let iPrev = i1 - 2,
  30860. iNext = i1 + 1,
  30861. tPrev = pp[ iPrev ],
  30862. tNext = pp[ iNext ];
  30863. if ( tPrev === undefined ) {
  30864. switch ( this.getSettings_().endingStart ) {
  30865. case ZeroSlopeEnding:
  30866. // f'(t0) = 0
  30867. iPrev = i1;
  30868. tPrev = 2 * t0 - t1;
  30869. break;
  30870. case WrapAroundEnding:
  30871. // use the other end of the curve
  30872. iPrev = pp.length - 2;
  30873. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30874. break;
  30875. default: // ZeroCurvatureEnding
  30876. // f''(t0) = 0 a.k.a. Natural Spline
  30877. iPrev = i1;
  30878. tPrev = t1;
  30879. }
  30880. }
  30881. if ( tNext === undefined ) {
  30882. switch ( this.getSettings_().endingEnd ) {
  30883. case ZeroSlopeEnding:
  30884. // f'(tN) = 0
  30885. iNext = i1;
  30886. tNext = 2 * t1 - t0;
  30887. break;
  30888. case WrapAroundEnding:
  30889. // use the other end of the curve
  30890. iNext = 1;
  30891. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30892. break;
  30893. default: // ZeroCurvatureEnding
  30894. // f''(tN) = 0, a.k.a. Natural Spline
  30895. iNext = i1 - 1;
  30896. tNext = t0;
  30897. }
  30898. }
  30899. const halfDt = ( t1 - t0 ) * 0.5,
  30900. stride = this.valueSize;
  30901. this._weightPrev = halfDt / ( t0 - tPrev );
  30902. this._weightNext = halfDt / ( tNext - t1 );
  30903. this._offsetPrev = iPrev * stride;
  30904. this._offsetNext = iNext * stride;
  30905. }
  30906. interpolate_( i1, t0, t, t1 ) {
  30907. const result = this.resultBuffer,
  30908. values = this.sampleValues,
  30909. stride = this.valueSize,
  30910. o1 = i1 * stride, o0 = o1 - stride,
  30911. oP = this._offsetPrev, oN = this._offsetNext,
  30912. wP = this._weightPrev, wN = this._weightNext,
  30913. p = ( t - t0 ) / ( t1 - t0 ),
  30914. pp = p * p,
  30915. ppp = pp * p;
  30916. // evaluate polynomials
  30917. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30918. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30919. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30920. const sN = wN * ppp - wN * pp;
  30921. // combine data linearly
  30922. for ( let i = 0; i !== stride; ++ i ) {
  30923. result[ i ] =
  30924. sP * values[ oP + i ] +
  30925. s0 * values[ o0 + i ] +
  30926. s1 * values[ o1 + i ] +
  30927. sN * values[ oN + i ];
  30928. }
  30929. return result;
  30930. }
  30931. }
  30932. /**
  30933. * A basic linear interpolant.
  30934. *
  30935. * @augments Interpolant
  30936. */
  30937. class LinearInterpolant extends Interpolant {
  30938. /**
  30939. * Constructs a new linear interpolant.
  30940. *
  30941. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30942. * @param {TypedArray} sampleValues - The sample values.
  30943. * @param {number} sampleSize - The sample size
  30944. * @param {TypedArray} [resultBuffer] - The result buffer.
  30945. */
  30946. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30947. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30948. }
  30949. interpolate_( i1, t0, t, t1 ) {
  30950. const result = this.resultBuffer,
  30951. values = this.sampleValues,
  30952. stride = this.valueSize,
  30953. offset1 = i1 * stride,
  30954. offset0 = offset1 - stride,
  30955. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30956. weight0 = 1 - weight1;
  30957. for ( let i = 0; i !== stride; ++ i ) {
  30958. result[ i ] =
  30959. values[ offset0 + i ] * weight0 +
  30960. values[ offset1 + i ] * weight1;
  30961. }
  30962. return result;
  30963. }
  30964. }
  30965. /**
  30966. * Interpolant that evaluates to the sample value at the position preceding
  30967. * the parameter.
  30968. *
  30969. * @augments Interpolant
  30970. */
  30971. class DiscreteInterpolant extends Interpolant {
  30972. /**
  30973. * Constructs a new discrete interpolant.
  30974. *
  30975. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30976. * @param {TypedArray} sampleValues - The sample values.
  30977. * @param {number} sampleSize - The sample size
  30978. * @param {TypedArray} [resultBuffer] - The result buffer.
  30979. */
  30980. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30981. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30982. }
  30983. interpolate_( i1 /*, t0, t, t1 */ ) {
  30984. return this.copySampleValue_( i1 - 1 );
  30985. }
  30986. }
  30987. /**
  30988. * Represents a timed sequence of keyframes, which are composed of lists of
  30989. * times and related values, and which are used to animate a specific property
  30990. * of an object.
  30991. */
  30992. class KeyframeTrack {
  30993. /**
  30994. * Constructs a new keyframe track.
  30995. *
  30996. * @param {string} name - The keyframe track's name.
  30997. * @param {Array<number>} times - A list of keyframe times.
  30998. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30999. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31000. */
  31001. constructor( name, times, values, interpolation ) {
  31002. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31003. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31004. /**
  31005. * The track's name can refer to morph targets or bones or
  31006. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31007. * for the forms of strings that can be parsed for property binding.
  31008. *
  31009. * @type {string}
  31010. */
  31011. this.name = name;
  31012. /**
  31013. * The keyframe times.
  31014. *
  31015. * @type {Float32Array}
  31016. */
  31017. this.times = convertArray( times, this.TimeBufferType );
  31018. /**
  31019. * The keyframe values.
  31020. *
  31021. * @type {Float32Array}
  31022. */
  31023. this.values = convertArray( values, this.ValueBufferType );
  31024. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31025. }
  31026. /**
  31027. * Converts the keyframe track to JSON.
  31028. *
  31029. * @static
  31030. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31031. * @return {Object} The serialized keyframe track as JSON.
  31032. */
  31033. static toJSON( track ) {
  31034. const trackType = track.constructor;
  31035. let json;
  31036. // derived classes can define a static toJSON method
  31037. if ( trackType.toJSON !== this.toJSON ) {
  31038. json = trackType.toJSON( track );
  31039. } else {
  31040. // by default, we assume the data can be serialized as-is
  31041. json = {
  31042. 'name': track.name,
  31043. 'times': convertArray( track.times, Array ),
  31044. 'values': convertArray( track.values, Array )
  31045. };
  31046. const interpolation = track.getInterpolation();
  31047. if ( interpolation !== track.DefaultInterpolation ) {
  31048. json.interpolation = interpolation;
  31049. }
  31050. }
  31051. json.type = track.ValueTypeName; // mandatory
  31052. return json;
  31053. }
  31054. /**
  31055. * Factory method for creating a new discrete interpolant.
  31056. *
  31057. * @static
  31058. * @param {TypedArray} [result] - The result buffer.
  31059. * @return {DiscreteInterpolant} The new interpolant.
  31060. */
  31061. InterpolantFactoryMethodDiscrete( result ) {
  31062. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31063. }
  31064. /**
  31065. * Factory method for creating a new linear interpolant.
  31066. *
  31067. * @static
  31068. * @param {TypedArray} [result] - The result buffer.
  31069. * @return {LinearInterpolant} The new interpolant.
  31070. */
  31071. InterpolantFactoryMethodLinear( result ) {
  31072. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31073. }
  31074. /**
  31075. * Factory method for creating a new smooth interpolant.
  31076. *
  31077. * @static
  31078. * @param {TypedArray} [result] - The result buffer.
  31079. * @return {CubicInterpolant} The new interpolant.
  31080. */
  31081. InterpolantFactoryMethodSmooth( result ) {
  31082. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31083. }
  31084. /**
  31085. * Defines the interpolation factor method for this keyframe track.
  31086. *
  31087. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31088. * @return {KeyframeTrack} A reference to this keyframe track.
  31089. */
  31090. setInterpolation( interpolation ) {
  31091. let factoryMethod;
  31092. switch ( interpolation ) {
  31093. case InterpolateDiscrete:
  31094. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31095. break;
  31096. case InterpolateLinear:
  31097. factoryMethod = this.InterpolantFactoryMethodLinear;
  31098. break;
  31099. case InterpolateSmooth:
  31100. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31101. break;
  31102. }
  31103. if ( factoryMethod === undefined ) {
  31104. const message = 'unsupported interpolation for ' +
  31105. this.ValueTypeName + ' keyframe track named ' + this.name;
  31106. if ( this.createInterpolant === undefined ) {
  31107. // fall back to default, unless the default itself is messed up
  31108. if ( interpolation !== this.DefaultInterpolation ) {
  31109. this.setInterpolation( this.DefaultInterpolation );
  31110. } else {
  31111. throw new Error( message ); // fatal, in this case
  31112. }
  31113. }
  31114. warn( 'KeyframeTrack:', message );
  31115. return this;
  31116. }
  31117. this.createInterpolant = factoryMethod;
  31118. return this;
  31119. }
  31120. /**
  31121. * Returns the current interpolation type.
  31122. *
  31123. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31124. */
  31125. getInterpolation() {
  31126. switch ( this.createInterpolant ) {
  31127. case this.InterpolantFactoryMethodDiscrete:
  31128. return InterpolateDiscrete;
  31129. case this.InterpolantFactoryMethodLinear:
  31130. return InterpolateLinear;
  31131. case this.InterpolantFactoryMethodSmooth:
  31132. return InterpolateSmooth;
  31133. }
  31134. }
  31135. /**
  31136. * Returns the value size.
  31137. *
  31138. * @return {number} The value size.
  31139. */
  31140. getValueSize() {
  31141. return this.values.length / this.times.length;
  31142. }
  31143. /**
  31144. * Moves all keyframes either forward or backward in time.
  31145. *
  31146. * @param {number} timeOffset - The offset to move the time values.
  31147. * @return {KeyframeTrack} A reference to this keyframe track.
  31148. */
  31149. shift( timeOffset ) {
  31150. if ( timeOffset !== 0.0 ) {
  31151. const times = this.times;
  31152. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31153. times[ i ] += timeOffset;
  31154. }
  31155. }
  31156. return this;
  31157. }
  31158. /**
  31159. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31160. *
  31161. * @param {number} timeScale - The time scale.
  31162. * @return {KeyframeTrack} A reference to this keyframe track.
  31163. */
  31164. scale( timeScale ) {
  31165. if ( timeScale !== 1.0 ) {
  31166. const times = this.times;
  31167. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31168. times[ i ] *= timeScale;
  31169. }
  31170. }
  31171. return this;
  31172. }
  31173. /**
  31174. * Removes keyframes before and after animation without changing any values within the defined time range.
  31175. *
  31176. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31177. * keys this will change their values
  31178. *
  31179. * @param {number} startTime - The start time.
  31180. * @param {number} endTime - The end time.
  31181. * @return {KeyframeTrack} A reference to this keyframe track.
  31182. */
  31183. trim( startTime, endTime ) {
  31184. const times = this.times,
  31185. nKeys = times.length;
  31186. let from = 0,
  31187. to = nKeys - 1;
  31188. while ( from !== nKeys && times[ from ] < startTime ) {
  31189. ++ from;
  31190. }
  31191. while ( to !== -1 && times[ to ] > endTime ) {
  31192. -- to;
  31193. }
  31194. ++ to; // inclusive -> exclusive bound
  31195. if ( from !== 0 || to !== nKeys ) {
  31196. // empty tracks are forbidden, so keep at least one keyframe
  31197. if ( from >= to ) {
  31198. to = Math.max( to, 1 );
  31199. from = to - 1;
  31200. }
  31201. const stride = this.getValueSize();
  31202. this.times = times.slice( from, to );
  31203. this.values = this.values.slice( from * stride, to * stride );
  31204. }
  31205. return this;
  31206. }
  31207. /**
  31208. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31209. * are valid.
  31210. *
  31211. * @return {boolean} Whether the keyframes are valid or not.
  31212. */
  31213. validate() {
  31214. let valid = true;
  31215. const valueSize = this.getValueSize();
  31216. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31217. error( 'KeyframeTrack: Invalid value size in track.', this );
  31218. valid = false;
  31219. }
  31220. const times = this.times,
  31221. values = this.values,
  31222. nKeys = times.length;
  31223. if ( nKeys === 0 ) {
  31224. error( 'KeyframeTrack: Track is empty.', this );
  31225. valid = false;
  31226. }
  31227. let prevTime = null;
  31228. for ( let i = 0; i !== nKeys; i ++ ) {
  31229. const currTime = times[ i ];
  31230. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31231. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31232. valid = false;
  31233. break;
  31234. }
  31235. if ( prevTime !== null && prevTime > currTime ) {
  31236. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31237. valid = false;
  31238. break;
  31239. }
  31240. prevTime = currTime;
  31241. }
  31242. if ( values !== undefined ) {
  31243. if ( isTypedArray( values ) ) {
  31244. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31245. const value = values[ i ];
  31246. if ( isNaN( value ) ) {
  31247. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31248. valid = false;
  31249. break;
  31250. }
  31251. }
  31252. }
  31253. }
  31254. return valid;
  31255. }
  31256. /**
  31257. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31258. * common in morph target sequences).
  31259. *
  31260. * @return {KeyframeTrack} A reference to this keyframe track.
  31261. */
  31262. optimize() {
  31263. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31264. // times or values may be shared with other tracks, so overwriting is unsafe
  31265. const times = this.times.slice(),
  31266. values = this.values.slice(),
  31267. stride = this.getValueSize(),
  31268. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31269. lastIndex = times.length - 1;
  31270. let writeIndex = 1;
  31271. for ( let i = 1; i < lastIndex; ++ i ) {
  31272. let keep = false;
  31273. const time = times[ i ];
  31274. const timeNext = times[ i + 1 ];
  31275. // remove adjacent keyframes scheduled at the same time
  31276. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31277. if ( ! smoothInterpolation ) {
  31278. // remove unnecessary keyframes same as their neighbors
  31279. const offset = i * stride,
  31280. offsetP = offset - stride,
  31281. offsetN = offset + stride;
  31282. for ( let j = 0; j !== stride; ++ j ) {
  31283. const value = values[ offset + j ];
  31284. if ( value !== values[ offsetP + j ] ||
  31285. value !== values[ offsetN + j ] ) {
  31286. keep = true;
  31287. break;
  31288. }
  31289. }
  31290. } else {
  31291. keep = true;
  31292. }
  31293. }
  31294. // in-place compaction
  31295. if ( keep ) {
  31296. if ( i !== writeIndex ) {
  31297. times[ writeIndex ] = times[ i ];
  31298. const readOffset = i * stride,
  31299. writeOffset = writeIndex * stride;
  31300. for ( let j = 0; j !== stride; ++ j ) {
  31301. values[ writeOffset + j ] = values[ readOffset + j ];
  31302. }
  31303. }
  31304. ++ writeIndex;
  31305. }
  31306. }
  31307. // flush last keyframe (compaction looks ahead)
  31308. if ( lastIndex > 0 ) {
  31309. times[ writeIndex ] = times[ lastIndex ];
  31310. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31311. values[ writeOffset + j ] = values[ readOffset + j ];
  31312. }
  31313. ++ writeIndex;
  31314. }
  31315. if ( writeIndex !== times.length ) {
  31316. this.times = times.slice( 0, writeIndex );
  31317. this.values = values.slice( 0, writeIndex * stride );
  31318. } else {
  31319. this.times = times;
  31320. this.values = values;
  31321. }
  31322. return this;
  31323. }
  31324. /**
  31325. * Returns a new keyframe track with copied values from this instance.
  31326. *
  31327. * @return {KeyframeTrack} A clone of this instance.
  31328. */
  31329. clone() {
  31330. const times = this.times.slice();
  31331. const values = this.values.slice();
  31332. const TypedKeyframeTrack = this.constructor;
  31333. const track = new TypedKeyframeTrack( this.name, times, values );
  31334. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31335. track.createInterpolant = this.createInterpolant;
  31336. return track;
  31337. }
  31338. }
  31339. /**
  31340. * The value type name.
  31341. *
  31342. * @type {string}
  31343. * @default ''
  31344. */
  31345. KeyframeTrack.prototype.ValueTypeName = '';
  31346. /**
  31347. * The time buffer type of this keyframe track.
  31348. *
  31349. * @type {TypedArray|Array}
  31350. * @default Float32Array.constructor
  31351. */
  31352. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31353. /**
  31354. * The value buffer type of this keyframe track.
  31355. *
  31356. * @type {TypedArray|Array}
  31357. * @default Float32Array.constructor
  31358. */
  31359. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31360. /**
  31361. * The default interpolation type of this keyframe track.
  31362. *
  31363. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31364. * @default InterpolateLinear
  31365. */
  31366. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31367. /**
  31368. * A track for boolean keyframe values.
  31369. *
  31370. * @augments KeyframeTrack
  31371. */
  31372. class BooleanKeyframeTrack extends KeyframeTrack {
  31373. /**
  31374. * Constructs a new boolean keyframe track.
  31375. *
  31376. * This keyframe track type has no `interpolation` parameter because the
  31377. * interpolation is always discrete.
  31378. *
  31379. * @param {string} name - The keyframe track's name.
  31380. * @param {Array<number>} times - A list of keyframe times.
  31381. * @param {Array<boolean>} values - A list of keyframe values.
  31382. */
  31383. constructor( name, times, values ) {
  31384. super( name, times, values );
  31385. }
  31386. }
  31387. /**
  31388. * The value type name.
  31389. *
  31390. * @type {string}
  31391. * @default 'bool'
  31392. */
  31393. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31394. /**
  31395. * The value buffer type of this keyframe track.
  31396. *
  31397. * @type {TypedArray|Array}
  31398. * @default Array.constructor
  31399. */
  31400. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31401. /**
  31402. * The default interpolation type of this keyframe track.
  31403. *
  31404. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31405. * @default InterpolateDiscrete
  31406. */
  31407. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31408. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31409. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31410. /**
  31411. * A track for color keyframe values.
  31412. *
  31413. * @augments KeyframeTrack
  31414. */
  31415. class ColorKeyframeTrack extends KeyframeTrack {
  31416. /**
  31417. * Constructs a new color keyframe track.
  31418. *
  31419. * @param {string} name - The keyframe track's name.
  31420. * @param {Array<number>} times - A list of keyframe times.
  31421. * @param {Array<number>} values - A list of keyframe values.
  31422. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31423. */
  31424. constructor( name, times, values, interpolation ) {
  31425. super( name, times, values, interpolation );
  31426. }
  31427. }
  31428. /**
  31429. * The value type name.
  31430. *
  31431. * @type {string}
  31432. * @default 'color'
  31433. */
  31434. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31435. /**
  31436. * A track for numeric keyframe values.
  31437. *
  31438. * @augments KeyframeTrack
  31439. */
  31440. class NumberKeyframeTrack extends KeyframeTrack {
  31441. /**
  31442. * Constructs a new number keyframe track.
  31443. *
  31444. * @param {string} name - The keyframe track's name.
  31445. * @param {Array<number>} times - A list of keyframe times.
  31446. * @param {Array<number>} values - A list of keyframe values.
  31447. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31448. */
  31449. constructor( name, times, values, interpolation ) {
  31450. super( name, times, values, interpolation );
  31451. }
  31452. }
  31453. /**
  31454. * The value type name.
  31455. *
  31456. * @type {string}
  31457. * @default 'number'
  31458. */
  31459. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31460. /**
  31461. * Spherical linear unit quaternion interpolant.
  31462. *
  31463. * @augments Interpolant
  31464. */
  31465. class QuaternionLinearInterpolant extends Interpolant {
  31466. /**
  31467. * Constructs a new SLERP interpolant.
  31468. *
  31469. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31470. * @param {TypedArray} sampleValues - The sample values.
  31471. * @param {number} sampleSize - The sample size
  31472. * @param {TypedArray} [resultBuffer] - The result buffer.
  31473. */
  31474. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31475. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31476. }
  31477. interpolate_( i1, t0, t, t1 ) {
  31478. const result = this.resultBuffer,
  31479. values = this.sampleValues,
  31480. stride = this.valueSize,
  31481. alpha = ( t - t0 ) / ( t1 - t0 );
  31482. let offset = i1 * stride;
  31483. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31484. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31485. }
  31486. return result;
  31487. }
  31488. }
  31489. /**
  31490. * A track for Quaternion keyframe values.
  31491. *
  31492. * @augments KeyframeTrack
  31493. */
  31494. class QuaternionKeyframeTrack extends KeyframeTrack {
  31495. /**
  31496. * Constructs a new Quaternion keyframe track.
  31497. *
  31498. * @param {string} name - The keyframe track's name.
  31499. * @param {Array<number>} times - A list of keyframe times.
  31500. * @param {Array<number>} values - A list of keyframe values.
  31501. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31502. */
  31503. constructor( name, times, values, interpolation ) {
  31504. super( name, times, values, interpolation );
  31505. }
  31506. /**
  31507. * Overwritten so the method returns Quaternion based interpolant.
  31508. *
  31509. * @static
  31510. * @param {TypedArray} [result] - The result buffer.
  31511. * @return {QuaternionLinearInterpolant} The new interpolant.
  31512. */
  31513. InterpolantFactoryMethodLinear( result ) {
  31514. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31515. }
  31516. }
  31517. /**
  31518. * The value type name.
  31519. *
  31520. * @type {string}
  31521. * @default 'quaternion'
  31522. */
  31523. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31524. // ValueBufferType is inherited
  31525. // DefaultInterpolation is inherited;
  31526. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31527. /**
  31528. * A track for string keyframe values.
  31529. *
  31530. * @augments KeyframeTrack
  31531. */
  31532. class StringKeyframeTrack extends KeyframeTrack {
  31533. /**
  31534. * Constructs a new string keyframe track.
  31535. *
  31536. * This keyframe track type has no `interpolation` parameter because the
  31537. * interpolation is always discrete.
  31538. *
  31539. * @param {string} name - The keyframe track's name.
  31540. * @param {Array<number>} times - A list of keyframe times.
  31541. * @param {Array<string>} values - A list of keyframe values.
  31542. */
  31543. constructor( name, times, values ) {
  31544. super( name, times, values );
  31545. }
  31546. }
  31547. /**
  31548. * The value type name.
  31549. *
  31550. * @type {string}
  31551. * @default 'string'
  31552. */
  31553. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31554. /**
  31555. * The value buffer type of this keyframe track.
  31556. *
  31557. * @type {TypedArray|Array}
  31558. * @default Array.constructor
  31559. */
  31560. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31561. /**
  31562. * The default interpolation type of this keyframe track.
  31563. *
  31564. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31565. * @default InterpolateDiscrete
  31566. */
  31567. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31568. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31569. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31570. /**
  31571. * A track for vector keyframe values.
  31572. *
  31573. * @augments KeyframeTrack
  31574. */
  31575. class VectorKeyframeTrack extends KeyframeTrack {
  31576. /**
  31577. * Constructs a new vector keyframe track.
  31578. *
  31579. * @param {string} name - The keyframe track's name.
  31580. * @param {Array<number>} times - A list of keyframe times.
  31581. * @param {Array<number>} values - A list of keyframe values.
  31582. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31583. */
  31584. constructor( name, times, values, interpolation ) {
  31585. super( name, times, values, interpolation );
  31586. }
  31587. }
  31588. /**
  31589. * The value type name.
  31590. *
  31591. * @type {string}
  31592. * @default 'vector'
  31593. */
  31594. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31595. /**
  31596. * A reusable set of keyframe tracks which represent an animation.
  31597. */
  31598. class AnimationClip {
  31599. /**
  31600. * Constructs a new animation clip.
  31601. *
  31602. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31603. * use the static interface of this class for creating clips. In most cases though, animation clips
  31604. * will automatically be created by loaders when importing animated 3D assets.
  31605. *
  31606. * @param {string} [name=''] - The clip's name.
  31607. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31608. * the duration will be calculated from the passed keyframes.
  31609. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31610. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31611. * is blended/combined when two or more animations are simultaneously played.
  31612. */
  31613. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31614. /**
  31615. * The clip's name.
  31616. *
  31617. * @type {string}
  31618. */
  31619. this.name = name;
  31620. /**
  31621. * An array of keyframe tracks.
  31622. *
  31623. * @type {Array<KeyframeTrack>}
  31624. */
  31625. this.tracks = tracks;
  31626. /**
  31627. * The clip's duration in seconds.
  31628. *
  31629. * @type {number}
  31630. */
  31631. this.duration = duration;
  31632. /**
  31633. * Defines how the animation is blended/combined when two or more animations
  31634. * are simultaneously played.
  31635. *
  31636. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31637. */
  31638. this.blendMode = blendMode;
  31639. /**
  31640. * The UUID of the animation clip.
  31641. *
  31642. * @type {string}
  31643. * @readonly
  31644. */
  31645. this.uuid = generateUUID();
  31646. /**
  31647. * An object that can be used to store custom data about the animation clip.
  31648. * It should not hold references to functions as these will not be cloned.
  31649. *
  31650. * @type {Object}
  31651. */
  31652. this.userData = {};
  31653. // this means it should figure out its duration by scanning the tracks
  31654. if ( this.duration < 0 ) {
  31655. this.resetDuration();
  31656. }
  31657. }
  31658. /**
  31659. * Factory method for creating an animation clip from the given JSON.
  31660. *
  31661. * @static
  31662. * @param {Object} json - The serialized animation clip.
  31663. * @return {AnimationClip} The new animation clip.
  31664. */
  31665. static parse( json ) {
  31666. const tracks = [],
  31667. jsonTracks = json.tracks,
  31668. frameTime = 1.0 / ( json.fps || 1.0 );
  31669. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31670. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31671. }
  31672. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31673. clip.uuid = json.uuid;
  31674. clip.userData = JSON.parse( json.userData || '{}' );
  31675. return clip;
  31676. }
  31677. /**
  31678. * Serializes the given animation clip into JSON.
  31679. *
  31680. * @static
  31681. * @param {AnimationClip} clip - The animation clip to serialize.
  31682. * @return {Object} The JSON object.
  31683. */
  31684. static toJSON( clip ) {
  31685. const tracks = [],
  31686. clipTracks = clip.tracks;
  31687. const json = {
  31688. 'name': clip.name,
  31689. 'duration': clip.duration,
  31690. 'tracks': tracks,
  31691. 'uuid': clip.uuid,
  31692. 'blendMode': clip.blendMode,
  31693. 'userData': JSON.stringify( clip.userData ),
  31694. };
  31695. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31696. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31697. }
  31698. return json;
  31699. }
  31700. /**
  31701. * Returns a new animation clip from the passed morph targets array of a
  31702. * geometry, taking a name and the number of frames per second.
  31703. *
  31704. * Note: The fps parameter is required, but the animation speed can be
  31705. * overridden via {@link AnimationAction#setDuration}.
  31706. *
  31707. * @static
  31708. * @param {string} name - The name of the animation clip.
  31709. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31710. * @param {number} fps - The Frames-Per-Second value.
  31711. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31712. * @return {AnimationClip} The new animation clip.
  31713. */
  31714. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31715. const numMorphTargets = morphTargetSequence.length;
  31716. const tracks = [];
  31717. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31718. let times = [];
  31719. let values = [];
  31720. times.push(
  31721. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31722. i,
  31723. ( i + 1 ) % numMorphTargets );
  31724. values.push( 0, 1, 0 );
  31725. const order = getKeyframeOrder( times );
  31726. times = sortedArray( times, 1, order );
  31727. values = sortedArray( values, 1, order );
  31728. // if there is a key at the first frame, duplicate it as the
  31729. // last frame as well for perfect loop.
  31730. if ( ! noLoop && times[ 0 ] === 0 ) {
  31731. times.push( numMorphTargets );
  31732. values.push( values[ 0 ] );
  31733. }
  31734. tracks.push(
  31735. new NumberKeyframeTrack(
  31736. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31737. times, values
  31738. ).scale( 1.0 / fps ) );
  31739. }
  31740. return new this( name, -1, tracks );
  31741. }
  31742. /**
  31743. * Searches for an animation clip by name, taking as its first parameter
  31744. * either an array of clips, or a mesh or geometry that contains an
  31745. * array named "animations" property.
  31746. *
  31747. * @static
  31748. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31749. * @param {string} name - The name to search for.
  31750. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31751. */
  31752. static findByName( objectOrClipArray, name ) {
  31753. let clipArray = objectOrClipArray;
  31754. if ( ! Array.isArray( objectOrClipArray ) ) {
  31755. const o = objectOrClipArray;
  31756. clipArray = o.geometry && o.geometry.animations || o.animations;
  31757. }
  31758. for ( let i = 0; i < clipArray.length; i ++ ) {
  31759. if ( clipArray[ i ].name === name ) {
  31760. return clipArray[ i ];
  31761. }
  31762. }
  31763. return null;
  31764. }
  31765. /**
  31766. * Returns an array of new AnimationClips created from the morph target
  31767. * sequences of a geometry, trying to sort morph target names into
  31768. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31769. *
  31770. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31771. *
  31772. * @static
  31773. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31774. * @param {number} fps - The Frames-Per-Second value.
  31775. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31776. * @return {Array<AnimationClip>} An array of new animation clips.
  31777. */
  31778. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31779. const animationToMorphTargets = {};
  31780. // tested with https://regex101.com/ on trick sequences
  31781. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31782. const pattern = /^([\w-]*?)([\d]+)$/;
  31783. // sort morph target names into animation groups based
  31784. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31785. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31786. const morphTarget = morphTargets[ i ];
  31787. const parts = morphTarget.name.match( pattern );
  31788. if ( parts && parts.length > 1 ) {
  31789. const name = parts[ 1 ];
  31790. let animationMorphTargets = animationToMorphTargets[ name ];
  31791. if ( ! animationMorphTargets ) {
  31792. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31793. }
  31794. animationMorphTargets.push( morphTarget );
  31795. }
  31796. }
  31797. const clips = [];
  31798. for ( const name in animationToMorphTargets ) {
  31799. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31800. }
  31801. return clips;
  31802. }
  31803. /**
  31804. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31805. *
  31806. * @static
  31807. * @deprecated since r175.
  31808. * @param {Object} animation - A serialized animation clip as JSON.
  31809. * @param {Array<Bone>} bones - An array of bones.
  31810. * @return {?AnimationClip} The new animation clip.
  31811. */
  31812. static parseAnimation( animation, bones ) {
  31813. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31814. if ( ! animation ) {
  31815. error( 'AnimationClip: No animation in JSONLoader data.' );
  31816. return null;
  31817. }
  31818. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31819. // only return track if there are actually keys.
  31820. if ( animationKeys.length !== 0 ) {
  31821. const times = [];
  31822. const values = [];
  31823. flattenJSON( animationKeys, times, values, propertyName );
  31824. // empty keys are filtered out, so check again
  31825. if ( times.length !== 0 ) {
  31826. destTracks.push( new trackType( trackName, times, values ) );
  31827. }
  31828. }
  31829. };
  31830. const tracks = [];
  31831. const clipName = animation.name || 'default';
  31832. const fps = animation.fps || 30;
  31833. const blendMode = animation.blendMode;
  31834. // automatic length determination in AnimationClip.
  31835. let duration = animation.length || -1;
  31836. const hierarchyTracks = animation.hierarchy || [];
  31837. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31838. const animationKeys = hierarchyTracks[ h ].keys;
  31839. // skip empty tracks
  31840. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31841. // process morph targets
  31842. if ( animationKeys[ 0 ].morphTargets ) {
  31843. // figure out all morph targets used in this track
  31844. const morphTargetNames = {};
  31845. let k;
  31846. for ( k = 0; k < animationKeys.length; k ++ ) {
  31847. if ( animationKeys[ k ].morphTargets ) {
  31848. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31849. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31850. }
  31851. }
  31852. }
  31853. // create a track for each morph target with all zero
  31854. // morphTargetInfluences except for the keys in which
  31855. // the morphTarget is named.
  31856. for ( const morphTargetName in morphTargetNames ) {
  31857. const times = [];
  31858. const values = [];
  31859. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31860. const animationKey = animationKeys[ k ];
  31861. times.push( animationKey.time );
  31862. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31863. }
  31864. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31865. }
  31866. duration = morphTargetNames.length * fps;
  31867. } else {
  31868. // ...assume skeletal animation
  31869. const boneName = '.bones[' + bones[ h ].name + ']';
  31870. addNonemptyTrack(
  31871. VectorKeyframeTrack, boneName + '.position',
  31872. animationKeys, 'pos', tracks );
  31873. addNonemptyTrack(
  31874. QuaternionKeyframeTrack, boneName + '.quaternion',
  31875. animationKeys, 'rot', tracks );
  31876. addNonemptyTrack(
  31877. VectorKeyframeTrack, boneName + '.scale',
  31878. animationKeys, 'scl', tracks );
  31879. }
  31880. }
  31881. if ( tracks.length === 0 ) {
  31882. return null;
  31883. }
  31884. const clip = new this( clipName, duration, tracks, blendMode );
  31885. return clip;
  31886. }
  31887. /**
  31888. * Sets the duration of this clip to the duration of its longest keyframe track.
  31889. *
  31890. * @return {AnimationClip} A reference to this animation clip.
  31891. */
  31892. resetDuration() {
  31893. const tracks = this.tracks;
  31894. let duration = 0;
  31895. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31896. const track = this.tracks[ i ];
  31897. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31898. }
  31899. this.duration = duration;
  31900. return this;
  31901. }
  31902. /**
  31903. * Trims all tracks to the clip's duration.
  31904. *
  31905. * @return {AnimationClip} A reference to this animation clip.
  31906. */
  31907. trim() {
  31908. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31909. this.tracks[ i ].trim( 0, this.duration );
  31910. }
  31911. return this;
  31912. }
  31913. /**
  31914. * Performs minimal validation on each track in the clip. Returns `true` if all
  31915. * tracks are valid.
  31916. *
  31917. * @return {boolean} Whether the clip's keyframes are valid or not.
  31918. */
  31919. validate() {
  31920. let valid = true;
  31921. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31922. valid = valid && this.tracks[ i ].validate();
  31923. }
  31924. return valid;
  31925. }
  31926. /**
  31927. * Optimizes each track by removing equivalent sequential keys (which are
  31928. * common in morph target sequences).
  31929. *
  31930. * @return {AnimationClip} A reference to this animation clip.
  31931. */
  31932. optimize() {
  31933. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31934. this.tracks[ i ].optimize();
  31935. }
  31936. return this;
  31937. }
  31938. /**
  31939. * Returns a new animation clip with copied values from this instance.
  31940. *
  31941. * @return {AnimationClip} A clone of this instance.
  31942. */
  31943. clone() {
  31944. const tracks = [];
  31945. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31946. tracks.push( this.tracks[ i ].clone() );
  31947. }
  31948. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31949. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31950. return clip;
  31951. }
  31952. /**
  31953. * Serializes this animation clip into JSON.
  31954. *
  31955. * @return {Object} The JSON object.
  31956. */
  31957. toJSON() {
  31958. return this.constructor.toJSON( this );
  31959. }
  31960. }
  31961. function getTrackTypeForValueTypeName( typeName ) {
  31962. switch ( typeName.toLowerCase() ) {
  31963. case 'scalar':
  31964. case 'double':
  31965. case 'float':
  31966. case 'number':
  31967. case 'integer':
  31968. return NumberKeyframeTrack;
  31969. case 'vector':
  31970. case 'vector2':
  31971. case 'vector3':
  31972. case 'vector4':
  31973. return VectorKeyframeTrack;
  31974. case 'color':
  31975. return ColorKeyframeTrack;
  31976. case 'quaternion':
  31977. return QuaternionKeyframeTrack;
  31978. case 'bool':
  31979. case 'boolean':
  31980. return BooleanKeyframeTrack;
  31981. case 'string':
  31982. return StringKeyframeTrack;
  31983. }
  31984. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31985. }
  31986. function parseKeyframeTrack( json ) {
  31987. if ( json.type === undefined ) {
  31988. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31989. }
  31990. const trackType = getTrackTypeForValueTypeName( json.type );
  31991. if ( json.times === undefined ) {
  31992. const times = [], values = [];
  31993. flattenJSON( json.keys, times, values, 'value' );
  31994. json.times = times;
  31995. json.values = values;
  31996. }
  31997. // derived classes can define a static parse method
  31998. if ( trackType.parse !== undefined ) {
  31999. return trackType.parse( json );
  32000. } else {
  32001. // by default, we assume a constructor compatible with the base
  32002. return new trackType( json.name, json.times, json.values, json.interpolation );
  32003. }
  32004. }
  32005. /**
  32006. * @class
  32007. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32008. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32009. * @hideconstructor
  32010. */
  32011. const Cache = {
  32012. /**
  32013. * Whether caching is enabled or not.
  32014. *
  32015. * @static
  32016. * @type {boolean}
  32017. * @default false
  32018. */
  32019. enabled: false,
  32020. /**
  32021. * A dictionary that holds cached files.
  32022. *
  32023. * @static
  32024. * @type {Object<string,Object>}
  32025. */
  32026. files: {},
  32027. /**
  32028. * Adds a cache entry with a key to reference the file. If this key already
  32029. * holds a file, it is overwritten.
  32030. *
  32031. * @static
  32032. * @param {string} key - The key to reference the cached file.
  32033. * @param {Object} file - The file to be cached.
  32034. */
  32035. add: function ( key, file ) {
  32036. if ( this.enabled === false ) return;
  32037. // log( 'Cache', 'Adding key:', key );
  32038. this.files[ key ] = file;
  32039. },
  32040. /**
  32041. * Gets the cached value for the given key.
  32042. *
  32043. * @static
  32044. * @param {string} key - The key to reference the cached file.
  32045. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32046. */
  32047. get: function ( key ) {
  32048. if ( this.enabled === false ) return;
  32049. // log( 'Cache', 'Checking key:', key );
  32050. return this.files[ key ];
  32051. },
  32052. /**
  32053. * Removes the cached file associated with the given key.
  32054. *
  32055. * @static
  32056. * @param {string} key - The key to reference the cached file.
  32057. */
  32058. remove: function ( key ) {
  32059. delete this.files[ key ];
  32060. },
  32061. /**
  32062. * Remove all values from the cache.
  32063. *
  32064. * @static
  32065. */
  32066. clear: function () {
  32067. this.files = {};
  32068. }
  32069. };
  32070. /**
  32071. * Handles and keeps track of loaded and pending data. A default global
  32072. * instance of this class is created and used by loaders if not supplied
  32073. * manually.
  32074. *
  32075. * In general that should be sufficient, however there are times when it can
  32076. * be useful to have separate loaders - for example if you want to show
  32077. * separate loading bars for objects and textures.
  32078. *
  32079. * ```js
  32080. * const manager = new THREE.LoadingManager();
  32081. * manager.onLoad = () => console.log( 'Loading complete!' );
  32082. *
  32083. * const loader1 = new OBJLoader( manager );
  32084. * const loader2 = new ColladaLoader( manager );
  32085. * ```
  32086. */
  32087. class LoadingManager {
  32088. /**
  32089. * Constructs a new loading manager.
  32090. *
  32091. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32092. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32093. * @param {Function} [onError] - Executes when an error occurs.
  32094. */
  32095. constructor( onLoad, onProgress, onError ) {
  32096. const scope = this;
  32097. let isLoading = false;
  32098. let itemsLoaded = 0;
  32099. let itemsTotal = 0;
  32100. let urlModifier = undefined;
  32101. const handlers = [];
  32102. // Refer to #5689 for the reason why we don't set .onStart
  32103. // in the constructor
  32104. /**
  32105. * Executes when an item starts loading.
  32106. *
  32107. * @type {Function|undefined}
  32108. * @default undefined
  32109. */
  32110. this.onStart = undefined;
  32111. /**
  32112. * Executes when all items have been loaded.
  32113. *
  32114. * @type {Function|undefined}
  32115. * @default undefined
  32116. */
  32117. this.onLoad = onLoad;
  32118. /**
  32119. * Executes when single items have been loaded.
  32120. *
  32121. * @type {Function|undefined}
  32122. * @default undefined
  32123. */
  32124. this.onProgress = onProgress;
  32125. /**
  32126. * Executes when an error occurs.
  32127. *
  32128. * @type {Function|undefined}
  32129. * @default undefined
  32130. */
  32131. this.onError = onError;
  32132. /**
  32133. * Used for aborting ongoing requests in loaders using this manager.
  32134. *
  32135. * @private
  32136. * @type {AbortController | null}
  32137. */
  32138. this._abortController = null;
  32139. /**
  32140. * This should be called by any loader using the manager when the loader
  32141. * starts loading an item.
  32142. *
  32143. * @param {string} url - The URL to load.
  32144. */
  32145. this.itemStart = function ( url ) {
  32146. itemsTotal ++;
  32147. if ( isLoading === false ) {
  32148. if ( scope.onStart !== undefined ) {
  32149. scope.onStart( url, itemsLoaded, itemsTotal );
  32150. }
  32151. }
  32152. isLoading = true;
  32153. };
  32154. /**
  32155. * This should be called by any loader using the manager when the loader
  32156. * ended loading an item.
  32157. *
  32158. * @param {string} url - The URL of the loaded item.
  32159. */
  32160. this.itemEnd = function ( url ) {
  32161. itemsLoaded ++;
  32162. if ( scope.onProgress !== undefined ) {
  32163. scope.onProgress( url, itemsLoaded, itemsTotal );
  32164. }
  32165. if ( itemsLoaded === itemsTotal ) {
  32166. isLoading = false;
  32167. if ( scope.onLoad !== undefined ) {
  32168. scope.onLoad();
  32169. }
  32170. }
  32171. };
  32172. /**
  32173. * This should be called by any loader using the manager when the loader
  32174. * encounters an error when loading an item.
  32175. *
  32176. * @param {string} url - The URL of the item that produces an error.
  32177. */
  32178. this.itemError = function ( url ) {
  32179. if ( scope.onError !== undefined ) {
  32180. scope.onError( url );
  32181. }
  32182. };
  32183. /**
  32184. * Given a URL, uses the URL modifier callback (if any) and returns a
  32185. * resolved URL. If no URL modifier is set, returns the original URL.
  32186. *
  32187. * @param {string} url - The URL to load.
  32188. * @return {string} The resolved URL.
  32189. */
  32190. this.resolveURL = function ( url ) {
  32191. if ( urlModifier ) {
  32192. return urlModifier( url );
  32193. }
  32194. return url;
  32195. };
  32196. /**
  32197. * If provided, the callback will be passed each resource URL before a
  32198. * request is sent. The callback may return the original URL, or a new URL to
  32199. * override loading behavior. This behavior can be used to load assets from
  32200. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32201. *
  32202. * ```js
  32203. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32204. *
  32205. * const manager = new THREE.LoadingManager();
  32206. *
  32207. * // Initialize loading manager with URL callback.
  32208. * const objectURLs = [];
  32209. * manager.setURLModifier( ( url ) => {
  32210. *
  32211. * url = URL.createObjectURL( blobs[ url ] );
  32212. * objectURLs.push( url );
  32213. * return url;
  32214. *
  32215. * } );
  32216. *
  32217. * // Load as usual, then revoke the blob URLs.
  32218. * const loader = new GLTFLoader( manager );
  32219. * loader.load( 'fish.gltf', (gltf) => {
  32220. *
  32221. * scene.add( gltf.scene );
  32222. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32223. *
  32224. * } );
  32225. * ```
  32226. *
  32227. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32228. * @return {LoadingManager} A reference to this loading manager.
  32229. */
  32230. this.setURLModifier = function ( transform ) {
  32231. urlModifier = transform;
  32232. return this;
  32233. };
  32234. /**
  32235. * Registers a loader with the given regular expression. Can be used to
  32236. * define what loader should be used in order to load specific files. A
  32237. * typical use case is to overwrite the default loader for textures.
  32238. *
  32239. * ```js
  32240. * // add handler for TGA textures
  32241. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32242. * ```
  32243. *
  32244. * @param {string} regex - A regular expression.
  32245. * @param {Loader} loader - A loader that should handle matched cases.
  32246. * @return {LoadingManager} A reference to this loading manager.
  32247. */
  32248. this.addHandler = function ( regex, loader ) {
  32249. handlers.push( regex, loader );
  32250. return this;
  32251. };
  32252. /**
  32253. * Removes the loader for the given regular expression.
  32254. *
  32255. * @param {string} regex - A regular expression.
  32256. * @return {LoadingManager} A reference to this loading manager.
  32257. */
  32258. this.removeHandler = function ( regex ) {
  32259. const index = handlers.indexOf( regex );
  32260. if ( index !== -1 ) {
  32261. handlers.splice( index, 2 );
  32262. }
  32263. return this;
  32264. };
  32265. /**
  32266. * Can be used to retrieve the registered loader for the given file path.
  32267. *
  32268. * @param {string} file - The file path.
  32269. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32270. */
  32271. this.getHandler = function ( file ) {
  32272. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32273. const regex = handlers[ i ];
  32274. const loader = handlers[ i + 1 ];
  32275. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32276. if ( regex.test( file ) ) {
  32277. return loader;
  32278. }
  32279. }
  32280. return null;
  32281. };
  32282. /**
  32283. * Can be used to abort ongoing loading requests in loaders using this manager.
  32284. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32285. * is supported in the browser.
  32286. *
  32287. * @return {LoadingManager} A reference to this loading manager.
  32288. */
  32289. this.abort = function () {
  32290. this.abortController.abort();
  32291. this._abortController = null;
  32292. return this;
  32293. };
  32294. }
  32295. // TODO: Revert this back to a single member variable once this issue has been fixed
  32296. // https://github.com/cloudflare/workerd/issues/3657
  32297. /**
  32298. * Used for aborting ongoing requests in loaders using this manager.
  32299. *
  32300. * @type {AbortController}
  32301. */
  32302. get abortController() {
  32303. if ( ! this._abortController ) {
  32304. this._abortController = new AbortController();
  32305. }
  32306. return this._abortController;
  32307. }
  32308. }
  32309. /**
  32310. * The global default loading manager.
  32311. *
  32312. * @constant
  32313. * @type {LoadingManager}
  32314. */
  32315. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32316. /**
  32317. * Abstract base class for loaders.
  32318. *
  32319. * @abstract
  32320. */
  32321. class Loader {
  32322. /**
  32323. * Constructs a new loader.
  32324. *
  32325. * @param {LoadingManager} [manager] - The loading manager.
  32326. */
  32327. constructor( manager ) {
  32328. /**
  32329. * The loading manager.
  32330. *
  32331. * @type {LoadingManager}
  32332. * @default DefaultLoadingManager
  32333. */
  32334. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32335. /**
  32336. * The crossOrigin string to implement CORS for loading the url from a
  32337. * different domain that allows CORS.
  32338. *
  32339. * @type {string}
  32340. * @default 'anonymous'
  32341. */
  32342. this.crossOrigin = 'anonymous';
  32343. /**
  32344. * Whether the XMLHttpRequest uses credentials.
  32345. *
  32346. * @type {boolean}
  32347. * @default false
  32348. */
  32349. this.withCredentials = false;
  32350. /**
  32351. * The base path from which the asset will be loaded.
  32352. *
  32353. * @type {string}
  32354. */
  32355. this.path = '';
  32356. /**
  32357. * The base path from which additional resources like textures will be loaded.
  32358. *
  32359. * @type {string}
  32360. */
  32361. this.resourcePath = '';
  32362. /**
  32363. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32364. * used in HTTP request.
  32365. *
  32366. * @type {Object<string, any>}
  32367. */
  32368. this.requestHeader = {};
  32369. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32370. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32371. }
  32372. }
  32373. /**
  32374. * This method needs to be implemented by all concrete loaders. It holds the
  32375. * logic for loading assets from the backend.
  32376. *
  32377. * @abstract
  32378. * @param {string} url - The path/URL of the file to be loaded.
  32379. * @param {Function} onLoad - Executed when the loading process has been finished.
  32380. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32381. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32382. */
  32383. load( /* url, onLoad, onProgress, onError */ ) {}
  32384. /**
  32385. * A async version of {@link Loader#load}.
  32386. *
  32387. * @param {string} url - The path/URL of the file to be loaded.
  32388. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32389. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32390. */
  32391. loadAsync( url, onProgress ) {
  32392. const scope = this;
  32393. return new Promise( function ( resolve, reject ) {
  32394. scope.load( url, resolve, onProgress, reject );
  32395. } );
  32396. }
  32397. /**
  32398. * This method needs to be implemented by all concrete loaders. It holds the
  32399. * logic for parsing the asset into three.js entities.
  32400. *
  32401. * @abstract
  32402. * @param {any} data - The data to parse.
  32403. */
  32404. parse( /* data */ ) {}
  32405. /**
  32406. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32407. * from a different domain that allows CORS.
  32408. *
  32409. * @param {string} crossOrigin - The `crossOrigin` value.
  32410. * @return {Loader} A reference to this instance.
  32411. */
  32412. setCrossOrigin( crossOrigin ) {
  32413. this.crossOrigin = crossOrigin;
  32414. return this;
  32415. }
  32416. /**
  32417. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32418. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32419. *
  32420. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32421. *
  32422. * @param {boolean} value - The `withCredentials` value.
  32423. * @return {Loader} A reference to this instance.
  32424. */
  32425. setWithCredentials( value ) {
  32426. this.withCredentials = value;
  32427. return this;
  32428. }
  32429. /**
  32430. * Sets the base path for the asset.
  32431. *
  32432. * @param {string} path - The base path.
  32433. * @return {Loader} A reference to this instance.
  32434. */
  32435. setPath( path ) {
  32436. this.path = path;
  32437. return this;
  32438. }
  32439. /**
  32440. * Sets the base path for dependent resources like textures.
  32441. *
  32442. * @param {string} resourcePath - The resource path.
  32443. * @return {Loader} A reference to this instance.
  32444. */
  32445. setResourcePath( resourcePath ) {
  32446. this.resourcePath = resourcePath;
  32447. return this;
  32448. }
  32449. /**
  32450. * Sets the given request header.
  32451. *
  32452. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32453. * for configuring the HTTP request.
  32454. * @return {Loader} A reference to this instance.
  32455. */
  32456. setRequestHeader( requestHeader ) {
  32457. this.requestHeader = requestHeader;
  32458. return this;
  32459. }
  32460. /**
  32461. * This method can be implemented in loaders for aborting ongoing requests.
  32462. *
  32463. * @abstract
  32464. * @return {Loader} A reference to this instance.
  32465. */
  32466. abort() {
  32467. return this;
  32468. }
  32469. }
  32470. /**
  32471. * Callback for onProgress in loaders.
  32472. *
  32473. * @callback onProgressCallback
  32474. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32475. */
  32476. /**
  32477. * Callback for onError in loaders.
  32478. *
  32479. * @callback onErrorCallback
  32480. * @param {Error} error - The error which occurred during the loading process.
  32481. */
  32482. /**
  32483. * The default material name that is used by loaders
  32484. * when creating materials for loaded 3D objects.
  32485. *
  32486. * Note: Not all loaders might honor this setting.
  32487. *
  32488. * @static
  32489. * @type {string}
  32490. * @default '__DEFAULT'
  32491. */
  32492. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32493. const loading = {};
  32494. class HttpError extends Error {
  32495. constructor( message, response ) {
  32496. super( message );
  32497. this.response = response;
  32498. }
  32499. }
  32500. /**
  32501. * A low level class for loading resources with the Fetch API, used internally by
  32502. * most loaders. It can also be used directly to load any file type that does
  32503. * not have a loader.
  32504. *
  32505. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32506. * once to your application.
  32507. *
  32508. * ```js
  32509. * const loader = new THREE.FileLoader();
  32510. * const data = await loader.loadAsync( 'example.txt' );
  32511. * ```
  32512. *
  32513. * @augments Loader
  32514. */
  32515. class FileLoader extends Loader {
  32516. /**
  32517. * Constructs a new file loader.
  32518. *
  32519. * @param {LoadingManager} [manager] - The loading manager.
  32520. */
  32521. constructor( manager ) {
  32522. super( manager );
  32523. /**
  32524. * The expected mime type. Valid values can be found
  32525. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32526. *
  32527. * @type {string}
  32528. */
  32529. this.mimeType = '';
  32530. /**
  32531. * The expected response type.
  32532. *
  32533. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32534. * @default ''
  32535. */
  32536. this.responseType = '';
  32537. /**
  32538. * Used for aborting requests.
  32539. *
  32540. * @private
  32541. * @type {AbortController}
  32542. */
  32543. this._abortController = new AbortController();
  32544. }
  32545. /**
  32546. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32547. *
  32548. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32549. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32550. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32551. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32552. * @return {any|undefined} The cached resource if available.
  32553. */
  32554. load( url, onLoad, onProgress, onError ) {
  32555. if ( url === undefined ) url = '';
  32556. if ( this.path !== undefined ) url = this.path + url;
  32557. url = this.manager.resolveURL( url );
  32558. const cached = Cache.get( `file:${url}` );
  32559. if ( cached !== undefined ) {
  32560. this.manager.itemStart( url );
  32561. setTimeout( () => {
  32562. if ( onLoad ) onLoad( cached );
  32563. this.manager.itemEnd( url );
  32564. }, 0 );
  32565. return cached;
  32566. }
  32567. // Check if request is duplicate
  32568. if ( loading[ url ] !== undefined ) {
  32569. loading[ url ].push( {
  32570. onLoad: onLoad,
  32571. onProgress: onProgress,
  32572. onError: onError
  32573. } );
  32574. return;
  32575. }
  32576. // Initialise array for duplicate requests
  32577. loading[ url ] = [];
  32578. loading[ url ].push( {
  32579. onLoad: onLoad,
  32580. onProgress: onProgress,
  32581. onError: onError,
  32582. } );
  32583. // create request
  32584. const req = new Request( url, {
  32585. headers: new Headers( this.requestHeader ),
  32586. credentials: this.withCredentials ? 'include' : 'same-origin',
  32587. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32588. } );
  32589. // record states ( avoid data race )
  32590. const mimeType = this.mimeType;
  32591. const responseType = this.responseType;
  32592. // start the fetch
  32593. fetch( req )
  32594. .then( response => {
  32595. if ( response.status === 200 || response.status === 0 ) {
  32596. // Some browsers return HTTP Status 0 when using non-http protocol
  32597. // e.g. 'file://' or 'data://'. Handle as success.
  32598. if ( response.status === 0 ) {
  32599. warn( 'FileLoader: HTTP Status 0 received.' );
  32600. }
  32601. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32602. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32603. return response;
  32604. }
  32605. const callbacks = loading[ url ];
  32606. const reader = response.body.getReader();
  32607. // Nginx needs X-File-Size check
  32608. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32609. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32610. const total = contentLength ? parseInt( contentLength ) : 0;
  32611. const lengthComputable = total !== 0;
  32612. let loaded = 0;
  32613. // periodically read data into the new stream tracking while download progress
  32614. const stream = new ReadableStream( {
  32615. start( controller ) {
  32616. readData();
  32617. function readData() {
  32618. reader.read().then( ( { done, value } ) => {
  32619. if ( done ) {
  32620. controller.close();
  32621. } else {
  32622. loaded += value.byteLength;
  32623. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32624. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32625. const callback = callbacks[ i ];
  32626. if ( callback.onProgress ) callback.onProgress( event );
  32627. }
  32628. controller.enqueue( value );
  32629. readData();
  32630. }
  32631. }, ( e ) => {
  32632. controller.error( e );
  32633. } );
  32634. }
  32635. }
  32636. } );
  32637. return new Response( stream );
  32638. } else {
  32639. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32640. }
  32641. } )
  32642. .then( response => {
  32643. switch ( responseType ) {
  32644. case 'arraybuffer':
  32645. return response.arrayBuffer();
  32646. case 'blob':
  32647. return response.blob();
  32648. case 'document':
  32649. return response.text()
  32650. .then( text => {
  32651. const parser = new DOMParser();
  32652. return parser.parseFromString( text, mimeType );
  32653. } );
  32654. case 'json':
  32655. return response.json();
  32656. default:
  32657. if ( mimeType === '' ) {
  32658. return response.text();
  32659. } else {
  32660. // sniff encoding
  32661. const re = /charset="?([^;"\s]*)"?/i;
  32662. const exec = re.exec( mimeType );
  32663. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32664. const decoder = new TextDecoder( label );
  32665. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32666. }
  32667. }
  32668. } )
  32669. .then( data => {
  32670. // Add to cache only on HTTP success, so that we do not cache
  32671. // error response bodies as proper responses to requests.
  32672. Cache.add( `file:${url}`, data );
  32673. const callbacks = loading[ url ];
  32674. delete loading[ url ];
  32675. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32676. const callback = callbacks[ i ];
  32677. if ( callback.onLoad ) callback.onLoad( data );
  32678. }
  32679. } )
  32680. .catch( err => {
  32681. // Abort errors and other errors are handled the same
  32682. const callbacks = loading[ url ];
  32683. if ( callbacks === undefined ) {
  32684. // When onLoad was called and url was deleted in `loading`
  32685. this.manager.itemError( url );
  32686. throw err;
  32687. }
  32688. delete loading[ url ];
  32689. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32690. const callback = callbacks[ i ];
  32691. if ( callback.onError ) callback.onError( err );
  32692. }
  32693. this.manager.itemError( url );
  32694. } )
  32695. .finally( () => {
  32696. this.manager.itemEnd( url );
  32697. } );
  32698. this.manager.itemStart( url );
  32699. }
  32700. /**
  32701. * Sets the expected response type.
  32702. *
  32703. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32704. * @return {FileLoader} A reference to this file loader.
  32705. */
  32706. setResponseType( value ) {
  32707. this.responseType = value;
  32708. return this;
  32709. }
  32710. /**
  32711. * Sets the expected mime type of the loaded file.
  32712. *
  32713. * @param {string} value - The mime type.
  32714. * @return {FileLoader} A reference to this file loader.
  32715. */
  32716. setMimeType( value ) {
  32717. this.mimeType = value;
  32718. return this;
  32719. }
  32720. /**
  32721. * Aborts ongoing fetch requests.
  32722. *
  32723. * @return {FileLoader} A reference to this instance.
  32724. */
  32725. abort() {
  32726. this._abortController.abort();
  32727. this._abortController = new AbortController();
  32728. return this;
  32729. }
  32730. }
  32731. /**
  32732. * Class for loading animation clips in the JSON format. The files are internally
  32733. * loaded via {@link FileLoader}.
  32734. *
  32735. * ```js
  32736. * const loader = new THREE.AnimationLoader();
  32737. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32738. * ```
  32739. *
  32740. * @augments Loader
  32741. */
  32742. class AnimationLoader extends Loader {
  32743. /**
  32744. * Constructs a new animation loader.
  32745. *
  32746. * @param {LoadingManager} [manager] - The loading manager.
  32747. */
  32748. constructor( manager ) {
  32749. super( manager );
  32750. }
  32751. /**
  32752. * Starts loading from the given URL and pass the loaded animations as an array
  32753. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32754. *
  32755. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32756. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32757. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32758. * @param {onErrorCallback} onError - Executed when errors occur.
  32759. */
  32760. load( url, onLoad, onProgress, onError ) {
  32761. const scope = this;
  32762. const loader = new FileLoader( this.manager );
  32763. loader.setPath( this.path );
  32764. loader.setRequestHeader( this.requestHeader );
  32765. loader.setWithCredentials( this.withCredentials );
  32766. loader.load( url, function ( text ) {
  32767. try {
  32768. onLoad( scope.parse( JSON.parse( text ) ) );
  32769. } catch ( e ) {
  32770. if ( onError ) {
  32771. onError( e );
  32772. } else {
  32773. error( e );
  32774. }
  32775. scope.manager.itemError( url );
  32776. }
  32777. }, onProgress, onError );
  32778. }
  32779. /**
  32780. * Parses the given JSON object and returns an array of animation clips.
  32781. *
  32782. * @param {Object} json - The serialized animation clips.
  32783. * @return {Array<AnimationClip>} The parsed animation clips.
  32784. */
  32785. parse( json ) {
  32786. const animations = [];
  32787. for ( let i = 0; i < json.length; i ++ ) {
  32788. const clip = AnimationClip.parse( json[ i ] );
  32789. animations.push( clip );
  32790. }
  32791. return animations;
  32792. }
  32793. }
  32794. /**
  32795. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32796. * Textures are internally loaded via {@link FileLoader}.
  32797. *
  32798. * Derived classes have to implement the `parse()` method which holds the parsing
  32799. * for the respective format.
  32800. *
  32801. * @abstract
  32802. * @augments Loader
  32803. */
  32804. class CompressedTextureLoader extends Loader {
  32805. /**
  32806. * Constructs a new compressed texture loader.
  32807. *
  32808. * @param {LoadingManager} [manager] - The loading manager.
  32809. */
  32810. constructor( manager ) {
  32811. super( manager );
  32812. }
  32813. /**
  32814. * Starts loading from the given URL and passes the loaded compressed texture
  32815. * to the `onLoad()` callback. The method also returns a new texture object which can
  32816. * directly be used for material creation. If you do it this way, the texture
  32817. * may pop up in your scene once the respective loading process is finished.
  32818. *
  32819. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32820. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32821. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32822. * @param {onErrorCallback} onError - Executed when errors occur.
  32823. * @return {CompressedTexture} The compressed texture.
  32824. */
  32825. load( url, onLoad, onProgress, onError ) {
  32826. const scope = this;
  32827. const images = [];
  32828. const texture = new CompressedTexture();
  32829. const loader = new FileLoader( this.manager );
  32830. loader.setPath( this.path );
  32831. loader.setResponseType( 'arraybuffer' );
  32832. loader.setRequestHeader( this.requestHeader );
  32833. loader.setWithCredentials( scope.withCredentials );
  32834. let loaded = 0;
  32835. function loadTexture( i ) {
  32836. loader.load( url[ i ], function ( buffer ) {
  32837. const texDatas = scope.parse( buffer, true );
  32838. images[ i ] = {
  32839. width: texDatas.width,
  32840. height: texDatas.height,
  32841. format: texDatas.format,
  32842. mipmaps: texDatas.mipmaps
  32843. };
  32844. loaded += 1;
  32845. if ( loaded === 6 ) {
  32846. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32847. texture.image = images;
  32848. texture.format = texDatas.format;
  32849. texture.needsUpdate = true;
  32850. if ( onLoad ) onLoad( texture );
  32851. }
  32852. }, onProgress, onError );
  32853. }
  32854. if ( Array.isArray( url ) ) {
  32855. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32856. loadTexture( i );
  32857. }
  32858. } else {
  32859. // compressed cubemap texture stored in a single DDS file
  32860. loader.load( url, function ( buffer ) {
  32861. const texDatas = scope.parse( buffer, true );
  32862. if ( texDatas.isCubemap ) {
  32863. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32864. for ( let f = 0; f < faces; f ++ ) {
  32865. images[ f ] = { mipmaps: [] };
  32866. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32867. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32868. images[ f ].format = texDatas.format;
  32869. images[ f ].width = texDatas.width;
  32870. images[ f ].height = texDatas.height;
  32871. }
  32872. }
  32873. texture.image = images;
  32874. } else {
  32875. texture.image.width = texDatas.width;
  32876. texture.image.height = texDatas.height;
  32877. texture.mipmaps = texDatas.mipmaps;
  32878. }
  32879. if ( texDatas.mipmapCount === 1 ) {
  32880. texture.minFilter = LinearFilter;
  32881. }
  32882. texture.format = texDatas.format;
  32883. texture.needsUpdate = true;
  32884. if ( onLoad ) onLoad( texture );
  32885. }, onProgress, onError );
  32886. }
  32887. return texture;
  32888. }
  32889. }
  32890. const _loading = new WeakMap();
  32891. /**
  32892. * A loader for loading images. The class loads images with the HTML `Image` API.
  32893. *
  32894. * ```js
  32895. * const loader = new THREE.ImageLoader();
  32896. * const image = await loader.loadAsync( 'image.png' );
  32897. * ```
  32898. * Please note that `ImageLoader` has dropped support for progress
  32899. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32900. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32901. *
  32902. * @augments Loader
  32903. */
  32904. class ImageLoader extends Loader {
  32905. /**
  32906. * Constructs a new image loader.
  32907. *
  32908. * @param {LoadingManager} [manager] - The loading manager.
  32909. */
  32910. constructor( manager ) {
  32911. super( manager );
  32912. }
  32913. /**
  32914. * Starts loading from the given URL and passes the loaded image
  32915. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32916. * directly be used for texture creation. If you do it this way, the texture
  32917. * may pop up in your scene once the respective loading process is finished.
  32918. *
  32919. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32920. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32921. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32922. * @param {onErrorCallback} onError - Executed when errors occur.
  32923. * @return {Image} The image.
  32924. */
  32925. load( url, onLoad, onProgress, onError ) {
  32926. if ( this.path !== undefined ) url = this.path + url;
  32927. url = this.manager.resolveURL( url );
  32928. const scope = this;
  32929. const cached = Cache.get( `image:${url}` );
  32930. if ( cached !== undefined ) {
  32931. if ( cached.complete === true ) {
  32932. scope.manager.itemStart( url );
  32933. setTimeout( function () {
  32934. if ( onLoad ) onLoad( cached );
  32935. scope.manager.itemEnd( url );
  32936. }, 0 );
  32937. } else {
  32938. let arr = _loading.get( cached );
  32939. if ( arr === undefined ) {
  32940. arr = [];
  32941. _loading.set( cached, arr );
  32942. }
  32943. arr.push( { onLoad, onError } );
  32944. }
  32945. return cached;
  32946. }
  32947. const image = createElementNS( 'img' );
  32948. function onImageLoad() {
  32949. removeEventListeners();
  32950. if ( onLoad ) onLoad( this );
  32951. //
  32952. const callbacks = _loading.get( this ) || [];
  32953. for ( let i = 0; i < callbacks.length; i ++ ) {
  32954. const callback = callbacks[ i ];
  32955. if ( callback.onLoad ) callback.onLoad( this );
  32956. }
  32957. _loading.delete( this );
  32958. scope.manager.itemEnd( url );
  32959. }
  32960. function onImageError( event ) {
  32961. removeEventListeners();
  32962. if ( onError ) onError( event );
  32963. Cache.remove( `image:${url}` );
  32964. //
  32965. const callbacks = _loading.get( this ) || [];
  32966. for ( let i = 0; i < callbacks.length; i ++ ) {
  32967. const callback = callbacks[ i ];
  32968. if ( callback.onError ) callback.onError( event );
  32969. }
  32970. _loading.delete( this );
  32971. scope.manager.itemError( url );
  32972. scope.manager.itemEnd( url );
  32973. }
  32974. function removeEventListeners() {
  32975. image.removeEventListener( 'load', onImageLoad, false );
  32976. image.removeEventListener( 'error', onImageError, false );
  32977. }
  32978. image.addEventListener( 'load', onImageLoad, false );
  32979. image.addEventListener( 'error', onImageError, false );
  32980. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32981. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32982. }
  32983. Cache.add( `image:${url}`, image );
  32984. scope.manager.itemStart( url );
  32985. image.src = url;
  32986. return image;
  32987. }
  32988. }
  32989. /**
  32990. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32991. *
  32992. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32993. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32994. * like vertical and horizontal cross, column and row layouts are not supported.
  32995. *
  32996. * Note that, by convention, cube maps are specified in a coordinate system
  32997. * in which positive-x is to the right when looking up the positive-z axis --
  32998. * in other words, using a left-handed coordinate system. Since three.js uses
  32999. * a right-handed coordinate system, environment maps used in three.js will
  33000. * have pos-x and neg-x swapped.
  33001. *
  33002. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33003. * is set to `SRGBColorSpace` by default.
  33004. *
  33005. * ```js
  33006. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33007. * const cubeTexture = await loader.loadAsync( [
  33008. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33009. * ] );
  33010. * scene.background = cubeTexture;
  33011. * ```
  33012. *
  33013. * @augments Loader
  33014. */
  33015. class CubeTextureLoader extends Loader {
  33016. /**
  33017. * Constructs a new cube texture loader.
  33018. *
  33019. * @param {LoadingManager} [manager] - The loading manager.
  33020. */
  33021. constructor( manager ) {
  33022. super( manager );
  33023. }
  33024. /**
  33025. * Starts loading from the given URL and pass the fully loaded cube texture
  33026. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33027. * directly be used for material creation. If you do it this way, the cube texture
  33028. * may pop up in your scene once the respective loading process is finished.
  33029. *
  33030. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33031. * cube texture. The urls should be specified in the following order: pos-x,
  33032. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33033. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33034. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33035. * @param {onErrorCallback} onError - Executed when errors occur.
  33036. * @return {CubeTexture} The cube texture.
  33037. */
  33038. load( urls, onLoad, onProgress, onError ) {
  33039. const texture = new CubeTexture();
  33040. texture.colorSpace = SRGBColorSpace;
  33041. const loader = new ImageLoader( this.manager );
  33042. loader.setCrossOrigin( this.crossOrigin );
  33043. loader.setPath( this.path );
  33044. let loaded = 0;
  33045. function loadTexture( i ) {
  33046. loader.load( urls[ i ], function ( image ) {
  33047. texture.images[ i ] = image;
  33048. loaded ++;
  33049. if ( loaded === 6 ) {
  33050. texture.needsUpdate = true;
  33051. if ( onLoad ) onLoad( texture );
  33052. }
  33053. }, undefined, onError );
  33054. }
  33055. for ( let i = 0; i < urls.length; ++ i ) {
  33056. loadTexture( i );
  33057. }
  33058. return texture;
  33059. }
  33060. }
  33061. /**
  33062. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33063. * Textures are internally loaded via {@link FileLoader}.
  33064. *
  33065. * Derived classes have to implement the `parse()` method which holds the parsing
  33066. * for the respective format.
  33067. *
  33068. * @abstract
  33069. * @augments Loader
  33070. */
  33071. class DataTextureLoader extends Loader {
  33072. /**
  33073. * Constructs a new data texture loader.
  33074. *
  33075. * @param {LoadingManager} [manager] - The loading manager.
  33076. */
  33077. constructor( manager ) {
  33078. super( manager );
  33079. }
  33080. /**
  33081. * Starts loading from the given URL and passes the loaded data texture
  33082. * to the `onLoad()` callback. The method also returns a new texture object which can
  33083. * directly be used for material creation. If you do it this way, the texture
  33084. * may pop up in your scene once the respective loading process is finished.
  33085. *
  33086. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33087. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33088. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33089. * @param {onErrorCallback} onError - Executed when errors occur.
  33090. * @return {DataTexture} The data texture.
  33091. */
  33092. load( url, onLoad, onProgress, onError ) {
  33093. const scope = this;
  33094. const texture = new DataTexture();
  33095. const loader = new FileLoader( this.manager );
  33096. loader.setResponseType( 'arraybuffer' );
  33097. loader.setRequestHeader( this.requestHeader );
  33098. loader.setPath( this.path );
  33099. loader.setWithCredentials( scope.withCredentials );
  33100. loader.load( url, function ( buffer ) {
  33101. let texData;
  33102. try {
  33103. texData = scope.parse( buffer );
  33104. } catch ( error ) {
  33105. if ( onError !== undefined ) {
  33106. onError( error );
  33107. } else {
  33108. error( error );
  33109. return;
  33110. }
  33111. }
  33112. if ( texData.image !== undefined ) {
  33113. texture.image = texData.image;
  33114. } else if ( texData.data !== undefined ) {
  33115. texture.image.width = texData.width;
  33116. texture.image.height = texData.height;
  33117. texture.image.data = texData.data;
  33118. }
  33119. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33120. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33121. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33122. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33123. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33124. if ( texData.colorSpace !== undefined ) {
  33125. texture.colorSpace = texData.colorSpace;
  33126. }
  33127. if ( texData.flipY !== undefined ) {
  33128. texture.flipY = texData.flipY;
  33129. }
  33130. if ( texData.format !== undefined ) {
  33131. texture.format = texData.format;
  33132. }
  33133. if ( texData.type !== undefined ) {
  33134. texture.type = texData.type;
  33135. }
  33136. if ( texData.mipmaps !== undefined ) {
  33137. texture.mipmaps = texData.mipmaps;
  33138. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33139. }
  33140. if ( texData.mipmapCount === 1 ) {
  33141. texture.minFilter = LinearFilter;
  33142. }
  33143. if ( texData.generateMipmaps !== undefined ) {
  33144. texture.generateMipmaps = texData.generateMipmaps;
  33145. }
  33146. texture.needsUpdate = true;
  33147. if ( onLoad ) onLoad( texture, texData );
  33148. }, onProgress, onError );
  33149. return texture;
  33150. }
  33151. }
  33152. /**
  33153. * Class for loading textures. Images are internally
  33154. * loaded via {@link ImageLoader}.
  33155. *
  33156. * ```js
  33157. * const loader = new THREE.TextureLoader();
  33158. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33159. *
  33160. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33161. * ```
  33162. * Please note that `TextureLoader` has dropped support for progress
  33163. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33164. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33165. *
  33166. * @augments Loader
  33167. */
  33168. class TextureLoader extends Loader {
  33169. /**
  33170. * Constructs a new texture loader.
  33171. *
  33172. * @param {LoadingManager} [manager] - The loading manager.
  33173. */
  33174. constructor( manager ) {
  33175. super( manager );
  33176. }
  33177. /**
  33178. * Starts loading from the given URL and pass the fully loaded texture
  33179. * to the `onLoad()` callback. The method also returns a new texture object which can
  33180. * directly be used for material creation. If you do it this way, the texture
  33181. * may pop up in your scene once the respective loading process is finished.
  33182. *
  33183. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33184. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33185. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33186. * @param {onErrorCallback} onError - Executed when errors occur.
  33187. * @return {Texture} The texture.
  33188. */
  33189. load( url, onLoad, onProgress, onError ) {
  33190. const texture = new Texture();
  33191. const loader = new ImageLoader( this.manager );
  33192. loader.setCrossOrigin( this.crossOrigin );
  33193. loader.setPath( this.path );
  33194. loader.load( url, function ( image ) {
  33195. texture.image = image;
  33196. texture.needsUpdate = true;
  33197. if ( onLoad !== undefined ) {
  33198. onLoad( texture );
  33199. }
  33200. }, onProgress, onError );
  33201. return texture;
  33202. }
  33203. }
  33204. /**
  33205. * Abstract base class for lights - all other light types inherit the
  33206. * properties and methods described here.
  33207. *
  33208. * @abstract
  33209. * @augments Object3D
  33210. */
  33211. class Light extends Object3D {
  33212. /**
  33213. * Constructs a new light.
  33214. *
  33215. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33216. * @param {number} [intensity=1] - The light's strength/intensity.
  33217. */
  33218. constructor( color, intensity = 1 ) {
  33219. super();
  33220. /**
  33221. * This flag can be used for type testing.
  33222. *
  33223. * @type {boolean}
  33224. * @readonly
  33225. * @default true
  33226. */
  33227. this.isLight = true;
  33228. this.type = 'Light';
  33229. /**
  33230. * The light's color.
  33231. *
  33232. * @type {Color}
  33233. */
  33234. this.color = new Color( color );
  33235. /**
  33236. * The light's intensity.
  33237. *
  33238. * @type {number}
  33239. * @default 1
  33240. */
  33241. this.intensity = intensity;
  33242. }
  33243. /**
  33244. * Frees the GPU-related resources allocated by this instance. Call this
  33245. * method whenever this instance is no longer used in your app.
  33246. */
  33247. dispose() {
  33248. this.dispatchEvent( { type: 'dispose' } );
  33249. }
  33250. copy( source, recursive ) {
  33251. super.copy( source, recursive );
  33252. this.color.copy( source.color );
  33253. this.intensity = source.intensity;
  33254. return this;
  33255. }
  33256. toJSON( meta ) {
  33257. const data = super.toJSON( meta );
  33258. data.object.color = this.color.getHex();
  33259. data.object.intensity = this.intensity;
  33260. return data;
  33261. }
  33262. }
  33263. /**
  33264. * A light source positioned directly above the scene, with color fading from
  33265. * the sky color to the ground color.
  33266. *
  33267. * This light cannot be used to cast shadows.
  33268. *
  33269. * ```js
  33270. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33271. * scene.add( light );
  33272. * ```
  33273. *
  33274. * @augments Light
  33275. */
  33276. class HemisphereLight extends Light {
  33277. /**
  33278. * Constructs a new hemisphere light.
  33279. *
  33280. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33281. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33282. * @param {number} [intensity=1] - The light's strength/intensity.
  33283. */
  33284. constructor( skyColor, groundColor, intensity ) {
  33285. super( skyColor, intensity );
  33286. /**
  33287. * This flag can be used for type testing.
  33288. *
  33289. * @type {boolean}
  33290. * @readonly
  33291. * @default true
  33292. */
  33293. this.isHemisphereLight = true;
  33294. this.type = 'HemisphereLight';
  33295. this.position.copy( Object3D.DEFAULT_UP );
  33296. this.updateMatrix();
  33297. /**
  33298. * The light's ground color.
  33299. *
  33300. * @type {Color}
  33301. */
  33302. this.groundColor = new Color( groundColor );
  33303. }
  33304. copy( source, recursive ) {
  33305. super.copy( source, recursive );
  33306. this.groundColor.copy( source.groundColor );
  33307. return this;
  33308. }
  33309. toJSON( meta ) {
  33310. const data = super.toJSON( meta );
  33311. data.object.groundColor = this.groundColor.getHex();
  33312. return data;
  33313. }
  33314. }
  33315. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33316. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33317. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33318. /**
  33319. * Abstract base class for light shadow classes. These classes
  33320. * represent the shadow configuration for different light types.
  33321. *
  33322. * @abstract
  33323. */
  33324. class LightShadow {
  33325. /**
  33326. * Constructs a new light shadow.
  33327. *
  33328. * @param {Camera} camera - The light's view of the world.
  33329. */
  33330. constructor( camera ) {
  33331. /**
  33332. * The light's view of the world.
  33333. *
  33334. * @type {Camera}
  33335. */
  33336. this.camera = camera;
  33337. /**
  33338. * The intensity of the shadow. The default is `1`.
  33339. * Valid values are in the range `[0, 1]`.
  33340. *
  33341. * @type {number}
  33342. * @default 1
  33343. */
  33344. this.intensity = 1;
  33345. /**
  33346. * Shadow map bias, how much to add or subtract from the normalized depth
  33347. * when deciding whether a surface is in shadow.
  33348. *
  33349. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33350. * may help reduce artifacts in shadows.
  33351. *
  33352. * @type {number}
  33353. * @default 0
  33354. */
  33355. this.bias = 0;
  33356. /**
  33357. * Defines how much the position used to query the shadow map is offset along
  33358. * the object normal. The default is `0`. Increasing this value can be used to
  33359. * reduce shadow acne especially in large scenes where light shines onto
  33360. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33361. *
  33362. * @type {number}
  33363. * @default 0
  33364. */
  33365. this.normalBias = 0;
  33366. /**
  33367. * Setting this to values greater than 1 will blur the edges of the shadow.
  33368. * High values will cause unwanted banding effects in the shadows - a greater
  33369. * map size will allow for a higher value to be used here before these effects
  33370. * become visible.
  33371. *
  33372. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33373. *
  33374. * @type {number}
  33375. * @default 1
  33376. */
  33377. this.radius = 1;
  33378. /**
  33379. * The amount of samples to use when blurring a VSM shadow map.
  33380. *
  33381. * @type {number}
  33382. * @default 8
  33383. */
  33384. this.blurSamples = 8;
  33385. /**
  33386. * Defines the width and height of the shadow map. Higher values give better quality
  33387. * shadows at the cost of computation time. Values must be powers of two.
  33388. *
  33389. * @type {Vector2}
  33390. * @default (512,512)
  33391. */
  33392. this.mapSize = new Vector2( 512, 512 );
  33393. /**
  33394. * The type of shadow texture. The default is `UnsignedByteType`.
  33395. *
  33396. * @type {number}
  33397. * @default UnsignedByteType
  33398. */
  33399. this.mapType = UnsignedByteType;
  33400. /**
  33401. * The depth map generated using the internal camera; a location beyond a
  33402. * pixel's depth is in shadow. Computed internally during rendering.
  33403. *
  33404. * @type {?RenderTarget}
  33405. * @default null
  33406. */
  33407. this.map = null;
  33408. /**
  33409. * The distribution map generated using the internal camera; an occlusion is
  33410. * calculated based on the distribution of depths. Computed internally during
  33411. * rendering.
  33412. *
  33413. * @type {?RenderTarget}
  33414. * @default null
  33415. */
  33416. this.mapPass = null;
  33417. /**
  33418. * Model to shadow camera space, to compute location and depth in shadow map.
  33419. * This is computed internally during rendering.
  33420. *
  33421. * @type {Matrix4}
  33422. */
  33423. this.matrix = new Matrix4();
  33424. /**
  33425. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33426. * lighting / shadows, you may set this to `false`.
  33427. *
  33428. * @type {boolean}
  33429. * @default true
  33430. */
  33431. this.autoUpdate = true;
  33432. /**
  33433. * When set to `true`, shadow maps will be updated in the next `render` call.
  33434. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33435. * set this property to `true` and then make a render call to update the light's shadow.
  33436. *
  33437. * @type {boolean}
  33438. * @default false
  33439. */
  33440. this.needsUpdate = false;
  33441. this._frustum = new Frustum();
  33442. this._frameExtents = new Vector2( 1, 1 );
  33443. this._viewportCount = 1;
  33444. this._viewports = [
  33445. new Vector4( 0, 0, 1, 1 )
  33446. ];
  33447. }
  33448. /**
  33449. * Used internally by the renderer to get the number of viewports that need
  33450. * to be rendered for this shadow.
  33451. *
  33452. * @return {number} The viewport count.
  33453. */
  33454. getViewportCount() {
  33455. return this._viewportCount;
  33456. }
  33457. /**
  33458. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33459. *
  33460. * @return {Frustum} The shadow camera frustum.
  33461. */
  33462. getFrustum() {
  33463. return this._frustum;
  33464. }
  33465. /**
  33466. * Update the matrices for the camera and shadow, used internally by the renderer.
  33467. *
  33468. * @param {Light} light - The light for which the shadow is being rendered.
  33469. */
  33470. updateMatrices( light ) {
  33471. const shadowCamera = this.camera;
  33472. const shadowMatrix = this.matrix;
  33473. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33474. shadowCamera.position.copy( _lightPositionWorld$1 );
  33475. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33476. shadowCamera.lookAt( _lookTarget$1 );
  33477. shadowCamera.updateMatrixWorld();
  33478. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33479. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33480. if ( shadowCamera.reversedDepth ) {
  33481. shadowMatrix.set(
  33482. 0.5, 0.0, 0.0, 0.5,
  33483. 0.0, 0.5, 0.0, 0.5,
  33484. 0.0, 0.0, 1.0, 0.0,
  33485. 0.0, 0.0, 0.0, 1.0
  33486. );
  33487. } else {
  33488. shadowMatrix.set(
  33489. 0.5, 0.0, 0.0, 0.5,
  33490. 0.0, 0.5, 0.0, 0.5,
  33491. 0.0, 0.0, 0.5, 0.5,
  33492. 0.0, 0.0, 0.0, 1.0
  33493. );
  33494. }
  33495. shadowMatrix.multiply( _projScreenMatrix$1 );
  33496. }
  33497. /**
  33498. * Returns a viewport definition for the given viewport index.
  33499. *
  33500. * @param {number} viewportIndex - The viewport index.
  33501. * @return {Vector4} The viewport.
  33502. */
  33503. getViewport( viewportIndex ) {
  33504. return this._viewports[ viewportIndex ];
  33505. }
  33506. /**
  33507. * Returns the frame extends.
  33508. *
  33509. * @return {Vector2} The frame extends.
  33510. */
  33511. getFrameExtents() {
  33512. return this._frameExtents;
  33513. }
  33514. /**
  33515. * Frees the GPU-related resources allocated by this instance. Call this
  33516. * method whenever this instance is no longer used in your app.
  33517. */
  33518. dispose() {
  33519. if ( this.map ) {
  33520. this.map.dispose();
  33521. }
  33522. if ( this.mapPass ) {
  33523. this.mapPass.dispose();
  33524. }
  33525. }
  33526. /**
  33527. * Copies the values of the given light shadow instance to this instance.
  33528. *
  33529. * @param {LightShadow} source - The light shadow to copy.
  33530. * @return {LightShadow} A reference to this light shadow instance.
  33531. */
  33532. copy( source ) {
  33533. this.camera = source.camera.clone();
  33534. this.intensity = source.intensity;
  33535. this.bias = source.bias;
  33536. this.radius = source.radius;
  33537. this.autoUpdate = source.autoUpdate;
  33538. this.needsUpdate = source.needsUpdate;
  33539. this.normalBias = source.normalBias;
  33540. this.blurSamples = source.blurSamples;
  33541. this.mapSize.copy( source.mapSize );
  33542. return this;
  33543. }
  33544. /**
  33545. * Returns a new light shadow instance with copied values from this instance.
  33546. *
  33547. * @return {LightShadow} A clone of this instance.
  33548. */
  33549. clone() {
  33550. return new this.constructor().copy( this );
  33551. }
  33552. /**
  33553. * Serializes the light shadow into JSON.
  33554. *
  33555. * @return {Object} A JSON object representing the serialized light shadow.
  33556. * @see {@link ObjectLoader#parse}
  33557. */
  33558. toJSON() {
  33559. const object = {};
  33560. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33561. if ( this.bias !== 0 ) object.bias = this.bias;
  33562. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33563. if ( this.radius !== 1 ) object.radius = this.radius;
  33564. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33565. object.camera = this.camera.toJSON( false ).object;
  33566. delete object.camera.matrix;
  33567. return object;
  33568. }
  33569. }
  33570. /**
  33571. * Represents the shadow configuration of directional lights.
  33572. *
  33573. * @augments LightShadow
  33574. */
  33575. class SpotLightShadow extends LightShadow {
  33576. /**
  33577. * Constructs a new spot light shadow.
  33578. */
  33579. constructor() {
  33580. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33581. /**
  33582. * This flag can be used for type testing.
  33583. *
  33584. * @type {boolean}
  33585. * @readonly
  33586. * @default true
  33587. */
  33588. this.isSpotLightShadow = true;
  33589. /**
  33590. * Used to focus the shadow camera. The camera's field of view is set as a
  33591. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33592. *
  33593. * @type {number}
  33594. * @default 1
  33595. */
  33596. this.focus = 1;
  33597. /**
  33598. * Texture aspect ratio.
  33599. *
  33600. * @type {number}
  33601. * @default 1
  33602. */
  33603. this.aspect = 1;
  33604. }
  33605. updateMatrices( light ) {
  33606. const camera = this.camera;
  33607. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33608. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33609. const far = light.distance || camera.far;
  33610. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33611. camera.fov = fov;
  33612. camera.aspect = aspect;
  33613. camera.far = far;
  33614. camera.updateProjectionMatrix();
  33615. }
  33616. super.updateMatrices( light );
  33617. }
  33618. copy( source ) {
  33619. super.copy( source );
  33620. this.focus = source.focus;
  33621. return this;
  33622. }
  33623. }
  33624. /**
  33625. * This light gets emitted from a single point in one direction, along a cone
  33626. * that increases in size the further from the light it gets.
  33627. *
  33628. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33629. *
  33630. * ```js
  33631. * // white spotlight shining from the side, modulated by a texture
  33632. * const spotLight = new THREE.SpotLight( 0xffffff );
  33633. * spotLight.position.set( 100, 1000, 100 );
  33634. * spotLight.map = new THREE.TextureLoader().load( url );
  33635. *
  33636. * spotLight.castShadow = true;
  33637. * spotLight.shadow.mapSize.width = 1024;
  33638. * spotLight.shadow.mapSize.height = 1024;
  33639. * spotLight.shadow.camera.near = 500;
  33640. * spotLight.shadow.camera.far = 4000;
  33641. * spotLight.shadow.camera.fov = 30;s
  33642. * ```
  33643. *
  33644. * @augments Light
  33645. */
  33646. class SpotLight extends Light {
  33647. /**
  33648. * Constructs a new spot light.
  33649. *
  33650. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33651. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33652. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33653. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33654. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33655. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33656. */
  33657. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33658. super( color, intensity );
  33659. /**
  33660. * This flag can be used for type testing.
  33661. *
  33662. * @type {boolean}
  33663. * @readonly
  33664. * @default true
  33665. */
  33666. this.isSpotLight = true;
  33667. this.type = 'SpotLight';
  33668. this.position.copy( Object3D.DEFAULT_UP );
  33669. this.updateMatrix();
  33670. /**
  33671. * The spot light points from its position to the
  33672. * target's position.
  33673. *
  33674. * For the target's position to be changed to anything other
  33675. * than the default, it must be added to the scene.
  33676. *
  33677. * It is also possible to set the target to be another 3D object
  33678. * in the scene. The light will now track the target object.
  33679. *
  33680. * @type {Object3D}
  33681. */
  33682. this.target = new Object3D();
  33683. /**
  33684. * Maximum range of the light. `0` means no limit.
  33685. *
  33686. * @type {number}
  33687. * @default 0
  33688. */
  33689. this.distance = distance;
  33690. /**
  33691. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33692. *
  33693. * @type {number}
  33694. * @default Math.PI/3
  33695. */
  33696. this.angle = angle;
  33697. /**
  33698. * Percent of the spotlight cone that is attenuated due to penumbra.
  33699. * Value range is `[0,1]`.
  33700. *
  33701. * @type {number}
  33702. * @default 0
  33703. */
  33704. this.penumbra = penumbra;
  33705. /**
  33706. * The amount the light dims along the distance of the light. In context of
  33707. * physically-correct rendering the default value should not be changed.
  33708. *
  33709. * @type {number}
  33710. * @default 2
  33711. */
  33712. this.decay = decay;
  33713. /**
  33714. * A texture used to modulate the color of the light. The spot light
  33715. * color is mixed with the RGB value of this texture, with a ratio
  33716. * corresponding to its alpha value. The cookie-like masking effect is
  33717. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33718. *
  33719. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33720. *
  33721. * @type {?Texture}
  33722. * @default null
  33723. */
  33724. this.map = null;
  33725. /**
  33726. * This property holds the light's shadow configuration.
  33727. *
  33728. * @type {SpotLightShadow}
  33729. */
  33730. this.shadow = new SpotLightShadow();
  33731. }
  33732. /**
  33733. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33734. * Changing the power will also change the light's intensity.
  33735. *
  33736. * @type {number}
  33737. */
  33738. get power() {
  33739. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33740. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33741. return this.intensity * Math.PI;
  33742. }
  33743. set power( power ) {
  33744. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33745. this.intensity = power / Math.PI;
  33746. }
  33747. dispose() {
  33748. super.dispose();
  33749. this.shadow.dispose();
  33750. }
  33751. copy( source, recursive ) {
  33752. super.copy( source, recursive );
  33753. this.distance = source.distance;
  33754. this.angle = source.angle;
  33755. this.penumbra = source.penumbra;
  33756. this.decay = source.decay;
  33757. this.target = source.target.clone();
  33758. this.map = source.map;
  33759. this.shadow = source.shadow.clone();
  33760. return this;
  33761. }
  33762. toJSON( meta ) {
  33763. const data = super.toJSON( meta );
  33764. data.object.distance = this.distance;
  33765. data.object.angle = this.angle;
  33766. data.object.decay = this.decay;
  33767. data.object.penumbra = this.penumbra;
  33768. data.object.target = this.target.uuid;
  33769. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33770. data.object.shadow = this.shadow.toJSON();
  33771. return data;
  33772. }
  33773. }
  33774. /**
  33775. * Represents the shadow configuration of point lights.
  33776. *
  33777. * @augments LightShadow
  33778. */
  33779. class PointLightShadow extends LightShadow {
  33780. /**
  33781. * Constructs a new point light shadow.
  33782. */
  33783. constructor() {
  33784. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33785. /**
  33786. * This flag can be used for type testing.
  33787. *
  33788. * @type {boolean}
  33789. * @readonly
  33790. * @default true
  33791. */
  33792. this.isPointLightShadow = true;
  33793. }
  33794. }
  33795. /**
  33796. * A light that gets emitted from a single point in all directions. A common
  33797. * use case for this is to replicate the light emitted from a bare
  33798. * lightbulb.
  33799. *
  33800. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33801. *
  33802. * ```js
  33803. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33804. * light.position.set( 50, 50, 50 );
  33805. * scene.add( light );
  33806. * ```
  33807. *
  33808. * @augments Light
  33809. */
  33810. class PointLight extends Light {
  33811. /**
  33812. * Constructs a new point light.
  33813. *
  33814. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33815. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33816. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33817. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33818. */
  33819. constructor( color, intensity, distance = 0, decay = 2 ) {
  33820. super( color, intensity );
  33821. /**
  33822. * This flag can be used for type testing.
  33823. *
  33824. * @type {boolean}
  33825. * @readonly
  33826. * @default true
  33827. */
  33828. this.isPointLight = true;
  33829. this.type = 'PointLight';
  33830. /**
  33831. * When distance is zero, light will attenuate according to inverse-square
  33832. * law to infinite distance. When distance is non-zero, light will attenuate
  33833. * according to inverse-square law until near the distance cutoff, where it
  33834. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33835. * physically correct.
  33836. *
  33837. * @type {number}
  33838. * @default 0
  33839. */
  33840. this.distance = distance;
  33841. /**
  33842. * The amount the light dims along the distance of the light. In context of
  33843. * physically-correct rendering the default value should not be changed.
  33844. *
  33845. * @type {number}
  33846. * @default 2
  33847. */
  33848. this.decay = decay;
  33849. /**
  33850. * This property holds the light's shadow configuration.
  33851. *
  33852. * @type {PointLightShadow}
  33853. */
  33854. this.shadow = new PointLightShadow();
  33855. }
  33856. /**
  33857. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33858. * Changing the power will also change the light's intensity.
  33859. *
  33860. * @type {number}
  33861. */
  33862. get power() {
  33863. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33864. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33865. return this.intensity * 4 * Math.PI;
  33866. }
  33867. set power( power ) {
  33868. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33869. this.intensity = power / ( 4 * Math.PI );
  33870. }
  33871. dispose() {
  33872. super.dispose();
  33873. this.shadow.dispose();
  33874. }
  33875. copy( source, recursive ) {
  33876. super.copy( source, recursive );
  33877. this.distance = source.distance;
  33878. this.decay = source.decay;
  33879. this.shadow = source.shadow.clone();
  33880. return this;
  33881. }
  33882. toJSON( meta ) {
  33883. const data = super.toJSON( meta );
  33884. data.object.distance = this.distance;
  33885. data.object.decay = this.decay;
  33886. data.object.shadow = this.shadow.toJSON();
  33887. return data;
  33888. }
  33889. }
  33890. /**
  33891. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33892. *
  33893. * In this projection mode, an object's size in the rendered image stays
  33894. * constant regardless of its distance from the camera. This can be useful
  33895. * for rendering 2D scenes and UI elements, amongst other things.
  33896. *
  33897. * ```js
  33898. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33899. * scene.add( camera );
  33900. * ```
  33901. *
  33902. * @augments Camera
  33903. */
  33904. class OrthographicCamera extends Camera {
  33905. /**
  33906. * Constructs a new orthographic camera.
  33907. *
  33908. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33909. * @param {number} [right=1] - The right plane of the camera's frustum.
  33910. * @param {number} [top=1] - The top plane of the camera's frustum.
  33911. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33912. * @param {number} [near=0.1] - The camera's near plane.
  33913. * @param {number} [far=2000] - The camera's far plane.
  33914. */
  33915. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33916. super();
  33917. /**
  33918. * This flag can be used for type testing.
  33919. *
  33920. * @type {boolean}
  33921. * @readonly
  33922. * @default true
  33923. */
  33924. this.isOrthographicCamera = true;
  33925. this.type = 'OrthographicCamera';
  33926. /**
  33927. * The zoom factor of the camera.
  33928. *
  33929. * @type {number}
  33930. * @default 1
  33931. */
  33932. this.zoom = 1;
  33933. /**
  33934. * Represents the frustum window specification. This property should not be edited
  33935. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33936. *
  33937. * @type {?Object}
  33938. * @default null
  33939. */
  33940. this.view = null;
  33941. /**
  33942. * The left plane of the camera's frustum.
  33943. *
  33944. * @type {number}
  33945. * @default -1
  33946. */
  33947. this.left = left;
  33948. /**
  33949. * The right plane of the camera's frustum.
  33950. *
  33951. * @type {number}
  33952. * @default 1
  33953. */
  33954. this.right = right;
  33955. /**
  33956. * The top plane of the camera's frustum.
  33957. *
  33958. * @type {number}
  33959. * @default 1
  33960. */
  33961. this.top = top;
  33962. /**
  33963. * The bottom plane of the camera's frustum.
  33964. *
  33965. * @type {number}
  33966. * @default -1
  33967. */
  33968. this.bottom = bottom;
  33969. /**
  33970. * The camera's near plane. The valid range is greater than `0`
  33971. * and less than the current value of {@link OrthographicCamera#far}.
  33972. *
  33973. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33974. * valid value for an orthographic camera's near plane.
  33975. *
  33976. * @type {number}
  33977. * @default 0.1
  33978. */
  33979. this.near = near;
  33980. /**
  33981. * The camera's far plane. Must be greater than the
  33982. * current value of {@link OrthographicCamera#near}.
  33983. *
  33984. * @type {number}
  33985. * @default 2000
  33986. */
  33987. this.far = far;
  33988. this.updateProjectionMatrix();
  33989. }
  33990. copy( source, recursive ) {
  33991. super.copy( source, recursive );
  33992. this.left = source.left;
  33993. this.right = source.right;
  33994. this.top = source.top;
  33995. this.bottom = source.bottom;
  33996. this.near = source.near;
  33997. this.far = source.far;
  33998. this.zoom = source.zoom;
  33999. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34000. return this;
  34001. }
  34002. /**
  34003. * Sets an offset in a larger frustum. This is useful for multi-window or
  34004. * multi-monitor/multi-machine setups.
  34005. *
  34006. * @param {number} fullWidth - The full width of multiview setup.
  34007. * @param {number} fullHeight - The full height of multiview setup.
  34008. * @param {number} x - The horizontal offset of the subcamera.
  34009. * @param {number} y - The vertical offset of the subcamera.
  34010. * @param {number} width - The width of subcamera.
  34011. * @param {number} height - The height of subcamera.
  34012. * @see {@link PerspectiveCamera#setViewOffset}
  34013. */
  34014. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34015. if ( this.view === null ) {
  34016. this.view = {
  34017. enabled: true,
  34018. fullWidth: 1,
  34019. fullHeight: 1,
  34020. offsetX: 0,
  34021. offsetY: 0,
  34022. width: 1,
  34023. height: 1
  34024. };
  34025. }
  34026. this.view.enabled = true;
  34027. this.view.fullWidth = fullWidth;
  34028. this.view.fullHeight = fullHeight;
  34029. this.view.offsetX = x;
  34030. this.view.offsetY = y;
  34031. this.view.width = width;
  34032. this.view.height = height;
  34033. this.updateProjectionMatrix();
  34034. }
  34035. /**
  34036. * Removes the view offset from the projection matrix.
  34037. */
  34038. clearViewOffset() {
  34039. if ( this.view !== null ) {
  34040. this.view.enabled = false;
  34041. }
  34042. this.updateProjectionMatrix();
  34043. }
  34044. /**
  34045. * Updates the camera's projection matrix. Must be called after any change of
  34046. * camera properties.
  34047. */
  34048. updateProjectionMatrix() {
  34049. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34050. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34051. const cx = ( this.right + this.left ) / 2;
  34052. const cy = ( this.top + this.bottom ) / 2;
  34053. let left = cx - dx;
  34054. let right = cx + dx;
  34055. let top = cy + dy;
  34056. let bottom = cy - dy;
  34057. if ( this.view !== null && this.view.enabled ) {
  34058. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34059. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34060. left += scaleW * this.view.offsetX;
  34061. right = left + scaleW * this.view.width;
  34062. top -= scaleH * this.view.offsetY;
  34063. bottom = top - scaleH * this.view.height;
  34064. }
  34065. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34066. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34067. }
  34068. toJSON( meta ) {
  34069. const data = super.toJSON( meta );
  34070. data.object.zoom = this.zoom;
  34071. data.object.left = this.left;
  34072. data.object.right = this.right;
  34073. data.object.top = this.top;
  34074. data.object.bottom = this.bottom;
  34075. data.object.near = this.near;
  34076. data.object.far = this.far;
  34077. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34078. return data;
  34079. }
  34080. }
  34081. /**
  34082. * Represents the shadow configuration of directional lights.
  34083. *
  34084. * @augments LightShadow
  34085. */
  34086. class DirectionalLightShadow extends LightShadow {
  34087. /**
  34088. * Constructs a new directional light shadow.
  34089. */
  34090. constructor() {
  34091. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34092. /**
  34093. * This flag can be used for type testing.
  34094. *
  34095. * @type {boolean}
  34096. * @readonly
  34097. * @default true
  34098. */
  34099. this.isDirectionalLightShadow = true;
  34100. }
  34101. }
  34102. /**
  34103. * A light that gets emitted in a specific direction. This light will behave
  34104. * as though it is infinitely far away and the rays produced from it are all
  34105. * parallel. The common use case for this is to simulate daylight; the sun is
  34106. * far enough away that its position can be considered to be infinite, and
  34107. * all light rays coming from it are parallel.
  34108. *
  34109. * A common point of confusion for directional lights is that setting the
  34110. * rotation has no effect. This is because three.js's DirectionalLight is the
  34111. * equivalent to what is often called a 'Target Direct Light' in other
  34112. * applications.
  34113. *
  34114. * This means that its direction is calculated as pointing from the light's
  34115. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34116. * (as opposed to a 'Free Direct Light' that just has a rotation
  34117. * component).
  34118. *
  34119. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34120. *
  34121. * ```js
  34122. * // White directional light at half intensity shining from the top.
  34123. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34124. * scene.add( directionalLight );
  34125. * ```
  34126. *
  34127. * @augments Light
  34128. */
  34129. class DirectionalLight extends Light {
  34130. /**
  34131. * Constructs a new directional light.
  34132. *
  34133. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34134. * @param {number} [intensity=1] - The light's strength/intensity.
  34135. */
  34136. constructor( color, intensity ) {
  34137. super( color, intensity );
  34138. /**
  34139. * This flag can be used for type testing.
  34140. *
  34141. * @type {boolean}
  34142. * @readonly
  34143. * @default true
  34144. */
  34145. this.isDirectionalLight = true;
  34146. this.type = 'DirectionalLight';
  34147. this.position.copy( Object3D.DEFAULT_UP );
  34148. this.updateMatrix();
  34149. /**
  34150. * The directional light points from its position to the
  34151. * target's position.
  34152. *
  34153. * For the target's position to be changed to anything other
  34154. * than the default, it must be added to the scene.
  34155. *
  34156. * It is also possible to set the target to be another 3D object
  34157. * in the scene. The light will now track the target object.
  34158. *
  34159. * @type {Object3D}
  34160. */
  34161. this.target = new Object3D();
  34162. /**
  34163. * This property holds the light's shadow configuration.
  34164. *
  34165. * @type {DirectionalLightShadow}
  34166. */
  34167. this.shadow = new DirectionalLightShadow();
  34168. }
  34169. dispose() {
  34170. super.dispose();
  34171. this.shadow.dispose();
  34172. }
  34173. copy( source ) {
  34174. super.copy( source );
  34175. this.target = source.target.clone();
  34176. this.shadow = source.shadow.clone();
  34177. return this;
  34178. }
  34179. toJSON( meta ) {
  34180. const data = super.toJSON( meta );
  34181. data.object.shadow = this.shadow.toJSON();
  34182. data.object.target = this.target.uuid;
  34183. return data;
  34184. }
  34185. }
  34186. /**
  34187. * This light globally illuminates all objects in the scene equally.
  34188. *
  34189. * It cannot be used to cast shadows as it does not have a direction.
  34190. *
  34191. * ```js
  34192. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34193. * scene.add( light );
  34194. * ```
  34195. *
  34196. * @augments Light
  34197. */
  34198. class AmbientLight extends Light {
  34199. /**
  34200. * Constructs a new ambient light.
  34201. *
  34202. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34203. * @param {number} [intensity=1] - The light's strength/intensity.
  34204. */
  34205. constructor( color, intensity ) {
  34206. super( color, intensity );
  34207. /**
  34208. * This flag can be used for type testing.
  34209. *
  34210. * @type {boolean}
  34211. * @readonly
  34212. * @default true
  34213. */
  34214. this.isAmbientLight = true;
  34215. this.type = 'AmbientLight';
  34216. }
  34217. }
  34218. /**
  34219. * This class emits light uniformly across the face a rectangular plane.
  34220. * This light type can be used to simulate light sources such as bright
  34221. * windows or strip lighting.
  34222. *
  34223. * Important Notes:
  34224. *
  34225. * - There is no shadow support.
  34226. * - Only PBR materials are supported.
  34227. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34228. * into your app and init the uniforms/textures.
  34229. *
  34230. * ```js
  34231. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34232. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34233. *
  34234. * const intensity = 1; const width = 10; const height = 10;
  34235. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34236. * rectLight.position.set( 5, 5, 0 );
  34237. * rectLight.lookAt( 0, 0, 0 );
  34238. * scene.add( rectLight )
  34239. * ```
  34240. *
  34241. * @augments Light
  34242. */
  34243. class RectAreaLight extends Light {
  34244. /**
  34245. * Constructs a new area light.
  34246. *
  34247. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34248. * @param {number} [intensity=1] - The light's strength/intensity.
  34249. * @param {number} [width=10] - The width of the light.
  34250. * @param {number} [height=10] - The height of the light.
  34251. */
  34252. constructor( color, intensity, width = 10, height = 10 ) {
  34253. super( color, intensity );
  34254. /**
  34255. * This flag can be used for type testing.
  34256. *
  34257. * @type {boolean}
  34258. * @readonly
  34259. * @default true
  34260. */
  34261. this.isRectAreaLight = true;
  34262. this.type = 'RectAreaLight';
  34263. /**
  34264. * The width of the light.
  34265. *
  34266. * @type {number}
  34267. * @default 10
  34268. */
  34269. this.width = width;
  34270. /**
  34271. * The height of the light.
  34272. *
  34273. * @type {number}
  34274. * @default 10
  34275. */
  34276. this.height = height;
  34277. }
  34278. /**
  34279. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34280. * Changing the power will also change the light's intensity.
  34281. *
  34282. * @type {number}
  34283. */
  34284. get power() {
  34285. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34286. return this.intensity * this.width * this.height * Math.PI;
  34287. }
  34288. set power( power ) {
  34289. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34290. this.intensity = power / ( this.width * this.height * Math.PI );
  34291. }
  34292. copy( source ) {
  34293. super.copy( source );
  34294. this.width = source.width;
  34295. this.height = source.height;
  34296. return this;
  34297. }
  34298. toJSON( meta ) {
  34299. const data = super.toJSON( meta );
  34300. data.object.width = this.width;
  34301. data.object.height = this.height;
  34302. return data;
  34303. }
  34304. }
  34305. /**
  34306. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34307. * to encode lighting information.
  34308. *
  34309. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34310. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34311. */
  34312. class SphericalHarmonics3 {
  34313. /**
  34314. * Constructs a new spherical harmonics.
  34315. */
  34316. constructor() {
  34317. /**
  34318. * This flag can be used for type testing.
  34319. *
  34320. * @type {boolean}
  34321. * @readonly
  34322. * @default true
  34323. */
  34324. this.isSphericalHarmonics3 = true;
  34325. /**
  34326. * An array holding the (9) SH coefficients.
  34327. *
  34328. * @type {Array<Vector3>}
  34329. */
  34330. this.coefficients = [];
  34331. for ( let i = 0; i < 9; i ++ ) {
  34332. this.coefficients.push( new Vector3() );
  34333. }
  34334. }
  34335. /**
  34336. * Sets the given SH coefficients to this instance by copying
  34337. * the values.
  34338. *
  34339. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34340. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34341. */
  34342. set( coefficients ) {
  34343. for ( let i = 0; i < 9; i ++ ) {
  34344. this.coefficients[ i ].copy( coefficients[ i ] );
  34345. }
  34346. return this;
  34347. }
  34348. /**
  34349. * Sets all SH coefficients to `0`.
  34350. *
  34351. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34352. */
  34353. zero() {
  34354. for ( let i = 0; i < 9; i ++ ) {
  34355. this.coefficients[ i ].set( 0, 0, 0 );
  34356. }
  34357. return this;
  34358. }
  34359. /**
  34360. * Returns the radiance in the direction of the given normal.
  34361. *
  34362. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34363. * @param {Vector3} target - The target vector that is used to store the method's result.
  34364. * @return {Vector3} The radiance.
  34365. */
  34366. getAt( normal, target ) {
  34367. // normal is assumed to be unit length
  34368. const x = normal.x, y = normal.y, z = normal.z;
  34369. const coeff = this.coefficients;
  34370. // band 0
  34371. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34372. // band 1
  34373. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34374. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34375. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34376. // band 2
  34377. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34378. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34379. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34380. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34381. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34382. return target;
  34383. }
  34384. /**
  34385. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34386. * direction of the given normal.
  34387. *
  34388. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34389. * @param {Vector3} target - The target vector that is used to store the method's result.
  34390. * @return {Vector3} The irradiance.
  34391. */
  34392. getIrradianceAt( normal, target ) {
  34393. // normal is assumed to be unit length
  34394. const x = normal.x, y = normal.y, z = normal.z;
  34395. const coeff = this.coefficients;
  34396. // band 0
  34397. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34398. // band 1
  34399. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34400. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34401. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34402. // band 2
  34403. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34404. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34405. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34406. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34407. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34408. return target;
  34409. }
  34410. /**
  34411. * Adds the given SH to this instance.
  34412. *
  34413. * @param {SphericalHarmonics3} sh - The SH to add.
  34414. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34415. */
  34416. add( sh ) {
  34417. for ( let i = 0; i < 9; i ++ ) {
  34418. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34419. }
  34420. return this;
  34421. }
  34422. /**
  34423. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34424. * {@link SphericalHarmonics3#scale} at once.
  34425. *
  34426. * @param {SphericalHarmonics3} sh - The SH to add.
  34427. * @param {number} s - The scale factor.
  34428. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34429. */
  34430. addScaledSH( sh, s ) {
  34431. for ( let i = 0; i < 9; i ++ ) {
  34432. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34433. }
  34434. return this;
  34435. }
  34436. /**
  34437. * Scales this SH by the given scale factor.
  34438. *
  34439. * @param {number} s - The scale factor.
  34440. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34441. */
  34442. scale( s ) {
  34443. for ( let i = 0; i < 9; i ++ ) {
  34444. this.coefficients[ i ].multiplyScalar( s );
  34445. }
  34446. return this;
  34447. }
  34448. /**
  34449. * Linear interpolates between the given SH and this instance by the given
  34450. * alpha factor.
  34451. *
  34452. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34453. * @param {number} alpha - The alpha factor.
  34454. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34455. */
  34456. lerp( sh, alpha ) {
  34457. for ( let i = 0; i < 9; i ++ ) {
  34458. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34459. }
  34460. return this;
  34461. }
  34462. /**
  34463. * Returns `true` if this spherical harmonics is equal with the given one.
  34464. *
  34465. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34466. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34467. */
  34468. equals( sh ) {
  34469. for ( let i = 0; i < 9; i ++ ) {
  34470. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34471. return false;
  34472. }
  34473. }
  34474. return true;
  34475. }
  34476. /**
  34477. * Copies the values of the given spherical harmonics to this instance.
  34478. *
  34479. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34480. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34481. */
  34482. copy( sh ) {
  34483. return this.set( sh.coefficients );
  34484. }
  34485. /**
  34486. * Returns a new spherical harmonics with copied values from this instance.
  34487. *
  34488. * @return {SphericalHarmonics3} A clone of this instance.
  34489. */
  34490. clone() {
  34491. return new this.constructor().copy( this );
  34492. }
  34493. /**
  34494. * Sets the SH coefficients of this instance from the given array.
  34495. *
  34496. * @param {Array<number>} array - An array holding the SH coefficients.
  34497. * @param {number} [offset=0] - The array offset where to start copying.
  34498. * @return {SphericalHarmonics3} A clone of this instance.
  34499. */
  34500. fromArray( array, offset = 0 ) {
  34501. const coefficients = this.coefficients;
  34502. for ( let i = 0; i < 9; i ++ ) {
  34503. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34504. }
  34505. return this;
  34506. }
  34507. /**
  34508. * Returns an array with the SH coefficients, or copies them into the provided
  34509. * array. The coefficients are represented as numbers.
  34510. *
  34511. * @param {Array<number>} [array=[]] - The target array.
  34512. * @param {number} [offset=0] - The array offset where to start copying.
  34513. * @return {Array<number>} An array with flat SH coefficients.
  34514. */
  34515. toArray( array = [], offset = 0 ) {
  34516. const coefficients = this.coefficients;
  34517. for ( let i = 0; i < 9; i ++ ) {
  34518. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34519. }
  34520. return array;
  34521. }
  34522. /**
  34523. * Computes the SH basis for the given normal vector.
  34524. *
  34525. * @param {Vector3} normal - The normal.
  34526. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34527. */
  34528. static getBasisAt( normal, shBasis ) {
  34529. // normal is assumed to be unit length
  34530. const x = normal.x, y = normal.y, z = normal.z;
  34531. // band 0
  34532. shBasis[ 0 ] = 0.282095;
  34533. // band 1
  34534. shBasis[ 1 ] = 0.488603 * y;
  34535. shBasis[ 2 ] = 0.488603 * z;
  34536. shBasis[ 3 ] = 0.488603 * x;
  34537. // band 2
  34538. shBasis[ 4 ] = 1.092548 * x * y;
  34539. shBasis[ 5 ] = 1.092548 * y * z;
  34540. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34541. shBasis[ 7 ] = 1.092548 * x * z;
  34542. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34543. }
  34544. }
  34545. /**
  34546. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34547. * classical light sources (e.g. directional, point or spot lights), light
  34548. * probes do not emit light. Instead they store information about light
  34549. * passing through 3D space. During rendering, the light that hits a 3D
  34550. * object is approximated by using the data from the light probe.
  34551. *
  34552. * Light probes are usually created from (radiance) environment maps. The
  34553. * class {@link LightProbeGenerator} can be used to create light probes from
  34554. * cube textures or render targets. However, light estimation data could also
  34555. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34556. * augmented reality content that reacts to real world lighting.
  34557. *
  34558. * The current probe implementation in three.js supports so-called diffuse
  34559. * light probes. This type of light probe is functionally equivalent to an
  34560. * irradiance environment map.
  34561. *
  34562. * @augments Light
  34563. */
  34564. class LightProbe extends Light {
  34565. /**
  34566. * Constructs a new light probe.
  34567. *
  34568. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34569. * @param {number} [intensity=1] - The light's strength/intensity.
  34570. */
  34571. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34572. super( undefined, intensity );
  34573. /**
  34574. * This flag can be used for type testing.
  34575. *
  34576. * @type {boolean}
  34577. * @readonly
  34578. * @default true
  34579. */
  34580. this.isLightProbe = true;
  34581. /**
  34582. * A light probe uses spherical harmonics to encode lighting information.
  34583. *
  34584. * @type {SphericalHarmonics3}
  34585. */
  34586. this.sh = sh;
  34587. }
  34588. copy( source ) {
  34589. super.copy( source );
  34590. this.sh.copy( source.sh );
  34591. return this;
  34592. }
  34593. toJSON( meta ) {
  34594. const data = super.toJSON( meta );
  34595. data.object.sh = this.sh.toArray();
  34596. return data;
  34597. }
  34598. }
  34599. /**
  34600. * Class for loading materials. The files are internally
  34601. * loaded via {@link FileLoader}.
  34602. *
  34603. * ```js
  34604. * const loader = new THREE.MaterialLoader();
  34605. * const material = await loader.loadAsync( 'material.json' );
  34606. * ```
  34607. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34608. *
  34609. * @augments Loader
  34610. */
  34611. class MaterialLoader extends Loader {
  34612. /**
  34613. * Constructs a new material loader.
  34614. *
  34615. * @param {LoadingManager} [manager] - The loading manager.
  34616. */
  34617. constructor( manager ) {
  34618. super( manager );
  34619. /**
  34620. * A dictionary holding textures used by the material.
  34621. *
  34622. * @type {Object<string,Texture>}
  34623. */
  34624. this.textures = {};
  34625. }
  34626. /**
  34627. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34628. *
  34629. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34630. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34631. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34632. * @param {onErrorCallback} onError - Executed when errors occur.
  34633. */
  34634. load( url, onLoad, onProgress, onError ) {
  34635. const scope = this;
  34636. const loader = new FileLoader( scope.manager );
  34637. loader.setPath( scope.path );
  34638. loader.setRequestHeader( scope.requestHeader );
  34639. loader.setWithCredentials( scope.withCredentials );
  34640. loader.load( url, function ( text ) {
  34641. try {
  34642. onLoad( scope.parse( JSON.parse( text ) ) );
  34643. } catch ( e ) {
  34644. if ( onError ) {
  34645. onError( e );
  34646. } else {
  34647. error( e );
  34648. }
  34649. scope.manager.itemError( url );
  34650. }
  34651. }, onProgress, onError );
  34652. }
  34653. /**
  34654. * Parses the given JSON object and returns a material.
  34655. *
  34656. * @param {Object} json - The serialized material.
  34657. * @return {Material} The parsed material.
  34658. */
  34659. parse( json ) {
  34660. const textures = this.textures;
  34661. function getTexture( name ) {
  34662. if ( textures[ name ] === undefined ) {
  34663. warn( 'MaterialLoader: Undefined texture', name );
  34664. }
  34665. return textures[ name ];
  34666. }
  34667. const material = this.createMaterialFromType( json.type );
  34668. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34669. if ( json.name !== undefined ) material.name = json.name;
  34670. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34671. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34672. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34673. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34674. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34675. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34676. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34677. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34678. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34679. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34680. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34681. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34682. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34683. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34684. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34685. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34686. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34687. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34688. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34689. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34690. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34691. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34692. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34693. if ( json.fog !== undefined ) material.fog = json.fog;
  34694. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34695. if ( json.blending !== undefined ) material.blending = json.blending;
  34696. if ( json.combine !== undefined ) material.combine = json.combine;
  34697. if ( json.side !== undefined ) material.side = json.side;
  34698. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34699. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34700. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34701. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34702. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34703. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34704. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34705. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34706. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34707. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34708. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34709. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34710. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34711. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34712. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34713. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34714. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34715. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34716. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34717. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34718. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34719. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34720. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34721. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34722. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34723. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34724. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34725. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34726. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34727. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34728. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34729. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34730. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34731. if ( json.scale !== undefined ) material.scale = json.scale;
  34732. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34733. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34734. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34735. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34736. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34737. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34738. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34739. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34740. if ( json.visible !== undefined ) material.visible = json.visible;
  34741. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34742. if ( json.userData !== undefined ) material.userData = json.userData;
  34743. if ( json.vertexColors !== undefined ) {
  34744. if ( typeof json.vertexColors === 'number' ) {
  34745. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34746. } else {
  34747. material.vertexColors = json.vertexColors;
  34748. }
  34749. }
  34750. // Shader Material
  34751. if ( json.uniforms !== undefined ) {
  34752. for ( const name in json.uniforms ) {
  34753. const uniform = json.uniforms[ name ];
  34754. material.uniforms[ name ] = {};
  34755. switch ( uniform.type ) {
  34756. case 't':
  34757. material.uniforms[ name ].value = getTexture( uniform.value );
  34758. break;
  34759. case 'c':
  34760. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34761. break;
  34762. case 'v2':
  34763. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34764. break;
  34765. case 'v3':
  34766. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34767. break;
  34768. case 'v4':
  34769. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34770. break;
  34771. case 'm3':
  34772. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34773. break;
  34774. case 'm4':
  34775. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34776. break;
  34777. default:
  34778. material.uniforms[ name ].value = uniform.value;
  34779. }
  34780. }
  34781. }
  34782. if ( json.defines !== undefined ) material.defines = json.defines;
  34783. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34784. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34785. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34786. if ( json.extensions !== undefined ) {
  34787. for ( const key in json.extensions ) {
  34788. material.extensions[ key ] = json.extensions[ key ];
  34789. }
  34790. }
  34791. if ( json.lights !== undefined ) material.lights = json.lights;
  34792. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34793. // for PointsMaterial
  34794. if ( json.size !== undefined ) material.size = json.size;
  34795. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34796. // maps
  34797. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34798. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34799. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34800. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34801. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34802. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34803. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34804. if ( json.normalScale !== undefined ) {
  34805. let normalScale = json.normalScale;
  34806. if ( Array.isArray( normalScale ) === false ) {
  34807. // Blender exporter used to export a scalar. See #7459
  34808. normalScale = [ normalScale, normalScale ];
  34809. }
  34810. material.normalScale = new Vector2().fromArray( normalScale );
  34811. }
  34812. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34813. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34814. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34815. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34816. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34817. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34818. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34819. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34820. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34821. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34822. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34823. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34824. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34825. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34826. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34827. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34828. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34829. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34830. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34831. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34832. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34833. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34834. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34835. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34836. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34837. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34838. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34839. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34840. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34841. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34842. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34843. return material;
  34844. }
  34845. /**
  34846. * Textures are not embedded in the material JSON so they have
  34847. * to be injected before the loading process starts.
  34848. *
  34849. * @param {Object} value - A dictionary holding textures for material properties.
  34850. * @return {MaterialLoader} A reference to this material loader.
  34851. */
  34852. setTextures( value ) {
  34853. this.textures = value;
  34854. return this;
  34855. }
  34856. /**
  34857. * Creates a material for the given type.
  34858. *
  34859. * @param {string} type - The material type.
  34860. * @return {Material} The new material.
  34861. */
  34862. createMaterialFromType( type ) {
  34863. return MaterialLoader.createMaterialFromType( type );
  34864. }
  34865. /**
  34866. * Creates a material for the given type.
  34867. *
  34868. * @static
  34869. * @param {string} type - The material type.
  34870. * @return {Material} The new material.
  34871. */
  34872. static createMaterialFromType( type ) {
  34873. const materialLib = {
  34874. ShadowMaterial,
  34875. SpriteMaterial,
  34876. RawShaderMaterial,
  34877. ShaderMaterial,
  34878. PointsMaterial,
  34879. MeshPhysicalMaterial,
  34880. MeshStandardMaterial,
  34881. MeshPhongMaterial,
  34882. MeshToonMaterial,
  34883. MeshNormalMaterial,
  34884. MeshLambertMaterial,
  34885. MeshDepthMaterial,
  34886. MeshDistanceMaterial,
  34887. MeshBasicMaterial,
  34888. MeshMatcapMaterial,
  34889. LineDashedMaterial,
  34890. LineBasicMaterial,
  34891. Material
  34892. };
  34893. return new materialLib[ type ]();
  34894. }
  34895. }
  34896. /**
  34897. * A class with loader utility functions.
  34898. */
  34899. class LoaderUtils {
  34900. /**
  34901. * Extracts the base URL from the given URL.
  34902. *
  34903. * @param {string} url -The URL to extract the base URL from.
  34904. * @return {string} The extracted base URL.
  34905. */
  34906. static extractUrlBase( url ) {
  34907. const index = url.lastIndexOf( '/' );
  34908. if ( index === -1 ) return './';
  34909. return url.slice( 0, index + 1 );
  34910. }
  34911. /**
  34912. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34913. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34914. * string.
  34915. *
  34916. * @param {string} url -The URL to resolve.
  34917. * @param {string} path - The base path for relative URLs to be resolved against.
  34918. * @return {string} The resolved URL.
  34919. */
  34920. static resolveURL( url, path ) {
  34921. // Invalid URL
  34922. if ( typeof url !== 'string' || url === '' ) return '';
  34923. // Host Relative URL
  34924. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34925. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34926. }
  34927. // Absolute URL http://,https://,//
  34928. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34929. // Data URI
  34930. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34931. // Blob URL
  34932. if ( /^blob:.*$/i.test( url ) ) return url;
  34933. // Relative URL
  34934. return path + url;
  34935. }
  34936. }
  34937. /**
  34938. * An instanced version of a geometry.
  34939. */
  34940. class InstancedBufferGeometry extends BufferGeometry {
  34941. /**
  34942. * Constructs a new instanced buffer geometry.
  34943. */
  34944. constructor() {
  34945. super();
  34946. /**
  34947. * This flag can be used for type testing.
  34948. *
  34949. * @type {boolean}
  34950. * @readonly
  34951. * @default true
  34952. */
  34953. this.isInstancedBufferGeometry = true;
  34954. this.type = 'InstancedBufferGeometry';
  34955. /**
  34956. * The instance count.
  34957. *
  34958. * @type {number}
  34959. * @default Infinity
  34960. */
  34961. this.instanceCount = Infinity;
  34962. }
  34963. copy( source ) {
  34964. super.copy( source );
  34965. this.instanceCount = source.instanceCount;
  34966. return this;
  34967. }
  34968. toJSON() {
  34969. const data = super.toJSON();
  34970. data.instanceCount = this.instanceCount;
  34971. data.isInstancedBufferGeometry = true;
  34972. return data;
  34973. }
  34974. }
  34975. /**
  34976. * Class for loading geometries. The files are internally
  34977. * loaded via {@link FileLoader}.
  34978. *
  34979. * ```js
  34980. * const loader = new THREE.BufferGeometryLoader();
  34981. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34982. *
  34983. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34984. * const object = new THREE.Mesh( geometry, material );
  34985. * scene.add( object );
  34986. * ```
  34987. *
  34988. * @augments Loader
  34989. */
  34990. class BufferGeometryLoader extends Loader {
  34991. /**
  34992. * Constructs a new geometry loader.
  34993. *
  34994. * @param {LoadingManager} [manager] - The loading manager.
  34995. */
  34996. constructor( manager ) {
  34997. super( manager );
  34998. }
  34999. /**
  35000. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35001. *
  35002. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35003. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35004. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35005. * @param {onErrorCallback} onError - Executed when errors occur.
  35006. */
  35007. load( url, onLoad, onProgress, onError ) {
  35008. const scope = this;
  35009. const loader = new FileLoader( scope.manager );
  35010. loader.setPath( scope.path );
  35011. loader.setRequestHeader( scope.requestHeader );
  35012. loader.setWithCredentials( scope.withCredentials );
  35013. loader.load( url, function ( text ) {
  35014. try {
  35015. onLoad( scope.parse( JSON.parse( text ) ) );
  35016. } catch ( e ) {
  35017. if ( onError ) {
  35018. onError( e );
  35019. } else {
  35020. error( e );
  35021. }
  35022. scope.manager.itemError( url );
  35023. }
  35024. }, onProgress, onError );
  35025. }
  35026. /**
  35027. * Parses the given JSON object and returns a geometry.
  35028. *
  35029. * @param {Object} json - The serialized geometry.
  35030. * @return {BufferGeometry} The parsed geometry.
  35031. */
  35032. parse( json ) {
  35033. const interleavedBufferMap = {};
  35034. const arrayBufferMap = {};
  35035. function getInterleavedBuffer( json, uuid ) {
  35036. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35037. const interleavedBuffers = json.interleavedBuffers;
  35038. const interleavedBuffer = interleavedBuffers[ uuid ];
  35039. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35040. const array = getTypedArray( interleavedBuffer.type, buffer );
  35041. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35042. ib.uuid = interleavedBuffer.uuid;
  35043. interleavedBufferMap[ uuid ] = ib;
  35044. return ib;
  35045. }
  35046. function getArrayBuffer( json, uuid ) {
  35047. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35048. const arrayBuffers = json.arrayBuffers;
  35049. const arrayBuffer = arrayBuffers[ uuid ];
  35050. const ab = new Uint32Array( arrayBuffer ).buffer;
  35051. arrayBufferMap[ uuid ] = ab;
  35052. return ab;
  35053. }
  35054. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35055. const index = json.data.index;
  35056. if ( index !== undefined ) {
  35057. const typedArray = getTypedArray( index.type, index.array );
  35058. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35059. }
  35060. const attributes = json.data.attributes;
  35061. for ( const key in attributes ) {
  35062. const attribute = attributes[ key ];
  35063. let bufferAttribute;
  35064. if ( attribute.isInterleavedBufferAttribute ) {
  35065. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35066. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35067. } else {
  35068. const typedArray = getTypedArray( attribute.type, attribute.array );
  35069. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35070. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35071. }
  35072. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35073. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35074. geometry.setAttribute( key, bufferAttribute );
  35075. }
  35076. const morphAttributes = json.data.morphAttributes;
  35077. if ( morphAttributes ) {
  35078. for ( const key in morphAttributes ) {
  35079. const attributeArray = morphAttributes[ key ];
  35080. const array = [];
  35081. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35082. const attribute = attributeArray[ i ];
  35083. let bufferAttribute;
  35084. if ( attribute.isInterleavedBufferAttribute ) {
  35085. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35086. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35087. } else {
  35088. const typedArray = getTypedArray( attribute.type, attribute.array );
  35089. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35090. }
  35091. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35092. array.push( bufferAttribute );
  35093. }
  35094. geometry.morphAttributes[ key ] = array;
  35095. }
  35096. }
  35097. const morphTargetsRelative = json.data.morphTargetsRelative;
  35098. if ( morphTargetsRelative ) {
  35099. geometry.morphTargetsRelative = true;
  35100. }
  35101. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35102. if ( groups !== undefined ) {
  35103. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35104. const group = groups[ i ];
  35105. geometry.addGroup( group.start, group.count, group.materialIndex );
  35106. }
  35107. }
  35108. const boundingSphere = json.data.boundingSphere;
  35109. if ( boundingSphere !== undefined ) {
  35110. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35111. }
  35112. if ( json.name ) geometry.name = json.name;
  35113. if ( json.userData ) geometry.userData = json.userData;
  35114. return geometry;
  35115. }
  35116. }
  35117. /**
  35118. * 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).
  35119. * The files are internally loaded via {@link FileLoader}.
  35120. *
  35121. * ```js
  35122. * const loader = new THREE.ObjectLoader();
  35123. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35124. * scene.add( obj );
  35125. *
  35126. * // Alternatively, to parse a previously loaded JSON structure
  35127. * const object = await loader.parseAsync( a_json_object );
  35128. * scene.add( object );
  35129. * ```
  35130. *
  35131. * @augments Loader
  35132. */
  35133. class ObjectLoader extends Loader {
  35134. /**
  35135. * Constructs a new object loader.
  35136. *
  35137. * @param {LoadingManager} [manager] - The loading manager.
  35138. */
  35139. constructor( manager ) {
  35140. super( manager );
  35141. }
  35142. /**
  35143. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35144. *
  35145. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35146. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35147. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35148. * @param {onErrorCallback} onError - Executed when errors occur.
  35149. */
  35150. load( url, onLoad, onProgress, onError ) {
  35151. const scope = this;
  35152. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35153. this.resourcePath = this.resourcePath || path;
  35154. const loader = new FileLoader( this.manager );
  35155. loader.setPath( this.path );
  35156. loader.setRequestHeader( this.requestHeader );
  35157. loader.setWithCredentials( this.withCredentials );
  35158. loader.load( url, function ( text ) {
  35159. let json = null;
  35160. try {
  35161. json = JSON.parse( text );
  35162. } catch ( error ) {
  35163. if ( onError !== undefined ) onError( error );
  35164. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35165. return;
  35166. }
  35167. const metadata = json.metadata;
  35168. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35169. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35170. error( 'ObjectLoader: Can\'t load ' + url );
  35171. return;
  35172. }
  35173. scope.parse( json, onLoad );
  35174. }, onProgress, onError );
  35175. }
  35176. /**
  35177. * Async version of {@link ObjectLoader#load}.
  35178. *
  35179. * @async
  35180. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35181. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35182. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35183. */
  35184. async loadAsync( url, onProgress ) {
  35185. const scope = this;
  35186. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35187. this.resourcePath = this.resourcePath || path;
  35188. const loader = new FileLoader( this.manager );
  35189. loader.setPath( this.path );
  35190. loader.setRequestHeader( this.requestHeader );
  35191. loader.setWithCredentials( this.withCredentials );
  35192. const text = await loader.loadAsync( url, onProgress );
  35193. const json = JSON.parse( text );
  35194. const metadata = json.metadata;
  35195. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35196. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35197. }
  35198. return await scope.parseAsync( json );
  35199. }
  35200. /**
  35201. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35202. * but can also be used directly to parse a previously loaded JSON structure.
  35203. *
  35204. * @param {Object} json - The serialized 3D object.
  35205. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35206. * @return {Object3D} The parsed 3D object.
  35207. */
  35208. parse( json, onLoad ) {
  35209. const animations = this.parseAnimations( json.animations );
  35210. const shapes = this.parseShapes( json.shapes );
  35211. const geometries = this.parseGeometries( json.geometries, shapes );
  35212. const images = this.parseImages( json.images, function () {
  35213. if ( onLoad !== undefined ) onLoad( object );
  35214. } );
  35215. const textures = this.parseTextures( json.textures, images );
  35216. const materials = this.parseMaterials( json.materials, textures );
  35217. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35218. const skeletons = this.parseSkeletons( json.skeletons, object );
  35219. this.bindSkeletons( object, skeletons );
  35220. this.bindLightTargets( object );
  35221. //
  35222. if ( onLoad !== undefined ) {
  35223. let hasImages = false;
  35224. for ( const uuid in images ) {
  35225. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35226. hasImages = true;
  35227. break;
  35228. }
  35229. }
  35230. if ( hasImages === false ) onLoad( object );
  35231. }
  35232. return object;
  35233. }
  35234. /**
  35235. * Async version of {@link ObjectLoader#parse}.
  35236. *
  35237. * @param {Object} json - The serialized 3D object.
  35238. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35239. */
  35240. async parseAsync( json ) {
  35241. const animations = this.parseAnimations( json.animations );
  35242. const shapes = this.parseShapes( json.shapes );
  35243. const geometries = this.parseGeometries( json.geometries, shapes );
  35244. const images = await this.parseImagesAsync( json.images );
  35245. const textures = this.parseTextures( json.textures, images );
  35246. const materials = this.parseMaterials( json.materials, textures );
  35247. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35248. const skeletons = this.parseSkeletons( json.skeletons, object );
  35249. this.bindSkeletons( object, skeletons );
  35250. this.bindLightTargets( object );
  35251. return object;
  35252. }
  35253. // internals
  35254. parseShapes( json ) {
  35255. const shapes = {};
  35256. if ( json !== undefined ) {
  35257. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35258. const shape = new Shape().fromJSON( json[ i ] );
  35259. shapes[ shape.uuid ] = shape;
  35260. }
  35261. }
  35262. return shapes;
  35263. }
  35264. parseSkeletons( json, object ) {
  35265. const skeletons = {};
  35266. const bones = {};
  35267. // generate bone lookup table
  35268. object.traverse( function ( child ) {
  35269. if ( child.isBone ) bones[ child.uuid ] = child;
  35270. } );
  35271. // create skeletons
  35272. if ( json !== undefined ) {
  35273. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35274. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35275. skeletons[ skeleton.uuid ] = skeleton;
  35276. }
  35277. }
  35278. return skeletons;
  35279. }
  35280. parseGeometries( json, shapes ) {
  35281. const geometries = {};
  35282. if ( json !== undefined ) {
  35283. const bufferGeometryLoader = new BufferGeometryLoader();
  35284. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35285. let geometry;
  35286. const data = json[ i ];
  35287. switch ( data.type ) {
  35288. case 'BufferGeometry':
  35289. case 'InstancedBufferGeometry':
  35290. geometry = bufferGeometryLoader.parse( data );
  35291. break;
  35292. default:
  35293. if ( data.type in Geometries ) {
  35294. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35295. } else {
  35296. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35297. }
  35298. }
  35299. geometry.uuid = data.uuid;
  35300. if ( data.name !== undefined ) geometry.name = data.name;
  35301. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35302. geometries[ data.uuid ] = geometry;
  35303. }
  35304. }
  35305. return geometries;
  35306. }
  35307. parseMaterials( json, textures ) {
  35308. const cache = {}; // MultiMaterial
  35309. const materials = {};
  35310. if ( json !== undefined ) {
  35311. const loader = new MaterialLoader();
  35312. loader.setTextures( textures );
  35313. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35314. const data = json[ i ];
  35315. if ( cache[ data.uuid ] === undefined ) {
  35316. cache[ data.uuid ] = loader.parse( data );
  35317. }
  35318. materials[ data.uuid ] = cache[ data.uuid ];
  35319. }
  35320. }
  35321. return materials;
  35322. }
  35323. parseAnimations( json ) {
  35324. const animations = {};
  35325. if ( json !== undefined ) {
  35326. for ( let i = 0; i < json.length; i ++ ) {
  35327. const data = json[ i ];
  35328. const clip = AnimationClip.parse( data );
  35329. animations[ clip.uuid ] = clip;
  35330. }
  35331. }
  35332. return animations;
  35333. }
  35334. parseImages( json, onLoad ) {
  35335. const scope = this;
  35336. const images = {};
  35337. let loader;
  35338. function loadImage( url ) {
  35339. scope.manager.itemStart( url );
  35340. return loader.load( url, function () {
  35341. scope.manager.itemEnd( url );
  35342. }, undefined, function () {
  35343. scope.manager.itemError( url );
  35344. scope.manager.itemEnd( url );
  35345. } );
  35346. }
  35347. function deserializeImage( image ) {
  35348. if ( typeof image === 'string' ) {
  35349. const url = image;
  35350. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35351. return loadImage( path );
  35352. } else {
  35353. if ( image.data ) {
  35354. return {
  35355. data: getTypedArray( image.type, image.data ),
  35356. width: image.width,
  35357. height: image.height
  35358. };
  35359. } else {
  35360. return null;
  35361. }
  35362. }
  35363. }
  35364. if ( json !== undefined && json.length > 0 ) {
  35365. const manager = new LoadingManager( onLoad );
  35366. loader = new ImageLoader( manager );
  35367. loader.setCrossOrigin( this.crossOrigin );
  35368. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35369. const image = json[ i ];
  35370. const url = image.url;
  35371. if ( Array.isArray( url ) ) {
  35372. // load array of images e.g CubeTexture
  35373. const imageArray = [];
  35374. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35375. const currentUrl = url[ j ];
  35376. const deserializedImage = deserializeImage( currentUrl );
  35377. if ( deserializedImage !== null ) {
  35378. if ( deserializedImage instanceof HTMLImageElement ) {
  35379. imageArray.push( deserializedImage );
  35380. } else {
  35381. // special case: handle array of data textures for cube textures
  35382. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35383. }
  35384. }
  35385. }
  35386. images[ image.uuid ] = new Source( imageArray );
  35387. } else {
  35388. // load single image
  35389. const deserializedImage = deserializeImage( image.url );
  35390. images[ image.uuid ] = new Source( deserializedImage );
  35391. }
  35392. }
  35393. }
  35394. return images;
  35395. }
  35396. async parseImagesAsync( json ) {
  35397. const scope = this;
  35398. const images = {};
  35399. let loader;
  35400. async function deserializeImage( image ) {
  35401. if ( typeof image === 'string' ) {
  35402. const url = image;
  35403. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35404. return await loader.loadAsync( path );
  35405. } else {
  35406. if ( image.data ) {
  35407. return {
  35408. data: getTypedArray( image.type, image.data ),
  35409. width: image.width,
  35410. height: image.height
  35411. };
  35412. } else {
  35413. return null;
  35414. }
  35415. }
  35416. }
  35417. if ( json !== undefined && json.length > 0 ) {
  35418. loader = new ImageLoader( this.manager );
  35419. loader.setCrossOrigin( this.crossOrigin );
  35420. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35421. const image = json[ i ];
  35422. const url = image.url;
  35423. if ( Array.isArray( url ) ) {
  35424. // load array of images e.g CubeTexture
  35425. const imageArray = [];
  35426. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35427. const currentUrl = url[ j ];
  35428. const deserializedImage = await deserializeImage( currentUrl );
  35429. if ( deserializedImage !== null ) {
  35430. if ( deserializedImage instanceof HTMLImageElement ) {
  35431. imageArray.push( deserializedImage );
  35432. } else {
  35433. // special case: handle array of data textures for cube textures
  35434. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35435. }
  35436. }
  35437. }
  35438. images[ image.uuid ] = new Source( imageArray );
  35439. } else {
  35440. // load single image
  35441. const deserializedImage = await deserializeImage( image.url );
  35442. images[ image.uuid ] = new Source( deserializedImage );
  35443. }
  35444. }
  35445. }
  35446. return images;
  35447. }
  35448. parseTextures( json, images ) {
  35449. function parseConstant( value, type ) {
  35450. if ( typeof value === 'number' ) return value;
  35451. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35452. return type[ value ];
  35453. }
  35454. const textures = {};
  35455. if ( json !== undefined ) {
  35456. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35457. const data = json[ i ];
  35458. if ( data.image === undefined ) {
  35459. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35460. }
  35461. if ( images[ data.image ] === undefined ) {
  35462. warn( 'ObjectLoader: Undefined image', data.image );
  35463. }
  35464. const source = images[ data.image ];
  35465. const image = source.data;
  35466. let texture;
  35467. if ( Array.isArray( image ) ) {
  35468. texture = new CubeTexture();
  35469. if ( image.length === 6 ) texture.needsUpdate = true;
  35470. } else {
  35471. if ( image && image.data ) {
  35472. texture = new DataTexture();
  35473. } else {
  35474. texture = new Texture();
  35475. }
  35476. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35477. }
  35478. texture.source = source;
  35479. texture.uuid = data.uuid;
  35480. if ( data.name !== undefined ) texture.name = data.name;
  35481. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35482. if ( data.channel !== undefined ) texture.channel = data.channel;
  35483. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35484. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35485. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35486. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35487. if ( data.wrap !== undefined ) {
  35488. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35489. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35490. }
  35491. if ( data.format !== undefined ) texture.format = data.format;
  35492. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35493. if ( data.type !== undefined ) texture.type = data.type;
  35494. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35495. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35496. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35497. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35498. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35499. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35500. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35501. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35502. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35503. if ( data.userData !== undefined ) texture.userData = data.userData;
  35504. textures[ data.uuid ] = texture;
  35505. }
  35506. }
  35507. return textures;
  35508. }
  35509. parseObject( data, geometries, materials, textures, animations ) {
  35510. let object;
  35511. function getGeometry( name ) {
  35512. if ( geometries[ name ] === undefined ) {
  35513. warn( 'ObjectLoader: Undefined geometry', name );
  35514. }
  35515. return geometries[ name ];
  35516. }
  35517. function getMaterial( name ) {
  35518. if ( name === undefined ) return undefined;
  35519. if ( Array.isArray( name ) ) {
  35520. const array = [];
  35521. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35522. const uuid = name[ i ];
  35523. if ( materials[ uuid ] === undefined ) {
  35524. warn( 'ObjectLoader: Undefined material', uuid );
  35525. }
  35526. array.push( materials[ uuid ] );
  35527. }
  35528. return array;
  35529. }
  35530. if ( materials[ name ] === undefined ) {
  35531. warn( 'ObjectLoader: Undefined material', name );
  35532. }
  35533. return materials[ name ];
  35534. }
  35535. function getTexture( uuid ) {
  35536. if ( textures[ uuid ] === undefined ) {
  35537. warn( 'ObjectLoader: Undefined texture', uuid );
  35538. }
  35539. return textures[ uuid ];
  35540. }
  35541. let geometry, material;
  35542. switch ( data.type ) {
  35543. case 'Scene':
  35544. object = new Scene();
  35545. if ( data.background !== undefined ) {
  35546. if ( Number.isInteger( data.background ) ) {
  35547. object.background = new Color( data.background );
  35548. } else {
  35549. object.background = getTexture( data.background );
  35550. }
  35551. }
  35552. if ( data.environment !== undefined ) {
  35553. object.environment = getTexture( data.environment );
  35554. }
  35555. if ( data.fog !== undefined ) {
  35556. if ( data.fog.type === 'Fog' ) {
  35557. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35558. } else if ( data.fog.type === 'FogExp2' ) {
  35559. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35560. }
  35561. if ( data.fog.name !== '' ) {
  35562. object.fog.name = data.fog.name;
  35563. }
  35564. }
  35565. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35566. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35567. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35568. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35569. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35570. break;
  35571. case 'PerspectiveCamera':
  35572. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35573. if ( data.focus !== undefined ) object.focus = data.focus;
  35574. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35575. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35576. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35577. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35578. break;
  35579. case 'OrthographicCamera':
  35580. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35581. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35582. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35583. break;
  35584. case 'AmbientLight':
  35585. object = new AmbientLight( data.color, data.intensity );
  35586. break;
  35587. case 'DirectionalLight':
  35588. object = new DirectionalLight( data.color, data.intensity );
  35589. object.target = data.target || '';
  35590. break;
  35591. case 'PointLight':
  35592. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35593. break;
  35594. case 'RectAreaLight':
  35595. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35596. break;
  35597. case 'SpotLight':
  35598. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35599. object.target = data.target || '';
  35600. break;
  35601. case 'HemisphereLight':
  35602. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35603. break;
  35604. case 'LightProbe':
  35605. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35606. object = new LightProbe( sh, data.intensity );
  35607. break;
  35608. case 'SkinnedMesh':
  35609. geometry = getGeometry( data.geometry );
  35610. material = getMaterial( data.material );
  35611. object = new SkinnedMesh( geometry, material );
  35612. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35613. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35614. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35615. break;
  35616. case 'Mesh':
  35617. geometry = getGeometry( data.geometry );
  35618. material = getMaterial( data.material );
  35619. object = new Mesh( geometry, material );
  35620. break;
  35621. case 'InstancedMesh':
  35622. geometry = getGeometry( data.geometry );
  35623. material = getMaterial( data.material );
  35624. const count = data.count;
  35625. const instanceMatrix = data.instanceMatrix;
  35626. const instanceColor = data.instanceColor;
  35627. object = new InstancedMesh( geometry, material, count );
  35628. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35629. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35630. break;
  35631. case 'BatchedMesh':
  35632. geometry = getGeometry( data.geometry );
  35633. material = getMaterial( data.material );
  35634. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35635. object.geometry = geometry;
  35636. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35637. object.sortObjects = data.sortObjects;
  35638. object._drawRanges = data.drawRanges;
  35639. object._reservedRanges = data.reservedRanges;
  35640. object._geometryInfo = data.geometryInfo.map( info => {
  35641. let box = null;
  35642. let sphere = null;
  35643. if ( info.boundingBox !== undefined ) {
  35644. box = new Box3().fromJSON( info.boundingBox );
  35645. }
  35646. if ( info.boundingSphere !== undefined ) {
  35647. sphere = new Sphere().fromJSON( info.boundingSphere );
  35648. }
  35649. return {
  35650. ...info,
  35651. boundingBox: box,
  35652. boundingSphere: sphere
  35653. };
  35654. } );
  35655. object._instanceInfo = data.instanceInfo;
  35656. object._availableInstanceIds = data._availableInstanceIds;
  35657. object._availableGeometryIds = data._availableGeometryIds;
  35658. object._nextIndexStart = data.nextIndexStart;
  35659. object._nextVertexStart = data.nextVertexStart;
  35660. object._geometryCount = data.geometryCount;
  35661. object._maxInstanceCount = data.maxInstanceCount;
  35662. object._maxVertexCount = data.maxVertexCount;
  35663. object._maxIndexCount = data.maxIndexCount;
  35664. object._geometryInitialized = data.geometryInitialized;
  35665. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35666. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35667. if ( data.colorsTexture !== undefined ) {
  35668. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35669. }
  35670. if ( data.boundingSphere !== undefined ) {
  35671. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35672. }
  35673. if ( data.boundingBox !== undefined ) {
  35674. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35675. }
  35676. break;
  35677. case 'LOD':
  35678. object = new LOD();
  35679. break;
  35680. case 'Line':
  35681. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35682. break;
  35683. case 'LineLoop':
  35684. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35685. break;
  35686. case 'LineSegments':
  35687. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35688. break;
  35689. case 'PointCloud':
  35690. case 'Points':
  35691. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35692. break;
  35693. case 'Sprite':
  35694. object = new Sprite( getMaterial( data.material ) );
  35695. break;
  35696. case 'Group':
  35697. object = new Group();
  35698. break;
  35699. case 'Bone':
  35700. object = new Bone();
  35701. break;
  35702. default:
  35703. object = new Object3D();
  35704. }
  35705. object.uuid = data.uuid;
  35706. if ( data.name !== undefined ) object.name = data.name;
  35707. if ( data.matrix !== undefined ) {
  35708. object.matrix.fromArray( data.matrix );
  35709. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35710. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35711. } else {
  35712. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35713. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35714. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35715. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35716. }
  35717. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35718. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35719. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35720. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35721. if ( data.shadow ) {
  35722. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35723. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35724. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35725. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35726. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35727. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35728. }
  35729. if ( data.visible !== undefined ) object.visible = data.visible;
  35730. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35731. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35732. if ( data.static !== undefined ) object.static = data.static;
  35733. if ( data.userData !== undefined ) object.userData = data.userData;
  35734. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35735. if ( data.children !== undefined ) {
  35736. const children = data.children;
  35737. for ( let i = 0; i < children.length; i ++ ) {
  35738. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35739. }
  35740. }
  35741. if ( data.animations !== undefined ) {
  35742. const objectAnimations = data.animations;
  35743. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35744. const uuid = objectAnimations[ i ];
  35745. object.animations.push( animations[ uuid ] );
  35746. }
  35747. }
  35748. if ( data.type === 'LOD' ) {
  35749. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35750. const levels = data.levels;
  35751. for ( let l = 0; l < levels.length; l ++ ) {
  35752. const level = levels[ l ];
  35753. const child = object.getObjectByProperty( 'uuid', level.object );
  35754. if ( child !== undefined ) {
  35755. object.addLevel( child, level.distance, level.hysteresis );
  35756. }
  35757. }
  35758. }
  35759. return object;
  35760. }
  35761. bindSkeletons( object, skeletons ) {
  35762. if ( Object.keys( skeletons ).length === 0 ) return;
  35763. object.traverse( function ( child ) {
  35764. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35765. const skeleton = skeletons[ child.skeleton ];
  35766. if ( skeleton === undefined ) {
  35767. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35768. } else {
  35769. child.bind( skeleton, child.bindMatrix );
  35770. }
  35771. }
  35772. } );
  35773. }
  35774. bindLightTargets( object ) {
  35775. object.traverse( function ( child ) {
  35776. if ( child.isDirectionalLight || child.isSpotLight ) {
  35777. const uuid = child.target;
  35778. const target = object.getObjectByProperty( 'uuid', uuid );
  35779. if ( target !== undefined ) {
  35780. child.target = target;
  35781. } else {
  35782. child.target = new Object3D();
  35783. }
  35784. }
  35785. } );
  35786. }
  35787. }
  35788. const TEXTURE_MAPPING = {
  35789. UVMapping: UVMapping,
  35790. CubeReflectionMapping: CubeReflectionMapping,
  35791. CubeRefractionMapping: CubeRefractionMapping,
  35792. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35793. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35794. CubeUVReflectionMapping: CubeUVReflectionMapping
  35795. };
  35796. const TEXTURE_WRAPPING = {
  35797. RepeatWrapping: RepeatWrapping,
  35798. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35799. MirroredRepeatWrapping: MirroredRepeatWrapping
  35800. };
  35801. const TEXTURE_FILTER = {
  35802. NearestFilter: NearestFilter,
  35803. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35804. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35805. LinearFilter: LinearFilter,
  35806. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35807. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35808. };
  35809. const _errorMap = new WeakMap();
  35810. /**
  35811. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35812. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35813. * textures for rendering.
  35814. *
  35815. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35816. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35817. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35818. *
  35819. * To match the default behaviour of {@link Texture}, the following options are needed:
  35820. *
  35821. * ```js
  35822. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35823. * ```
  35824. *
  35825. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35826. *
  35827. * ```js
  35828. * const loader = new THREE.ImageBitmapLoader();
  35829. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35830. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35831. *
  35832. * const texture = new THREE.Texture( imageBitmap );
  35833. * texture.needsUpdate = true;
  35834. * ```
  35835. *
  35836. * @augments Loader
  35837. */
  35838. class ImageBitmapLoader extends Loader {
  35839. /**
  35840. * Constructs a new image bitmap loader.
  35841. *
  35842. * @param {LoadingManager} [manager] - The loading manager.
  35843. */
  35844. constructor( manager ) {
  35845. super( manager );
  35846. /**
  35847. * This flag can be used for type testing.
  35848. *
  35849. * @type {boolean}
  35850. * @readonly
  35851. * @default true
  35852. */
  35853. this.isImageBitmapLoader = true;
  35854. if ( typeof createImageBitmap === 'undefined' ) {
  35855. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35856. }
  35857. if ( typeof fetch === 'undefined' ) {
  35858. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35859. }
  35860. /**
  35861. * Represents the loader options.
  35862. *
  35863. * @type {Object}
  35864. * @default {premultiplyAlpha:'none'}
  35865. */
  35866. this.options = { premultiplyAlpha: 'none' };
  35867. /**
  35868. * Used for aborting requests.
  35869. *
  35870. * @private
  35871. * @type {AbortController}
  35872. */
  35873. this._abortController = new AbortController();
  35874. }
  35875. /**
  35876. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35877. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35878. *
  35879. * @param {Object} options - The loader options to set.
  35880. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35881. */
  35882. setOptions( options ) {
  35883. this.options = options;
  35884. return this;
  35885. }
  35886. /**
  35887. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35888. *
  35889. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35890. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35891. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35892. * @param {onErrorCallback} onError - Executed when errors occur.
  35893. * @return {ImageBitmap|undefined} The image bitmap.
  35894. */
  35895. load( url, onLoad, onProgress, onError ) {
  35896. if ( url === undefined ) url = '';
  35897. if ( this.path !== undefined ) url = this.path + url;
  35898. url = this.manager.resolveURL( url );
  35899. const scope = this;
  35900. const cached = Cache.get( `image-bitmap:${url}` );
  35901. if ( cached !== undefined ) {
  35902. scope.manager.itemStart( url );
  35903. // If cached is a promise, wait for it to resolve
  35904. if ( cached.then ) {
  35905. cached.then( imageBitmap => {
  35906. // check if there is an error for the cached promise
  35907. if ( _errorMap.has( cached ) === true ) {
  35908. if ( onError ) onError( _errorMap.get( cached ) );
  35909. scope.manager.itemError( url );
  35910. scope.manager.itemEnd( url );
  35911. } else {
  35912. if ( onLoad ) onLoad( imageBitmap );
  35913. scope.manager.itemEnd( url );
  35914. return imageBitmap;
  35915. }
  35916. } );
  35917. return;
  35918. }
  35919. // If cached is not a promise (i.e., it's already an imageBitmap)
  35920. setTimeout( function () {
  35921. if ( onLoad ) onLoad( cached );
  35922. scope.manager.itemEnd( url );
  35923. }, 0 );
  35924. return cached;
  35925. }
  35926. const fetchOptions = {};
  35927. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35928. fetchOptions.headers = this.requestHeader;
  35929. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35930. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35931. return res.blob();
  35932. } ).then( function ( blob ) {
  35933. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35934. } ).then( function ( imageBitmap ) {
  35935. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35936. if ( onLoad ) onLoad( imageBitmap );
  35937. scope.manager.itemEnd( url );
  35938. return imageBitmap;
  35939. } ).catch( function ( e ) {
  35940. if ( onError ) onError( e );
  35941. _errorMap.set( promise, e );
  35942. Cache.remove( `image-bitmap:${url}` );
  35943. scope.manager.itemError( url );
  35944. scope.manager.itemEnd( url );
  35945. } );
  35946. Cache.add( `image-bitmap:${url}`, promise );
  35947. scope.manager.itemStart( url );
  35948. }
  35949. /**
  35950. * Aborts ongoing fetch requests.
  35951. *
  35952. * @return {ImageBitmapLoader} A reference to this instance.
  35953. */
  35954. abort() {
  35955. this._abortController.abort();
  35956. this._abortController = new AbortController();
  35957. return this;
  35958. }
  35959. }
  35960. let _context;
  35961. /**
  35962. * Manages the global audio context in the engine.
  35963. *
  35964. * @hideconstructor
  35965. */
  35966. class AudioContext {
  35967. /**
  35968. * Returns the global native audio context.
  35969. *
  35970. * @return {AudioContext} The native audio context.
  35971. */
  35972. static getContext() {
  35973. if ( _context === undefined ) {
  35974. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35975. }
  35976. return _context;
  35977. }
  35978. /**
  35979. * Allows to set the global native audio context from outside.
  35980. *
  35981. * @param {AudioContext} value - The native context to set.
  35982. */
  35983. static setContext( value ) {
  35984. _context = value;
  35985. }
  35986. }
  35987. /**
  35988. * Class for loading audio buffers. Audios are internally
  35989. * loaded via {@link FileLoader}.
  35990. *
  35991. * ```js
  35992. * const audioListener = new THREE.AudioListener();
  35993. * const ambientSound = new THREE.Audio( audioListener );
  35994. *
  35995. * const loader = new THREE.AudioLoader();
  35996. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35997. *
  35998. * ambientSound.setBuffer( audioBuffer );
  35999. * ambientSound.play();
  36000. * ```
  36001. *
  36002. * @augments Loader
  36003. */
  36004. class AudioLoader extends Loader {
  36005. /**
  36006. * Constructs a new audio loader.
  36007. *
  36008. * @param {LoadingManager} [manager] - The loading manager.
  36009. */
  36010. constructor( manager ) {
  36011. super( manager );
  36012. }
  36013. /**
  36014. * Starts loading from the given URL and passes the loaded audio buffer
  36015. * to the `onLoad()` callback.
  36016. *
  36017. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36018. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36019. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36020. * @param {onErrorCallback} onError - Executed when errors occur.
  36021. */
  36022. load( url, onLoad, onProgress, onError ) {
  36023. const scope = this;
  36024. const loader = new FileLoader( this.manager );
  36025. loader.setResponseType( 'arraybuffer' );
  36026. loader.setPath( this.path );
  36027. loader.setRequestHeader( this.requestHeader );
  36028. loader.setWithCredentials( this.withCredentials );
  36029. loader.load( url, function ( buffer ) {
  36030. try {
  36031. // Create a copy of the buffer. The `decodeAudioData` method
  36032. // detaches the buffer when complete, preventing reuse.
  36033. const bufferCopy = buffer.slice( 0 );
  36034. const context = AudioContext.getContext();
  36035. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36036. onLoad( audioBuffer );
  36037. } ).catch( handleError );
  36038. } catch ( e ) {
  36039. handleError( e );
  36040. }
  36041. }, onProgress, onError );
  36042. function handleError( e ) {
  36043. if ( onError ) {
  36044. onError( e );
  36045. } else {
  36046. error( e );
  36047. }
  36048. scope.manager.itemError( url );
  36049. }
  36050. }
  36051. }
  36052. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36053. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36054. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36055. /**
  36056. * A special type of camera that uses two perspective cameras with
  36057. * stereoscopic projection. Can be used for rendering stereo effects
  36058. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36059. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36060. */
  36061. class StereoCamera {
  36062. /**
  36063. * Constructs a new stereo camera.
  36064. */
  36065. constructor() {
  36066. /**
  36067. * The type property is used for detecting the object type
  36068. * in context of serialization/deserialization.
  36069. *
  36070. * @type {string}
  36071. * @readonly
  36072. */
  36073. this.type = 'StereoCamera';
  36074. /**
  36075. * The aspect.
  36076. *
  36077. * @type {number}
  36078. * @default 1
  36079. */
  36080. this.aspect = 1;
  36081. /**
  36082. * The eye separation which represents the distance
  36083. * between the left and right camera.
  36084. *
  36085. * @type {number}
  36086. * @default 0.064
  36087. */
  36088. this.eyeSep = 0.064;
  36089. /**
  36090. * The camera representing the left eye. This is added to layer `1` so objects to be
  36091. * rendered by the left camera must also be added to this layer.
  36092. *
  36093. * @type {PerspectiveCamera}
  36094. */
  36095. this.cameraL = new PerspectiveCamera();
  36096. this.cameraL.layers.enable( 1 );
  36097. this.cameraL.matrixAutoUpdate = false;
  36098. /**
  36099. * The camera representing the right eye. This is added to layer `2` so objects to be
  36100. * rendered by the right camera must also be added to this layer.
  36101. *
  36102. * @type {PerspectiveCamera}
  36103. */
  36104. this.cameraR = new PerspectiveCamera();
  36105. this.cameraR.layers.enable( 2 );
  36106. this.cameraR.matrixAutoUpdate = false;
  36107. this._cache = {
  36108. focus: null,
  36109. fov: null,
  36110. aspect: null,
  36111. near: null,
  36112. far: null,
  36113. zoom: null,
  36114. eyeSep: null
  36115. };
  36116. }
  36117. /**
  36118. * Updates the stereo camera based on the given perspective camera.
  36119. *
  36120. * @param {PerspectiveCamera} camera - The perspective camera.
  36121. */
  36122. update( camera ) {
  36123. const cache = this._cache;
  36124. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36125. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36126. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36127. if ( needsUpdate ) {
  36128. cache.focus = camera.focus;
  36129. cache.fov = camera.fov;
  36130. cache.aspect = camera.aspect * this.aspect;
  36131. cache.near = camera.near;
  36132. cache.far = camera.far;
  36133. cache.zoom = camera.zoom;
  36134. cache.eyeSep = this.eyeSep;
  36135. // Off-axis stereoscopic effect based on
  36136. // http://paulbourke.net/stereographics/stereorender/
  36137. _projectionMatrix.copy( camera.projectionMatrix );
  36138. const eyeSepHalf = cache.eyeSep / 2;
  36139. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36140. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36141. let xmin, xmax;
  36142. // translate xOffset
  36143. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36144. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36145. // for left eye
  36146. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36147. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36148. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36149. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36150. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36151. // for right eye
  36152. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36153. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36154. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36155. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36156. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36157. }
  36158. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36159. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36160. }
  36161. }
  36162. /**
  36163. * This type of camera can be used in order to efficiently render a scene with a
  36164. * predefined set of cameras. This is an important performance aspect for
  36165. * rendering VR scenes.
  36166. *
  36167. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36168. * to define for each sub camera the `viewport` property which determines the
  36169. * part of the viewport that is rendered with this camera.
  36170. *
  36171. * @augments PerspectiveCamera
  36172. */
  36173. class ArrayCamera extends PerspectiveCamera {
  36174. /**
  36175. * Constructs a new array camera.
  36176. *
  36177. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36178. */
  36179. constructor( array = [] ) {
  36180. super();
  36181. /**
  36182. * This flag can be used for type testing.
  36183. *
  36184. * @type {boolean}
  36185. * @readonly
  36186. * @default true
  36187. */
  36188. this.isArrayCamera = true;
  36189. /**
  36190. * Whether this camera is used with multiview rendering or not.
  36191. *
  36192. * @type {boolean}
  36193. * @readonly
  36194. * @default false
  36195. */
  36196. this.isMultiViewCamera = false;
  36197. /**
  36198. * An array of perspective sub cameras.
  36199. *
  36200. * @type {Array<PerspectiveCamera>}
  36201. */
  36202. this.cameras = array;
  36203. }
  36204. }
  36205. /**
  36206. * Class for keeping track of time.
  36207. */
  36208. class Clock {
  36209. /**
  36210. * Constructs a new clock.
  36211. *
  36212. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36213. * `getDelta()` is called for the first time.
  36214. */
  36215. constructor( autoStart = true ) {
  36216. /**
  36217. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36218. * for the first time.
  36219. *
  36220. * @type {boolean}
  36221. * @default true
  36222. */
  36223. this.autoStart = autoStart;
  36224. /**
  36225. * Holds the time at which the clock's `start()` method was last called.
  36226. *
  36227. * @type {number}
  36228. * @default 0
  36229. */
  36230. this.startTime = 0;
  36231. /**
  36232. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36233. * `getDelta()` methods were last called.
  36234. *
  36235. * @type {number}
  36236. * @default 0
  36237. */
  36238. this.oldTime = 0;
  36239. /**
  36240. * Keeps track of the total time that the clock has been running.
  36241. *
  36242. * @type {number}
  36243. * @default 0
  36244. */
  36245. this.elapsedTime = 0;
  36246. /**
  36247. * Whether the clock is running or not.
  36248. *
  36249. * @type {boolean}
  36250. * @default true
  36251. */
  36252. this.running = false;
  36253. }
  36254. /**
  36255. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36256. * called by the class.
  36257. */
  36258. start() {
  36259. this.startTime = performance.now();
  36260. this.oldTime = this.startTime;
  36261. this.elapsedTime = 0;
  36262. this.running = true;
  36263. }
  36264. /**
  36265. * Stops the clock.
  36266. */
  36267. stop() {
  36268. this.getElapsedTime();
  36269. this.running = false;
  36270. this.autoStart = false;
  36271. }
  36272. /**
  36273. * Returns the elapsed time in seconds.
  36274. *
  36275. * @return {number} The elapsed time.
  36276. */
  36277. getElapsedTime() {
  36278. this.getDelta();
  36279. return this.elapsedTime;
  36280. }
  36281. /**
  36282. * Returns the delta time in seconds.
  36283. *
  36284. * @return {number} The delta time.
  36285. */
  36286. getDelta() {
  36287. let diff = 0;
  36288. if ( this.autoStart && ! this.running ) {
  36289. this.start();
  36290. return 0;
  36291. }
  36292. if ( this.running ) {
  36293. const newTime = performance.now();
  36294. diff = ( newTime - this.oldTime ) / 1000;
  36295. this.oldTime = newTime;
  36296. this.elapsedTime += diff;
  36297. }
  36298. return diff;
  36299. }
  36300. }
  36301. const _position$1 = /*@__PURE__*/ new Vector3();
  36302. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36303. const _scale$1 = /*@__PURE__*/ new Vector3();
  36304. const _forward = /*@__PURE__*/ new Vector3();
  36305. const _up = /*@__PURE__*/ new Vector3();
  36306. /**
  36307. * The class represents a virtual listener of the all positional and non-positional audio effects
  36308. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36309. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36310. *
  36311. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36312. * camera represents the 3D transformation of the listener.
  36313. *
  36314. * @augments Object3D
  36315. */
  36316. class AudioListener extends Object3D {
  36317. /**
  36318. * Constructs a new audio listener.
  36319. */
  36320. constructor() {
  36321. super();
  36322. this.type = 'AudioListener';
  36323. /**
  36324. * The native audio context.
  36325. *
  36326. * @type {AudioContext}
  36327. * @readonly
  36328. */
  36329. this.context = AudioContext.getContext();
  36330. /**
  36331. * The gain node used for volume control.
  36332. *
  36333. * @type {GainNode}
  36334. * @readonly
  36335. */
  36336. this.gain = this.context.createGain();
  36337. this.gain.connect( this.context.destination );
  36338. /**
  36339. * An optional filter.
  36340. *
  36341. * Defined via {@link AudioListener#setFilter}.
  36342. *
  36343. * @type {?AudioNode}
  36344. * @default null
  36345. * @readonly
  36346. */
  36347. this.filter = null;
  36348. /**
  36349. * Time delta values required for `linearRampToValueAtTime()` usage.
  36350. *
  36351. * @type {number}
  36352. * @default 0
  36353. * @readonly
  36354. */
  36355. this.timeDelta = 0;
  36356. // private
  36357. this._clock = new Clock();
  36358. }
  36359. /**
  36360. * Returns the listener's input node.
  36361. *
  36362. * This method is used by other audio nodes to connect to this listener.
  36363. *
  36364. * @return {GainNode} The input node.
  36365. */
  36366. getInput() {
  36367. return this.gain;
  36368. }
  36369. /**
  36370. * Removes the current filter from this listener.
  36371. *
  36372. * @return {AudioListener} A reference to this listener.
  36373. */
  36374. removeFilter() {
  36375. if ( this.filter !== null ) {
  36376. this.gain.disconnect( this.filter );
  36377. this.filter.disconnect( this.context.destination );
  36378. this.gain.connect( this.context.destination );
  36379. this.filter = null;
  36380. }
  36381. return this;
  36382. }
  36383. /**
  36384. * Returns the current set filter.
  36385. *
  36386. * @return {?AudioNode} The filter.
  36387. */
  36388. getFilter() {
  36389. return this.filter;
  36390. }
  36391. /**
  36392. * Sets the given filter to this listener.
  36393. *
  36394. * @param {AudioNode} value - The filter to set.
  36395. * @return {AudioListener} A reference to this listener.
  36396. */
  36397. setFilter( value ) {
  36398. if ( this.filter !== null ) {
  36399. this.gain.disconnect( this.filter );
  36400. this.filter.disconnect( this.context.destination );
  36401. } else {
  36402. this.gain.disconnect( this.context.destination );
  36403. }
  36404. this.filter = value;
  36405. this.gain.connect( this.filter );
  36406. this.filter.connect( this.context.destination );
  36407. return this;
  36408. }
  36409. /**
  36410. * Returns the applications master volume.
  36411. *
  36412. * @return {number} The master volume.
  36413. */
  36414. getMasterVolume() {
  36415. return this.gain.gain.value;
  36416. }
  36417. /**
  36418. * Sets the applications master volume. This volume setting affects
  36419. * all audio nodes in the scene.
  36420. *
  36421. * @param {number} value - The master volume to set.
  36422. * @return {AudioListener} A reference to this listener.
  36423. */
  36424. setMasterVolume( value ) {
  36425. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36426. return this;
  36427. }
  36428. updateMatrixWorld( force ) {
  36429. super.updateMatrixWorld( force );
  36430. const listener = this.context.listener;
  36431. this.timeDelta = this._clock.getDelta();
  36432. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36433. // the initial forward and up directions must be orthogonal
  36434. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36435. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36436. if ( listener.positionX ) {
  36437. // code path for Chrome (see #14393)
  36438. const endTime = this.context.currentTime + this.timeDelta;
  36439. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36440. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36441. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36442. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36443. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36444. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36445. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36446. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36447. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36448. } else {
  36449. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36450. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36451. }
  36452. }
  36453. }
  36454. /**
  36455. * Represents a non-positional ( global ) audio object.
  36456. *
  36457. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36458. *
  36459. * ```js
  36460. * // create an AudioListener and add it to the camera
  36461. * const listener = new THREE.AudioListener();
  36462. * camera.add( listener );
  36463. *
  36464. * // create a global audio source
  36465. * const sound = new THREE.Audio( listener );
  36466. *
  36467. * // load a sound and set it as the Audio object's buffer
  36468. * const audioLoader = new THREE.AudioLoader();
  36469. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36470. * sound.setBuffer( buffer );
  36471. * sound.setLoop( true );
  36472. * sound.setVolume( 0.5 );
  36473. * sound.play();
  36474. * });
  36475. * ```
  36476. *
  36477. * @augments Object3D
  36478. */
  36479. class Audio extends Object3D {
  36480. /**
  36481. * Constructs a new audio.
  36482. *
  36483. * @param {AudioListener} listener - The global audio listener.
  36484. */
  36485. constructor( listener ) {
  36486. super();
  36487. this.type = 'Audio';
  36488. /**
  36489. * The global audio listener.
  36490. *
  36491. * @type {AudioListener}
  36492. * @readonly
  36493. */
  36494. this.listener = listener;
  36495. /**
  36496. * The audio context.
  36497. *
  36498. * @type {AudioContext}
  36499. * @readonly
  36500. */
  36501. this.context = listener.context;
  36502. /**
  36503. * The gain node used for volume control.
  36504. *
  36505. * @type {GainNode}
  36506. * @readonly
  36507. */
  36508. this.gain = this.context.createGain();
  36509. this.gain.connect( listener.getInput() );
  36510. /**
  36511. * Whether to start playback automatically or not.
  36512. *
  36513. * @type {boolean}
  36514. * @default false
  36515. */
  36516. this.autoplay = false;
  36517. /**
  36518. * A reference to an audio buffer.
  36519. *
  36520. * Defined via {@link Audio#setBuffer}.
  36521. *
  36522. * @type {?AudioBuffer}
  36523. * @default null
  36524. * @readonly
  36525. */
  36526. this.buffer = null;
  36527. /**
  36528. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36529. * +/- 1200 is an octave.
  36530. *
  36531. * Defined via {@link Audio#setDetune}.
  36532. *
  36533. * @type {number}
  36534. * @default 0
  36535. * @readonly
  36536. */
  36537. this.detune = 0;
  36538. /**
  36539. * Whether the audio should loop or not.
  36540. *
  36541. * Defined via {@link Audio#setLoop}.
  36542. *
  36543. * @type {boolean}
  36544. * @default false
  36545. * @readonly
  36546. */
  36547. this.loop = false;
  36548. /**
  36549. * Defines where in the audio buffer the replay should
  36550. * start, in seconds.
  36551. *
  36552. * @type {number}
  36553. * @default 0
  36554. */
  36555. this.loopStart = 0;
  36556. /**
  36557. * Defines where in the audio buffer the replay should
  36558. * stop, in seconds.
  36559. *
  36560. * @type {number}
  36561. * @default 0
  36562. */
  36563. this.loopEnd = 0;
  36564. /**
  36565. * An offset to the time within the audio buffer the playback
  36566. * should begin, in seconds.
  36567. *
  36568. * @type {number}
  36569. * @default 0
  36570. */
  36571. this.offset = 0;
  36572. /**
  36573. * Overrides the default duration of the audio.
  36574. *
  36575. * @type {undefined|number}
  36576. * @default undefined
  36577. */
  36578. this.duration = undefined;
  36579. /**
  36580. * The playback speed.
  36581. *
  36582. * Defined via {@link Audio#setPlaybackRate}.
  36583. *
  36584. * @type {number}
  36585. * @readonly
  36586. * @default 1
  36587. */
  36588. this.playbackRate = 1;
  36589. /**
  36590. * Indicates whether the audio is playing or not.
  36591. *
  36592. * This flag will be automatically set when using {@link Audio#play},
  36593. * {@link Audio#pause}, {@link Audio#stop}.
  36594. *
  36595. * @type {boolean}
  36596. * @readonly
  36597. * @default false
  36598. */
  36599. this.isPlaying = false;
  36600. /**
  36601. * Indicates whether the audio playback can be controlled
  36602. * with method like {@link Audio#play} or {@link Audio#pause}.
  36603. *
  36604. * This flag will be automatically set when audio sources are
  36605. * defined.
  36606. *
  36607. * @type {boolean}
  36608. * @readonly
  36609. * @default true
  36610. */
  36611. this.hasPlaybackControl = true;
  36612. /**
  36613. * Holds a reference to the current audio source.
  36614. *
  36615. * The property is automatically by one of the `set*()` methods.
  36616. *
  36617. * @type {?AudioNode}
  36618. * @readonly
  36619. * @default null
  36620. */
  36621. this.source = null;
  36622. /**
  36623. * Defines the source type.
  36624. *
  36625. * The property is automatically set by one of the `set*()` methods.
  36626. *
  36627. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36628. * @readonly
  36629. * @default 'empty'
  36630. */
  36631. this.sourceType = 'empty';
  36632. this._startedAt = 0;
  36633. this._progress = 0;
  36634. this._connected = false;
  36635. /**
  36636. * Can be used to apply a variety of low-order filters to create
  36637. * more complex sound effects e.g. via `BiquadFilterNode`.
  36638. *
  36639. * The property is automatically set by {@link Audio#setFilters}.
  36640. *
  36641. * @type {Array<AudioNode>}
  36642. * @readonly
  36643. */
  36644. this.filters = [];
  36645. }
  36646. /**
  36647. * Returns the output audio node.
  36648. *
  36649. * @return {GainNode} The output node.
  36650. */
  36651. getOutput() {
  36652. return this.gain;
  36653. }
  36654. /**
  36655. * Sets the given audio node as the source of this instance.
  36656. *
  36657. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36658. *
  36659. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36660. * @return {Audio} A reference to this instance.
  36661. */
  36662. setNodeSource( audioNode ) {
  36663. this.hasPlaybackControl = false;
  36664. this.sourceType = 'audioNode';
  36665. this.source = audioNode;
  36666. this.connect();
  36667. return this;
  36668. }
  36669. /**
  36670. * Sets the given media element as the source of this instance.
  36671. *
  36672. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36673. *
  36674. * @param {HTMLMediaElement} mediaElement - The media element.
  36675. * @return {Audio} A reference to this instance.
  36676. */
  36677. setMediaElementSource( mediaElement ) {
  36678. this.hasPlaybackControl = false;
  36679. this.sourceType = 'mediaNode';
  36680. this.source = this.context.createMediaElementSource( mediaElement );
  36681. this.connect();
  36682. return this;
  36683. }
  36684. /**
  36685. * Sets the given media stream as the source of this instance.
  36686. *
  36687. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36688. *
  36689. * @param {MediaStream} mediaStream - The media stream.
  36690. * @return {Audio} A reference to this instance.
  36691. */
  36692. setMediaStreamSource( mediaStream ) {
  36693. this.hasPlaybackControl = false;
  36694. this.sourceType = 'mediaStreamNode';
  36695. this.source = this.context.createMediaStreamSource( mediaStream );
  36696. this.connect();
  36697. return this;
  36698. }
  36699. /**
  36700. * Sets the given audio buffer as the source of this instance.
  36701. *
  36702. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36703. *
  36704. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36705. * @return {Audio} A reference to this instance.
  36706. */
  36707. setBuffer( audioBuffer ) {
  36708. this.buffer = audioBuffer;
  36709. this.sourceType = 'buffer';
  36710. if ( this.autoplay ) this.play();
  36711. return this;
  36712. }
  36713. /**
  36714. * Starts the playback of the audio.
  36715. *
  36716. * Can only be used with compatible audio sources that allow playback control.
  36717. *
  36718. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36719. * @return {Audio|undefined} A reference to this instance.
  36720. */
  36721. play( delay = 0 ) {
  36722. if ( this.isPlaying === true ) {
  36723. warn( 'Audio: Audio is already playing.' );
  36724. return;
  36725. }
  36726. if ( this.hasPlaybackControl === false ) {
  36727. warn( 'Audio: this Audio has no playback control.' );
  36728. return;
  36729. }
  36730. this._startedAt = this.context.currentTime + delay;
  36731. const source = this.context.createBufferSource();
  36732. source.buffer = this.buffer;
  36733. source.loop = this.loop;
  36734. source.loopStart = this.loopStart;
  36735. source.loopEnd = this.loopEnd;
  36736. source.onended = this.onEnded.bind( this );
  36737. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36738. this.isPlaying = true;
  36739. this.source = source;
  36740. this.setDetune( this.detune );
  36741. this.setPlaybackRate( this.playbackRate );
  36742. return this.connect();
  36743. }
  36744. /**
  36745. * Pauses the playback of the audio.
  36746. *
  36747. * Can only be used with compatible audio sources that allow playback control.
  36748. *
  36749. * @return {Audio|undefined} A reference to this instance.
  36750. */
  36751. pause() {
  36752. if ( this.hasPlaybackControl === false ) {
  36753. warn( 'Audio: this Audio has no playback control.' );
  36754. return;
  36755. }
  36756. if ( this.isPlaying === true ) {
  36757. // update current progress
  36758. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36759. if ( this.loop === true ) {
  36760. // ensure _progress does not exceed duration with looped audios
  36761. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36762. }
  36763. this.source.stop();
  36764. this.source.onended = null;
  36765. this.isPlaying = false;
  36766. }
  36767. return this;
  36768. }
  36769. /**
  36770. * Stops the playback of the audio.
  36771. *
  36772. * Can only be used with compatible audio sources that allow playback control.
  36773. *
  36774. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36775. * @return {Audio|undefined} A reference to this instance.
  36776. */
  36777. stop( delay = 0 ) {
  36778. if ( this.hasPlaybackControl === false ) {
  36779. warn( 'Audio: this Audio has no playback control.' );
  36780. return;
  36781. }
  36782. this._progress = 0;
  36783. if ( this.source !== null ) {
  36784. this.source.stop( this.context.currentTime + delay );
  36785. this.source.onended = null;
  36786. }
  36787. this.isPlaying = false;
  36788. return this;
  36789. }
  36790. /**
  36791. * Connects to the audio source. This is used internally on
  36792. * initialisation and when setting / removing filters.
  36793. *
  36794. * @return {Audio} A reference to this instance.
  36795. */
  36796. connect() {
  36797. if ( this.filters.length > 0 ) {
  36798. this.source.connect( this.filters[ 0 ] );
  36799. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36800. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36801. }
  36802. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36803. } else {
  36804. this.source.connect( this.getOutput() );
  36805. }
  36806. this._connected = true;
  36807. return this;
  36808. }
  36809. /**
  36810. * Disconnects to the audio source. This is used internally on
  36811. * initialisation and when setting / removing filters.
  36812. *
  36813. * @return {Audio|undefined} A reference to this instance.
  36814. */
  36815. disconnect() {
  36816. if ( this._connected === false ) {
  36817. return;
  36818. }
  36819. if ( this.filters.length > 0 ) {
  36820. this.source.disconnect( this.filters[ 0 ] );
  36821. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36822. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36823. }
  36824. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36825. } else {
  36826. this.source.disconnect( this.getOutput() );
  36827. }
  36828. this._connected = false;
  36829. return this;
  36830. }
  36831. /**
  36832. * Returns the current set filters.
  36833. *
  36834. * @return {Array<AudioNode>} The list of filters.
  36835. */
  36836. getFilters() {
  36837. return this.filters;
  36838. }
  36839. /**
  36840. * Sets an array of filters and connects them with the audio source.
  36841. *
  36842. * @param {Array<AudioNode>} [value] - A list of filters.
  36843. * @return {Audio} A reference to this instance.
  36844. */
  36845. setFilters( value ) {
  36846. if ( ! value ) value = [];
  36847. if ( this._connected === true ) {
  36848. this.disconnect();
  36849. this.filters = value.slice();
  36850. this.connect();
  36851. } else {
  36852. this.filters = value.slice();
  36853. }
  36854. return this;
  36855. }
  36856. /**
  36857. * Defines the detuning of oscillation in cents.
  36858. *
  36859. * @param {number} value - The detuning of oscillation in cents.
  36860. * @return {Audio} A reference to this instance.
  36861. */
  36862. setDetune( value ) {
  36863. this.detune = value;
  36864. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36865. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36866. }
  36867. return this;
  36868. }
  36869. /**
  36870. * Returns the detuning of oscillation in cents.
  36871. *
  36872. * @return {number} The detuning of oscillation in cents.
  36873. */
  36874. getDetune() {
  36875. return this.detune;
  36876. }
  36877. /**
  36878. * Returns the first filter in the list of filters.
  36879. *
  36880. * @return {AudioNode|undefined} The first filter in the list of filters.
  36881. */
  36882. getFilter() {
  36883. return this.getFilters()[ 0 ];
  36884. }
  36885. /**
  36886. * Applies a single filter node to the audio.
  36887. *
  36888. * @param {AudioNode} [filter] - The filter to set.
  36889. * @return {Audio} A reference to this instance.
  36890. */
  36891. setFilter( filter ) {
  36892. return this.setFilters( filter ? [ filter ] : [] );
  36893. }
  36894. /**
  36895. * Sets the playback rate.
  36896. *
  36897. * Can only be used with compatible audio sources that allow playback control.
  36898. *
  36899. * @param {number} [value] - The playback rate to set.
  36900. * @return {Audio|undefined} A reference to this instance.
  36901. */
  36902. setPlaybackRate( value ) {
  36903. if ( this.hasPlaybackControl === false ) {
  36904. warn( 'Audio: this Audio has no playback control.' );
  36905. return;
  36906. }
  36907. this.playbackRate = value;
  36908. if ( this.isPlaying === true ) {
  36909. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36910. }
  36911. return this;
  36912. }
  36913. /**
  36914. * Returns the current playback rate.
  36915. * @return {number} The playback rate.
  36916. */
  36917. getPlaybackRate() {
  36918. return this.playbackRate;
  36919. }
  36920. /**
  36921. * Automatically called when playback finished.
  36922. */
  36923. onEnded() {
  36924. this.isPlaying = false;
  36925. this._progress = 0;
  36926. }
  36927. /**
  36928. * Returns the loop flag.
  36929. *
  36930. * Can only be used with compatible audio sources that allow playback control.
  36931. *
  36932. * @return {boolean} Whether the audio should loop or not.
  36933. */
  36934. getLoop() {
  36935. if ( this.hasPlaybackControl === false ) {
  36936. warn( 'Audio: this Audio has no playback control.' );
  36937. return false;
  36938. }
  36939. return this.loop;
  36940. }
  36941. /**
  36942. * Sets the loop flag.
  36943. *
  36944. * Can only be used with compatible audio sources that allow playback control.
  36945. *
  36946. * @param {boolean} value - Whether the audio should loop or not.
  36947. * @return {Audio|undefined} A reference to this instance.
  36948. */
  36949. setLoop( value ) {
  36950. if ( this.hasPlaybackControl === false ) {
  36951. warn( 'Audio: this Audio has no playback control.' );
  36952. return;
  36953. }
  36954. this.loop = value;
  36955. if ( this.isPlaying === true ) {
  36956. this.source.loop = this.loop;
  36957. }
  36958. return this;
  36959. }
  36960. /**
  36961. * Sets the loop start value which defines where in the audio buffer the replay should
  36962. * start, in seconds.
  36963. *
  36964. * @param {number} value - The loop start value.
  36965. * @return {Audio} A reference to this instance.
  36966. */
  36967. setLoopStart( value ) {
  36968. this.loopStart = value;
  36969. return this;
  36970. }
  36971. /**
  36972. * Sets the loop end value which defines where in the audio buffer the replay should
  36973. * stop, in seconds.
  36974. *
  36975. * @param {number} value - The loop end value.
  36976. * @return {Audio} A reference to this instance.
  36977. */
  36978. setLoopEnd( value ) {
  36979. this.loopEnd = value;
  36980. return this;
  36981. }
  36982. /**
  36983. * Returns the volume.
  36984. *
  36985. * @return {number} The volume.
  36986. */
  36987. getVolume() {
  36988. return this.gain.gain.value;
  36989. }
  36990. /**
  36991. * Sets the volume.
  36992. *
  36993. * @param {number} value - The volume to set.
  36994. * @return {Audio} A reference to this instance.
  36995. */
  36996. setVolume( value ) {
  36997. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36998. return this;
  36999. }
  37000. copy( source, recursive ) {
  37001. super.copy( source, recursive );
  37002. if ( source.sourceType !== 'buffer' ) {
  37003. warn( 'Audio: Audio source type cannot be copied.' );
  37004. return this;
  37005. }
  37006. this.autoplay = source.autoplay;
  37007. this.buffer = source.buffer;
  37008. this.detune = source.detune;
  37009. this.loop = source.loop;
  37010. this.loopStart = source.loopStart;
  37011. this.loopEnd = source.loopEnd;
  37012. this.offset = source.offset;
  37013. this.duration = source.duration;
  37014. this.playbackRate = source.playbackRate;
  37015. this.hasPlaybackControl = source.hasPlaybackControl;
  37016. this.sourceType = source.sourceType;
  37017. this.filters = source.filters.slice();
  37018. return this;
  37019. }
  37020. clone( recursive ) {
  37021. return new this.constructor( this.listener ).copy( this, recursive );
  37022. }
  37023. }
  37024. const _position = /*@__PURE__*/ new Vector3();
  37025. const _quaternion = /*@__PURE__*/ new Quaternion();
  37026. const _scale = /*@__PURE__*/ new Vector3();
  37027. const _orientation = /*@__PURE__*/ new Vector3();
  37028. /**
  37029. * Represents a positional audio object.
  37030. *
  37031. * ```js
  37032. * // create an AudioListener and add it to the camera
  37033. * const listener = new THREE.AudioListener();
  37034. * camera.add( listener );
  37035. *
  37036. * // create the PositionalAudio object (passing in the listener)
  37037. * const sound = new THREE.PositionalAudio( listener );
  37038. *
  37039. * // load a sound and set it as the PositionalAudio object's buffer
  37040. * const audioLoader = new THREE.AudioLoader();
  37041. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37042. * sound.setBuffer( buffer );
  37043. * sound.setRefDistance( 20 );
  37044. * sound.play();
  37045. * });
  37046. *
  37047. * // create an object for the sound to play from
  37048. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37049. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37050. * const mesh = new THREE.Mesh( sphere, material );
  37051. * scene.add( mesh );
  37052. *
  37053. * // finally add the sound to the mesh
  37054. * mesh.add( sound );
  37055. *
  37056. * @augments Audio
  37057. */
  37058. class PositionalAudio extends Audio {
  37059. /**
  37060. * Constructs a positional audio.
  37061. *
  37062. * @param {AudioListener} listener - The global audio listener.
  37063. */
  37064. constructor( listener ) {
  37065. super( listener );
  37066. /**
  37067. * The panner node represents the location, direction, and behavior of an audio
  37068. * source in 3D space.
  37069. *
  37070. * @type {PannerNode}
  37071. * @readonly
  37072. */
  37073. this.panner = this.context.createPanner();
  37074. this.panner.panningModel = 'HRTF';
  37075. this.panner.connect( this.gain );
  37076. }
  37077. connect() {
  37078. super.connect();
  37079. this.panner.connect( this.gain );
  37080. return this;
  37081. }
  37082. disconnect() {
  37083. super.disconnect();
  37084. this.panner.disconnect( this.gain );
  37085. return this;
  37086. }
  37087. getOutput() {
  37088. return this.panner;
  37089. }
  37090. /**
  37091. * Returns the current reference distance.
  37092. *
  37093. * @return {number} The reference distance.
  37094. */
  37095. getRefDistance() {
  37096. return this.panner.refDistance;
  37097. }
  37098. /**
  37099. * Defines the reference distance for reducing volume as the audio source moves
  37100. * further from the listener – i.e. the distance at which the volume reduction
  37101. * starts taking effect.
  37102. *
  37103. * @param {number} value - The reference distance to set.
  37104. * @return {PositionalAudio} A reference to this instance.
  37105. */
  37106. setRefDistance( value ) {
  37107. this.panner.refDistance = value;
  37108. return this;
  37109. }
  37110. /**
  37111. * Returns the current rolloff factor.
  37112. *
  37113. * @return {number} The rolloff factor.
  37114. */
  37115. getRolloffFactor() {
  37116. return this.panner.rolloffFactor;
  37117. }
  37118. /**
  37119. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37120. *
  37121. * @param {number} value - The rolloff factor.
  37122. * @return {PositionalAudio} A reference to this instance.
  37123. */
  37124. setRolloffFactor( value ) {
  37125. this.panner.rolloffFactor = value;
  37126. return this;
  37127. }
  37128. /**
  37129. * Returns the current distance model.
  37130. *
  37131. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37132. */
  37133. getDistanceModel() {
  37134. return this.panner.distanceModel;
  37135. }
  37136. /**
  37137. * Defines which algorithm to use to reduce the volume of the audio source
  37138. * as it moves away from the listener.
  37139. *
  37140. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37141. * for more details.
  37142. *
  37143. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37144. * @return {PositionalAudio} A reference to this instance.
  37145. */
  37146. setDistanceModel( value ) {
  37147. this.panner.distanceModel = value;
  37148. return this;
  37149. }
  37150. /**
  37151. * Returns the current max distance.
  37152. *
  37153. * @return {number} The max distance.
  37154. */
  37155. getMaxDistance() {
  37156. return this.panner.maxDistance;
  37157. }
  37158. /**
  37159. * Defines the maximum distance between the audio source and the listener,
  37160. * after which the volume is not reduced any further.
  37161. *
  37162. * This value is used only by the `linear` distance model.
  37163. *
  37164. * @param {number} value - The max distance.
  37165. * @return {PositionalAudio} A reference to this instance.
  37166. */
  37167. setMaxDistance( value ) {
  37168. this.panner.maxDistance = value;
  37169. return this;
  37170. }
  37171. /**
  37172. * Sets the directional cone in which the audio can be listened.
  37173. *
  37174. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37175. * @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.
  37176. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37177. * @return {PositionalAudio} A reference to this instance.
  37178. */
  37179. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37180. this.panner.coneInnerAngle = coneInnerAngle;
  37181. this.panner.coneOuterAngle = coneOuterAngle;
  37182. this.panner.coneOuterGain = coneOuterGain;
  37183. return this;
  37184. }
  37185. updateMatrixWorld( force ) {
  37186. super.updateMatrixWorld( force );
  37187. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37188. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37189. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37190. const panner = this.panner;
  37191. if ( panner.positionX ) {
  37192. // code path for Chrome and Firefox (see #14393)
  37193. const endTime = this.context.currentTime + this.listener.timeDelta;
  37194. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37195. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37196. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37197. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37198. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37199. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37200. } else {
  37201. panner.setPosition( _position.x, _position.y, _position.z );
  37202. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37203. }
  37204. }
  37205. }
  37206. /**
  37207. * This class can be used to analyse audio data.
  37208. *
  37209. * ```js
  37210. * // create an AudioListener and add it to the camera
  37211. * const listener = new THREE.AudioListener();
  37212. * camera.add( listener );
  37213. *
  37214. * // create an Audio source
  37215. * const sound = new THREE.Audio( listener );
  37216. *
  37217. * // load a sound and set it as the Audio object's buffer
  37218. * const audioLoader = new THREE.AudioLoader();
  37219. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37220. * sound.setBuffer( buffer );
  37221. * sound.setLoop(true);
  37222. * sound.setVolume(0.5);
  37223. * sound.play();
  37224. * });
  37225. *
  37226. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37227. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37228. *
  37229. * // get the average frequency of the sound
  37230. * const data = analyser.getAverageFrequency();
  37231. * ```
  37232. */
  37233. class AudioAnalyser {
  37234. /**
  37235. * Constructs a new audio analyzer.
  37236. *
  37237. * @param {Audio} audio - The audio to analyze.
  37238. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37239. */
  37240. constructor( audio, fftSize = 2048 ) {
  37241. /**
  37242. * The global audio listener.
  37243. *
  37244. * @type {AnalyserNode}
  37245. */
  37246. this.analyser = audio.context.createAnalyser();
  37247. this.analyser.fftSize = fftSize;
  37248. /**
  37249. * Holds the analyzed data.
  37250. *
  37251. * @type {Uint8Array}
  37252. */
  37253. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37254. audio.getOutput().connect( this.analyser );
  37255. }
  37256. /**
  37257. * Returns an array with frequency data of the audio.
  37258. *
  37259. * Each item in the array represents the decibel value for a specific frequency.
  37260. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37261. * For example, for 48000 sample rate, the last item of the array will represent
  37262. * the decibel value for 24000 Hz.
  37263. *
  37264. * @return {Uint8Array} The frequency data.
  37265. */
  37266. getFrequencyData() {
  37267. this.analyser.getByteFrequencyData( this.data );
  37268. return this.data;
  37269. }
  37270. /**
  37271. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37272. *
  37273. * @return {number} The average frequency.
  37274. */
  37275. getAverageFrequency() {
  37276. let value = 0;
  37277. const data = this.getFrequencyData();
  37278. for ( let i = 0; i < data.length; i ++ ) {
  37279. value += data[ i ];
  37280. }
  37281. return value / data.length;
  37282. }
  37283. }
  37284. /**
  37285. * Buffered scene graph property that allows weighted accumulation; used internally.
  37286. */
  37287. class PropertyMixer {
  37288. /**
  37289. * Constructs a new property mixer.
  37290. *
  37291. * @param {PropertyBinding} binding - The property binding.
  37292. * @param {string} typeName - The keyframe track type name.
  37293. * @param {number} valueSize - The keyframe track value size.
  37294. */
  37295. constructor( binding, typeName, valueSize ) {
  37296. /**
  37297. * The property binding.
  37298. *
  37299. * @type {PropertyBinding}
  37300. */
  37301. this.binding = binding;
  37302. /**
  37303. * The keyframe track value size.
  37304. *
  37305. * @type {number}
  37306. */
  37307. this.valueSize = valueSize;
  37308. let mixFunction,
  37309. mixFunctionAdditive,
  37310. setIdentity;
  37311. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37312. //
  37313. // interpolators can use .buffer as their .result
  37314. // the data then goes to 'incoming'
  37315. //
  37316. // 'accu0' and 'accu1' are used frame-interleaved for
  37317. // the cumulative result and are compared to detect
  37318. // changes
  37319. //
  37320. // 'orig' stores the original state of the property
  37321. //
  37322. // 'add' is used for additive cumulative results
  37323. //
  37324. // 'work' is optional and is only present for quaternion types. It is used
  37325. // to store intermediate quaternion multiplication results
  37326. switch ( typeName ) {
  37327. case 'quaternion':
  37328. mixFunction = this._slerp;
  37329. mixFunctionAdditive = this._slerpAdditive;
  37330. setIdentity = this._setAdditiveIdentityQuaternion;
  37331. this.buffer = new Float64Array( valueSize * 6 );
  37332. this._workIndex = 5;
  37333. break;
  37334. case 'string':
  37335. case 'bool':
  37336. mixFunction = this._select;
  37337. // Use the regular mix function and for additive on these types,
  37338. // additive is not relevant for non-numeric types
  37339. mixFunctionAdditive = this._select;
  37340. setIdentity = this._setAdditiveIdentityOther;
  37341. this.buffer = new Array( valueSize * 5 );
  37342. break;
  37343. default:
  37344. mixFunction = this._lerp;
  37345. mixFunctionAdditive = this._lerpAdditive;
  37346. setIdentity = this._setAdditiveIdentityNumeric;
  37347. this.buffer = new Float64Array( valueSize * 5 );
  37348. }
  37349. this._mixBufferRegion = mixFunction;
  37350. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37351. this._setIdentity = setIdentity;
  37352. this._origIndex = 3;
  37353. this._addIndex = 4;
  37354. /**
  37355. * TODO
  37356. *
  37357. * @type {number}
  37358. * @default 0
  37359. */
  37360. this.cumulativeWeight = 0;
  37361. /**
  37362. * TODO
  37363. *
  37364. * @type {number}
  37365. * @default 0
  37366. */
  37367. this.cumulativeWeightAdditive = 0;
  37368. /**
  37369. * TODO
  37370. *
  37371. * @type {number}
  37372. * @default 0
  37373. */
  37374. this.useCount = 0;
  37375. /**
  37376. * TODO
  37377. *
  37378. * @type {number}
  37379. * @default 0
  37380. */
  37381. this.referenceCount = 0;
  37382. }
  37383. /**
  37384. * Accumulates data in the `incoming` region into `accu<i>`.
  37385. *
  37386. * @param {number} accuIndex - The accumulation index.
  37387. * @param {number} weight - The weight.
  37388. */
  37389. accumulate( accuIndex, weight ) {
  37390. // note: happily accumulating nothing when weight = 0, the caller knows
  37391. // the weight and shouldn't have made the call in the first place
  37392. const buffer = this.buffer,
  37393. stride = this.valueSize,
  37394. offset = accuIndex * stride + stride;
  37395. let currentWeight = this.cumulativeWeight;
  37396. if ( currentWeight === 0 ) {
  37397. // accuN := incoming * weight
  37398. for ( let i = 0; i !== stride; ++ i ) {
  37399. buffer[ offset + i ] = buffer[ i ];
  37400. }
  37401. currentWeight = weight;
  37402. } else {
  37403. // accuN := accuN + incoming * weight
  37404. currentWeight += weight;
  37405. const mix = weight / currentWeight;
  37406. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37407. }
  37408. this.cumulativeWeight = currentWeight;
  37409. }
  37410. /**
  37411. * Accumulates data in the `incoming` region into `add`.
  37412. *
  37413. * @param {number} weight - The weight.
  37414. */
  37415. accumulateAdditive( weight ) {
  37416. const buffer = this.buffer,
  37417. stride = this.valueSize,
  37418. offset = stride * this._addIndex;
  37419. if ( this.cumulativeWeightAdditive === 0 ) {
  37420. // add = identity
  37421. this._setIdentity();
  37422. }
  37423. // add := add + incoming * weight
  37424. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37425. this.cumulativeWeightAdditive += weight;
  37426. }
  37427. /**
  37428. * Applies the state of `accu<i>` to the binding when accus differ.
  37429. *
  37430. * @param {number} accuIndex - The accumulation index.
  37431. */
  37432. apply( accuIndex ) {
  37433. const stride = this.valueSize,
  37434. buffer = this.buffer,
  37435. offset = accuIndex * stride + stride,
  37436. weight = this.cumulativeWeight,
  37437. weightAdditive = this.cumulativeWeightAdditive,
  37438. binding = this.binding;
  37439. this.cumulativeWeight = 0;
  37440. this.cumulativeWeightAdditive = 0;
  37441. if ( weight < 1 ) {
  37442. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37443. const originalValueOffset = stride * this._origIndex;
  37444. this._mixBufferRegion(
  37445. buffer, offset, originalValueOffset, 1 - weight, stride );
  37446. }
  37447. if ( weightAdditive > 0 ) {
  37448. // accuN := accuN + additive accuN
  37449. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37450. }
  37451. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37452. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37453. // value has changed -> update scene graph
  37454. binding.setValue( buffer, offset );
  37455. break;
  37456. }
  37457. }
  37458. }
  37459. /**
  37460. * Remembers the state of the bound property and copy it to both accus.
  37461. */
  37462. saveOriginalState() {
  37463. const binding = this.binding;
  37464. const buffer = this.buffer,
  37465. stride = this.valueSize,
  37466. originalValueOffset = stride * this._origIndex;
  37467. binding.getValue( buffer, originalValueOffset );
  37468. // accu[0..1] := orig -- initially detect changes against the original
  37469. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37470. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37471. }
  37472. // Add to identity for additive
  37473. this._setIdentity();
  37474. this.cumulativeWeight = 0;
  37475. this.cumulativeWeightAdditive = 0;
  37476. }
  37477. /**
  37478. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37479. */
  37480. restoreOriginalState() {
  37481. const originalValueOffset = this.valueSize * 3;
  37482. this.binding.setValue( this.buffer, originalValueOffset );
  37483. }
  37484. // internals
  37485. _setAdditiveIdentityNumeric() {
  37486. const startIndex = this._addIndex * this.valueSize;
  37487. const endIndex = startIndex + this.valueSize;
  37488. for ( let i = startIndex; i < endIndex; i ++ ) {
  37489. this.buffer[ i ] = 0;
  37490. }
  37491. }
  37492. _setAdditiveIdentityQuaternion() {
  37493. this._setAdditiveIdentityNumeric();
  37494. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37495. }
  37496. _setAdditiveIdentityOther() {
  37497. const startIndex = this._origIndex * this.valueSize;
  37498. const targetIndex = this._addIndex * this.valueSize;
  37499. for ( let i = 0; i < this.valueSize; i ++ ) {
  37500. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37501. }
  37502. }
  37503. // mix functions
  37504. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37505. if ( t >= 0.5 ) {
  37506. for ( let i = 0; i !== stride; ++ i ) {
  37507. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37508. }
  37509. }
  37510. }
  37511. _slerp( buffer, dstOffset, srcOffset, t ) {
  37512. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37513. }
  37514. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37515. const workOffset = this._workIndex * stride;
  37516. // Store result in intermediate buffer offset
  37517. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37518. // Slerp to the intermediate result
  37519. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37520. }
  37521. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37522. const s = 1 - t;
  37523. for ( let i = 0; i !== stride; ++ i ) {
  37524. const j = dstOffset + i;
  37525. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37526. }
  37527. }
  37528. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37529. for ( let i = 0; i !== stride; ++ i ) {
  37530. const j = dstOffset + i;
  37531. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37532. }
  37533. }
  37534. }
  37535. // Characters [].:/ are reserved for track binding syntax.
  37536. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37537. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37538. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37539. // only latin characters, and the unicode \p{L} is not yet supported. So
  37540. // instead, we exclude reserved characters and match everything else.
  37541. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37542. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37543. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37544. // be matched to parse the rest of the track name.
  37545. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37546. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37547. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37548. // Object on target node, and accessor. May not contain reserved
  37549. // characters. Accessor may contain any character except closing bracket.
  37550. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37551. // Property and accessor. May not contain reserved characters. Accessor may
  37552. // contain any non-bracket characters.
  37553. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37554. const _trackRe = new RegExp( ''
  37555. + '^'
  37556. + _directoryRe
  37557. + _nodeRe
  37558. + _objectRe
  37559. + _propertyRe
  37560. + '$'
  37561. );
  37562. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37563. class Composite {
  37564. constructor( targetGroup, path, optionalParsedPath ) {
  37565. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37566. this._targetGroup = targetGroup;
  37567. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37568. }
  37569. getValue( array, offset ) {
  37570. this.bind(); // bind all binding
  37571. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37572. binding = this._bindings[ firstValidIndex ];
  37573. // and only call .getValue on the first
  37574. if ( binding !== undefined ) binding.getValue( array, offset );
  37575. }
  37576. setValue( array, offset ) {
  37577. const bindings = this._bindings;
  37578. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37579. bindings[ i ].setValue( array, offset );
  37580. }
  37581. }
  37582. bind() {
  37583. const bindings = this._bindings;
  37584. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37585. bindings[ i ].bind();
  37586. }
  37587. }
  37588. unbind() {
  37589. const bindings = this._bindings;
  37590. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37591. bindings[ i ].unbind();
  37592. }
  37593. }
  37594. }
  37595. // Note: This class uses a State pattern on a per-method basis:
  37596. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37597. // prototype version of these methods with one that represents
  37598. // the bound state. When the property is not found, the methods
  37599. // become no-ops.
  37600. /**
  37601. * This holds a reference to a real property in the scene graph; used internally.
  37602. */
  37603. class PropertyBinding {
  37604. /**
  37605. * Constructs a new property binding.
  37606. *
  37607. * @param {Object} rootNode - The root node.
  37608. * @param {string} path - The path.
  37609. * @param {?Object} [parsedPath] - The parsed path.
  37610. */
  37611. constructor( rootNode, path, parsedPath ) {
  37612. /**
  37613. * The object path to the animated property.
  37614. *
  37615. * @type {string}
  37616. */
  37617. this.path = path;
  37618. /**
  37619. * An object holding information about the path.
  37620. *
  37621. * @type {Object}
  37622. */
  37623. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37624. /**
  37625. * The object owns the animated property.
  37626. *
  37627. * @type {?Object}
  37628. */
  37629. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37630. /**
  37631. * The root node.
  37632. *
  37633. * @type {Object3D|Skeleton}
  37634. */
  37635. this.rootNode = rootNode;
  37636. // initial state of these methods that calls 'bind'
  37637. this.getValue = this._getValue_unbound;
  37638. this.setValue = this._setValue_unbound;
  37639. }
  37640. /**
  37641. * Factory method for creating a property binding from the given parameters.
  37642. *
  37643. * @static
  37644. * @param {Object} root - The root node.
  37645. * @param {string} path - The path.
  37646. * @param {?Object} [parsedPath] - The parsed path.
  37647. * @return {PropertyBinding|Composite} The created property binding or composite.
  37648. */
  37649. static create( root, path, parsedPath ) {
  37650. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37651. return new PropertyBinding( root, path, parsedPath );
  37652. } else {
  37653. return new PropertyBinding.Composite( root, path, parsedPath );
  37654. }
  37655. }
  37656. /**
  37657. * Replaces spaces with underscores and removes unsupported characters from
  37658. * node names, to ensure compatibility with parseTrackName().
  37659. *
  37660. * @param {string} name - Node name to be sanitized.
  37661. * @return {string} The sanitized node name.
  37662. */
  37663. static sanitizeNodeName( name ) {
  37664. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37665. }
  37666. /**
  37667. * Parses the given track name (an object path to an animated property) and
  37668. * returns an object with information about the path. Matches strings in the following forms:
  37669. *
  37670. * - nodeName.property
  37671. * - nodeName.property[accessor]
  37672. * - nodeName.material.property[accessor]
  37673. * - uuid.property[accessor]
  37674. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37675. * - parentName/nodeName.property
  37676. * - parentName/parentName/nodeName.property[index]
  37677. * - .bone[Armature.DEF_cog].position
  37678. * - scene:helium_balloon_model:helium_balloon_model.position
  37679. *
  37680. * @static
  37681. * @param {string} trackName - The track name to parse.
  37682. * @return {Object} The parsed track name as an object.
  37683. */
  37684. static parseTrackName( trackName ) {
  37685. const matches = _trackRe.exec( trackName );
  37686. if ( matches === null ) {
  37687. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37688. }
  37689. const results = {
  37690. // directoryName: matches[ 1 ], // (tschw) currently unused
  37691. nodeName: matches[ 2 ],
  37692. objectName: matches[ 3 ],
  37693. objectIndex: matches[ 4 ],
  37694. propertyName: matches[ 5 ], // required
  37695. propertyIndex: matches[ 6 ]
  37696. };
  37697. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37698. if ( lastDot !== undefined && lastDot !== -1 ) {
  37699. const objectName = results.nodeName.substring( lastDot + 1 );
  37700. // Object names must be checked against an allowlist. Otherwise, there
  37701. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37702. // 'bar' could be the objectName, or part of a nodeName (which can
  37703. // include '.' characters).
  37704. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37705. results.nodeName = results.nodeName.substring( 0, lastDot );
  37706. results.objectName = objectName;
  37707. }
  37708. }
  37709. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37710. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37711. }
  37712. return results;
  37713. }
  37714. /**
  37715. * Searches for a node in the hierarchy of the given root object by the given
  37716. * node name.
  37717. *
  37718. * @static
  37719. * @param {Object} root - The root object.
  37720. * @param {string|number} nodeName - The name of the node.
  37721. * @return {?Object} The found node. Returns `null` if no object was found.
  37722. */
  37723. static findNode( root, nodeName ) {
  37724. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37725. return root;
  37726. }
  37727. // search into skeleton bones.
  37728. if ( root.skeleton ) {
  37729. const bone = root.skeleton.getBoneByName( nodeName );
  37730. if ( bone !== undefined ) {
  37731. return bone;
  37732. }
  37733. }
  37734. // search into node subtree.
  37735. if ( root.children ) {
  37736. const searchNodeSubtree = function ( children ) {
  37737. for ( let i = 0; i < children.length; i ++ ) {
  37738. const childNode = children[ i ];
  37739. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37740. return childNode;
  37741. }
  37742. const result = searchNodeSubtree( childNode.children );
  37743. if ( result ) return result;
  37744. }
  37745. return null;
  37746. };
  37747. const subTreeNode = searchNodeSubtree( root.children );
  37748. if ( subTreeNode ) {
  37749. return subTreeNode;
  37750. }
  37751. }
  37752. return null;
  37753. }
  37754. // these are used to "bind" a nonexistent property
  37755. _getValue_unavailable() {}
  37756. _setValue_unavailable() {}
  37757. // Getters
  37758. _getValue_direct( buffer, offset ) {
  37759. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37760. }
  37761. _getValue_array( buffer, offset ) {
  37762. const source = this.resolvedProperty;
  37763. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37764. buffer[ offset ++ ] = source[ i ];
  37765. }
  37766. }
  37767. _getValue_arrayElement( buffer, offset ) {
  37768. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37769. }
  37770. _getValue_toArray( buffer, offset ) {
  37771. this.resolvedProperty.toArray( buffer, offset );
  37772. }
  37773. // Direct
  37774. _setValue_direct( buffer, offset ) {
  37775. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37776. }
  37777. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37778. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37779. this.targetObject.needsUpdate = true;
  37780. }
  37781. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37782. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37783. this.targetObject.matrixWorldNeedsUpdate = true;
  37784. }
  37785. // EntireArray
  37786. _setValue_array( buffer, offset ) {
  37787. const dest = this.resolvedProperty;
  37788. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37789. dest[ i ] = buffer[ offset ++ ];
  37790. }
  37791. }
  37792. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37793. const dest = this.resolvedProperty;
  37794. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37795. dest[ i ] = buffer[ offset ++ ];
  37796. }
  37797. this.targetObject.needsUpdate = true;
  37798. }
  37799. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37800. const dest = this.resolvedProperty;
  37801. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37802. dest[ i ] = buffer[ offset ++ ];
  37803. }
  37804. this.targetObject.matrixWorldNeedsUpdate = true;
  37805. }
  37806. // ArrayElement
  37807. _setValue_arrayElement( buffer, offset ) {
  37808. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37809. }
  37810. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37811. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37812. this.targetObject.needsUpdate = true;
  37813. }
  37814. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37815. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37816. this.targetObject.matrixWorldNeedsUpdate = true;
  37817. }
  37818. // HasToFromArray
  37819. _setValue_fromArray( buffer, offset ) {
  37820. this.resolvedProperty.fromArray( buffer, offset );
  37821. }
  37822. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37823. this.resolvedProperty.fromArray( buffer, offset );
  37824. this.targetObject.needsUpdate = true;
  37825. }
  37826. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37827. this.resolvedProperty.fromArray( buffer, offset );
  37828. this.targetObject.matrixWorldNeedsUpdate = true;
  37829. }
  37830. _getValue_unbound( targetArray, offset ) {
  37831. this.bind();
  37832. this.getValue( targetArray, offset );
  37833. }
  37834. _setValue_unbound( sourceArray, offset ) {
  37835. this.bind();
  37836. this.setValue( sourceArray, offset );
  37837. }
  37838. /**
  37839. * Creates a getter / setter pair for the property tracked by this binding.
  37840. */
  37841. bind() {
  37842. let targetObject = this.node;
  37843. const parsedPath = this.parsedPath;
  37844. const objectName = parsedPath.objectName;
  37845. const propertyName = parsedPath.propertyName;
  37846. let propertyIndex = parsedPath.propertyIndex;
  37847. if ( ! targetObject ) {
  37848. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37849. this.node = targetObject;
  37850. }
  37851. // set fail state so we can just 'return' on error
  37852. this.getValue = this._getValue_unavailable;
  37853. this.setValue = this._setValue_unavailable;
  37854. // ensure there is a value node
  37855. if ( ! targetObject ) {
  37856. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37857. return;
  37858. }
  37859. if ( objectName ) {
  37860. let objectIndex = parsedPath.objectIndex;
  37861. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37862. switch ( objectName ) {
  37863. case 'materials':
  37864. if ( ! targetObject.material ) {
  37865. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37866. return;
  37867. }
  37868. if ( ! targetObject.material.materials ) {
  37869. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37870. return;
  37871. }
  37872. targetObject = targetObject.material.materials;
  37873. break;
  37874. case 'bones':
  37875. if ( ! targetObject.skeleton ) {
  37876. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37877. return;
  37878. }
  37879. // potential future optimization: skip this if propertyIndex is already an integer
  37880. // and convert the integer string to a true integer.
  37881. targetObject = targetObject.skeleton.bones;
  37882. // support resolving morphTarget names into indices.
  37883. for ( let i = 0; i < targetObject.length; i ++ ) {
  37884. if ( targetObject[ i ].name === objectIndex ) {
  37885. objectIndex = i;
  37886. break;
  37887. }
  37888. }
  37889. break;
  37890. case 'map':
  37891. if ( 'map' in targetObject ) {
  37892. targetObject = targetObject.map;
  37893. break;
  37894. }
  37895. if ( ! targetObject.material ) {
  37896. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37897. return;
  37898. }
  37899. if ( ! targetObject.material.map ) {
  37900. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37901. return;
  37902. }
  37903. targetObject = targetObject.material.map;
  37904. break;
  37905. default:
  37906. if ( targetObject[ objectName ] === undefined ) {
  37907. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  37908. return;
  37909. }
  37910. targetObject = targetObject[ objectName ];
  37911. }
  37912. if ( objectIndex !== undefined ) {
  37913. if ( targetObject[ objectIndex ] === undefined ) {
  37914. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37915. return;
  37916. }
  37917. targetObject = targetObject[ objectIndex ];
  37918. }
  37919. }
  37920. // resolve property
  37921. const nodeProperty = targetObject[ propertyName ];
  37922. if ( nodeProperty === undefined ) {
  37923. const nodeName = parsedPath.nodeName;
  37924. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  37925. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37926. return;
  37927. }
  37928. // determine versioning scheme
  37929. let versioning = this.Versioning.None;
  37930. this.targetObject = targetObject;
  37931. if ( targetObject.isMaterial === true ) {
  37932. versioning = this.Versioning.NeedsUpdate;
  37933. } else if ( targetObject.isObject3D === true ) {
  37934. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37935. }
  37936. // determine how the property gets bound
  37937. let bindingType = this.BindingType.Direct;
  37938. if ( propertyIndex !== undefined ) {
  37939. // access a sub element of the property array (only primitives are supported right now)
  37940. if ( propertyName === 'morphTargetInfluences' ) {
  37941. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37942. // support resolving morphTarget names into indices.
  37943. if ( ! targetObject.geometry ) {
  37944. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37945. return;
  37946. }
  37947. if ( ! targetObject.geometry.morphAttributes ) {
  37948. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37949. return;
  37950. }
  37951. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37952. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37953. }
  37954. }
  37955. bindingType = this.BindingType.ArrayElement;
  37956. this.resolvedProperty = nodeProperty;
  37957. this.propertyIndex = propertyIndex;
  37958. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37959. // must use copy for Object3D.Euler/Quaternion
  37960. bindingType = this.BindingType.HasFromToArray;
  37961. this.resolvedProperty = nodeProperty;
  37962. } else if ( Array.isArray( nodeProperty ) ) {
  37963. bindingType = this.BindingType.EntireArray;
  37964. this.resolvedProperty = nodeProperty;
  37965. } else {
  37966. this.propertyName = propertyName;
  37967. }
  37968. // select getter / setter
  37969. this.getValue = this.GetterByBindingType[ bindingType ];
  37970. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37971. }
  37972. /**
  37973. * Unbinds the property.
  37974. */
  37975. unbind() {
  37976. this.node = null;
  37977. // back to the prototype version of getValue / setValue
  37978. // note: avoiding to mutate the shape of 'this' via 'delete'
  37979. this.getValue = this._getValue_unbound;
  37980. this.setValue = this._setValue_unbound;
  37981. }
  37982. }
  37983. PropertyBinding.Composite = Composite;
  37984. PropertyBinding.prototype.BindingType = {
  37985. Direct: 0,
  37986. EntireArray: 1,
  37987. ArrayElement: 2,
  37988. HasFromToArray: 3
  37989. };
  37990. PropertyBinding.prototype.Versioning = {
  37991. None: 0,
  37992. NeedsUpdate: 1,
  37993. MatrixWorldNeedsUpdate: 2
  37994. };
  37995. PropertyBinding.prototype.GetterByBindingType = [
  37996. PropertyBinding.prototype._getValue_direct,
  37997. PropertyBinding.prototype._getValue_array,
  37998. PropertyBinding.prototype._getValue_arrayElement,
  37999. PropertyBinding.prototype._getValue_toArray,
  38000. ];
  38001. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38002. [
  38003. // Direct
  38004. PropertyBinding.prototype._setValue_direct,
  38005. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38006. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38007. ], [
  38008. // EntireArray
  38009. PropertyBinding.prototype._setValue_array,
  38010. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38011. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38012. ], [
  38013. // ArrayElement
  38014. PropertyBinding.prototype._setValue_arrayElement,
  38015. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38016. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38017. ], [
  38018. // HasToFromArray
  38019. PropertyBinding.prototype._setValue_fromArray,
  38020. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38021. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38022. ]
  38023. ];
  38024. /**
  38025. * A group of objects that receives a shared animation state.
  38026. *
  38027. * Usage:
  38028. *
  38029. * - Add objects you would otherwise pass as 'root' to the
  38030. * constructor or the .clipAction method of AnimationMixer.
  38031. * - Instead pass this object as 'root'.
  38032. * - You can also add and remove objects later when the mixer is running.
  38033. *
  38034. * Note:
  38035. *
  38036. * - Objects of this class appear as one object to the mixer,
  38037. * so cache control of the individual objects must be done on the group.
  38038. *
  38039. * Limitation:
  38040. *
  38041. * - The animated properties must be compatible among the all objects in the group.
  38042. * - A single property can either be controlled through a target group or directly, but not both.
  38043. */
  38044. class AnimationObjectGroup {
  38045. /**
  38046. * Constructs a new animation group.
  38047. *
  38048. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38049. */
  38050. constructor() {
  38051. /**
  38052. * This flag can be used for type testing.
  38053. *
  38054. * @type {boolean}
  38055. * @readonly
  38056. * @default true
  38057. */
  38058. this.isAnimationObjectGroup = true;
  38059. /**
  38060. * The UUID of the 3D object.
  38061. *
  38062. * @type {string}
  38063. * @readonly
  38064. */
  38065. this.uuid = generateUUID();
  38066. // cached objects followed by the active ones
  38067. this._objects = Array.prototype.slice.call( arguments );
  38068. this.nCachedObjects_ = 0; // threshold
  38069. // note: read by PropertyBinding.Composite
  38070. const indices = {};
  38071. this._indicesByUUID = indices; // for bookkeeping
  38072. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38073. indices[ arguments[ i ].uuid ] = i;
  38074. }
  38075. this._paths = []; // inside: string
  38076. this._parsedPaths = []; // inside: { we don't care, here }
  38077. this._bindings = []; // inside: Array< PropertyBinding >
  38078. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38079. const scope = this;
  38080. this.stats = {
  38081. objects: {
  38082. get total() {
  38083. return scope._objects.length;
  38084. },
  38085. get inUse() {
  38086. return this.total - scope.nCachedObjects_;
  38087. }
  38088. },
  38089. get bindingsPerObject() {
  38090. return scope._bindings.length;
  38091. }
  38092. };
  38093. }
  38094. /**
  38095. * Adds an arbitrary number of objects to this animation group.
  38096. *
  38097. * @param {...Object3D} arguments - The 3D objects to add.
  38098. */
  38099. add() {
  38100. const objects = this._objects,
  38101. indicesByUUID = this._indicesByUUID,
  38102. paths = this._paths,
  38103. parsedPaths = this._parsedPaths,
  38104. bindings = this._bindings,
  38105. nBindings = bindings.length;
  38106. let knownObject = undefined,
  38107. nObjects = objects.length,
  38108. nCachedObjects = this.nCachedObjects_;
  38109. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38110. const object = arguments[ i ],
  38111. uuid = object.uuid;
  38112. let index = indicesByUUID[ uuid ];
  38113. if ( index === undefined ) {
  38114. // unknown object -> add it to the ACTIVE region
  38115. index = nObjects ++;
  38116. indicesByUUID[ uuid ] = index;
  38117. objects.push( object );
  38118. // accounting is done, now do the same for all bindings
  38119. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38120. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38121. }
  38122. } else if ( index < nCachedObjects ) {
  38123. knownObject = objects[ index ];
  38124. // move existing object to the ACTIVE region
  38125. const firstActiveIndex = -- nCachedObjects,
  38126. lastCachedObject = objects[ firstActiveIndex ];
  38127. indicesByUUID[ lastCachedObject.uuid ] = index;
  38128. objects[ index ] = lastCachedObject;
  38129. indicesByUUID[ uuid ] = firstActiveIndex;
  38130. objects[ firstActiveIndex ] = object;
  38131. // accounting is done, now do the same for all bindings
  38132. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38133. const bindingsForPath = bindings[ j ],
  38134. lastCached = bindingsForPath[ firstActiveIndex ];
  38135. let binding = bindingsForPath[ index ];
  38136. bindingsForPath[ index ] = lastCached;
  38137. if ( binding === undefined ) {
  38138. // since we do not bother to create new bindings
  38139. // for objects that are cached, the binding may
  38140. // or may not exist
  38141. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38142. }
  38143. bindingsForPath[ firstActiveIndex ] = binding;
  38144. }
  38145. } else if ( objects[ index ] !== knownObject ) {
  38146. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38147. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38148. } // else the object is already where we want it to be
  38149. } // for arguments
  38150. this.nCachedObjects_ = nCachedObjects;
  38151. }
  38152. /**
  38153. * Removes an arbitrary number of objects to this animation group
  38154. *
  38155. * @param {...Object3D} arguments - The 3D objects to remove.
  38156. */
  38157. remove() {
  38158. const objects = this._objects,
  38159. indicesByUUID = this._indicesByUUID,
  38160. bindings = this._bindings,
  38161. nBindings = bindings.length;
  38162. let nCachedObjects = this.nCachedObjects_;
  38163. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38164. const object = arguments[ i ],
  38165. uuid = object.uuid,
  38166. index = indicesByUUID[ uuid ];
  38167. if ( index !== undefined && index >= nCachedObjects ) {
  38168. // move existing object into the CACHED region
  38169. const lastCachedIndex = nCachedObjects ++,
  38170. firstActiveObject = objects[ lastCachedIndex ];
  38171. indicesByUUID[ firstActiveObject.uuid ] = index;
  38172. objects[ index ] = firstActiveObject;
  38173. indicesByUUID[ uuid ] = lastCachedIndex;
  38174. objects[ lastCachedIndex ] = object;
  38175. // accounting is done, now do the same for all bindings
  38176. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38177. const bindingsForPath = bindings[ j ],
  38178. firstActive = bindingsForPath[ lastCachedIndex ],
  38179. binding = bindingsForPath[ index ];
  38180. bindingsForPath[ index ] = firstActive;
  38181. bindingsForPath[ lastCachedIndex ] = binding;
  38182. }
  38183. }
  38184. } // for arguments
  38185. this.nCachedObjects_ = nCachedObjects;
  38186. }
  38187. /**
  38188. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38189. *
  38190. * @param {...Object3D} arguments - The 3D objects to uncache.
  38191. */
  38192. uncache() {
  38193. const objects = this._objects,
  38194. indicesByUUID = this._indicesByUUID,
  38195. bindings = this._bindings,
  38196. nBindings = bindings.length;
  38197. let nCachedObjects = this.nCachedObjects_,
  38198. nObjects = objects.length;
  38199. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38200. const object = arguments[ i ],
  38201. uuid = object.uuid,
  38202. index = indicesByUUID[ uuid ];
  38203. if ( index !== undefined ) {
  38204. delete indicesByUUID[ uuid ];
  38205. if ( index < nCachedObjects ) {
  38206. // object is cached, shrink the CACHED region
  38207. const firstActiveIndex = -- nCachedObjects,
  38208. lastCachedObject = objects[ firstActiveIndex ],
  38209. lastIndex = -- nObjects,
  38210. lastObject = objects[ lastIndex ];
  38211. // last cached object takes this object's place
  38212. indicesByUUID[ lastCachedObject.uuid ] = index;
  38213. objects[ index ] = lastCachedObject;
  38214. // last object goes to the activated slot and pop
  38215. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38216. objects[ firstActiveIndex ] = lastObject;
  38217. objects.pop();
  38218. // accounting is done, now do the same for all bindings
  38219. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38220. const bindingsForPath = bindings[ j ],
  38221. lastCached = bindingsForPath[ firstActiveIndex ],
  38222. last = bindingsForPath[ lastIndex ];
  38223. bindingsForPath[ index ] = lastCached;
  38224. bindingsForPath[ firstActiveIndex ] = last;
  38225. bindingsForPath.pop();
  38226. }
  38227. } else {
  38228. // object is active, just swap with the last and pop
  38229. const lastIndex = -- nObjects,
  38230. lastObject = objects[ lastIndex ];
  38231. if ( lastIndex > 0 ) {
  38232. indicesByUUID[ lastObject.uuid ] = index;
  38233. }
  38234. objects[ index ] = lastObject;
  38235. objects.pop();
  38236. // accounting is done, now do the same for all bindings
  38237. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38238. const bindingsForPath = bindings[ j ];
  38239. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38240. bindingsForPath.pop();
  38241. }
  38242. } // cached or active
  38243. } // if object is known
  38244. } // for arguments
  38245. this.nCachedObjects_ = nCachedObjects;
  38246. }
  38247. // Internal interface used by befriended PropertyBinding.Composite:
  38248. subscribe_( path, parsedPath ) {
  38249. // returns an array of bindings for the given path that is changed
  38250. // according to the contained objects in the group
  38251. const indicesByPath = this._bindingsIndicesByPath;
  38252. let index = indicesByPath[ path ];
  38253. const bindings = this._bindings;
  38254. if ( index !== undefined ) return bindings[ index ];
  38255. const paths = this._paths,
  38256. parsedPaths = this._parsedPaths,
  38257. objects = this._objects,
  38258. nObjects = objects.length,
  38259. nCachedObjects = this.nCachedObjects_,
  38260. bindingsForPath = new Array( nObjects );
  38261. index = bindings.length;
  38262. indicesByPath[ path ] = index;
  38263. paths.push( path );
  38264. parsedPaths.push( parsedPath );
  38265. bindings.push( bindingsForPath );
  38266. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38267. const object = objects[ i ];
  38268. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38269. }
  38270. return bindingsForPath;
  38271. }
  38272. unsubscribe_( path ) {
  38273. // tells the group to forget about a property path and no longer
  38274. // update the array previously obtained with 'subscribe_'
  38275. const indicesByPath = this._bindingsIndicesByPath,
  38276. index = indicesByPath[ path ];
  38277. if ( index !== undefined ) {
  38278. const paths = this._paths,
  38279. parsedPaths = this._parsedPaths,
  38280. bindings = this._bindings,
  38281. lastBindingsIndex = bindings.length - 1,
  38282. lastBindings = bindings[ lastBindingsIndex ],
  38283. lastBindingsPath = path[ lastBindingsIndex ];
  38284. indicesByPath[ lastBindingsPath ] = index;
  38285. bindings[ index ] = lastBindings;
  38286. bindings.pop();
  38287. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38288. parsedPaths.pop();
  38289. paths[ index ] = paths[ lastBindingsIndex ];
  38290. paths.pop();
  38291. }
  38292. }
  38293. }
  38294. /**
  38295. * An instance of `AnimationAction` schedules the playback of an animation which is
  38296. * stored in {@link AnimationClip}.
  38297. */
  38298. class AnimationAction {
  38299. /**
  38300. * Constructs a new animation action.
  38301. *
  38302. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38303. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38304. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38305. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38306. */
  38307. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38308. this._mixer = mixer;
  38309. this._clip = clip;
  38310. this._localRoot = localRoot;
  38311. /**
  38312. * Defines how the animation is blended/combined when two or more animations
  38313. * are simultaneously played.
  38314. *
  38315. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38316. */
  38317. this.blendMode = blendMode;
  38318. const tracks = clip.tracks,
  38319. nTracks = tracks.length,
  38320. interpolants = new Array( nTracks );
  38321. const interpolantSettings = {
  38322. endingStart: ZeroCurvatureEnding,
  38323. endingEnd: ZeroCurvatureEnding
  38324. };
  38325. for ( let i = 0; i !== nTracks; ++ i ) {
  38326. const interpolant = tracks[ i ].createInterpolant( null );
  38327. interpolants[ i ] = interpolant;
  38328. interpolant.settings = interpolantSettings;
  38329. }
  38330. this._interpolantSettings = interpolantSettings;
  38331. this._interpolants = interpolants; // bound by the mixer
  38332. // inside: PropertyMixer (managed by the mixer)
  38333. this._propertyBindings = new Array( nTracks );
  38334. this._cacheIndex = null; // for the memory manager
  38335. this._byClipCacheIndex = null; // for the memory manager
  38336. this._timeScaleInterpolant = null;
  38337. this._weightInterpolant = null;
  38338. /**
  38339. * The loop mode, set via {@link AnimationAction#setLoop}.
  38340. *
  38341. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38342. * @default LoopRepeat
  38343. */
  38344. this.loop = LoopRepeat;
  38345. this._loopCount = -1;
  38346. // global mixer time when the action is to be started
  38347. // it's set back to 'null' upon start of the action
  38348. this._startTime = null;
  38349. /**
  38350. * The local time of this action (in seconds, starting with `0`).
  38351. *
  38352. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38353. * loop state).
  38354. *
  38355. * @type {number}
  38356. * @default Infinity
  38357. */
  38358. this.time = 0;
  38359. /**
  38360. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38361. * animation to pause. Negative values cause the animation to play backwards.
  38362. *
  38363. * @type {number}
  38364. * @default 1
  38365. */
  38366. this.timeScale = 1;
  38367. this._effectiveTimeScale = 1;
  38368. /**
  38369. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38370. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38371. * several actions.
  38372. *
  38373. * @type {number}
  38374. * @default 1
  38375. */
  38376. this.weight = 1;
  38377. this._effectiveWeight = 1;
  38378. /**
  38379. * The number of repetitions of the performed clip over the course of this action.
  38380. * Can be set via {@link AnimationAction#setLoop}.
  38381. *
  38382. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38383. * `THREE:LoopOnce`.
  38384. *
  38385. * @type {number}
  38386. * @default Infinity
  38387. */
  38388. this.repetitions = Infinity;
  38389. /**
  38390. * If set to `true`, the playback of the action is paused.
  38391. *
  38392. * @type {boolean}
  38393. * @default false
  38394. */
  38395. this.paused = false;
  38396. /**
  38397. * If set to `false`, the action is disabled so it has no impact.
  38398. *
  38399. * When the action is re-enabled, the animation continues from its current
  38400. * time (setting `enabled` to `false` doesn't reset the action).
  38401. *
  38402. * @type {boolean}
  38403. * @default true
  38404. */
  38405. this.enabled = true;
  38406. /**
  38407. * If set to true the animation will automatically be paused on its last frame.
  38408. *
  38409. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38410. * to `false` when the last loop of the action has finished, so that this action has
  38411. * no further impact.
  38412. *
  38413. * Note: This member has no impact if the action is interrupted (it
  38414. * has only an effect if its last loop has really finished).
  38415. *
  38416. * @type {boolean}
  38417. * @default false
  38418. */
  38419. this.clampWhenFinished = false;
  38420. /**
  38421. * Enables smooth interpolation without separate clips for start, loop and end.
  38422. *
  38423. * @type {boolean}
  38424. * @default true
  38425. */
  38426. this.zeroSlopeAtStart = true;
  38427. /**
  38428. * Enables smooth interpolation without separate clips for start, loop and end.
  38429. *
  38430. * @type {boolean}
  38431. * @default true
  38432. */
  38433. this.zeroSlopeAtEnd = true;
  38434. }
  38435. /**
  38436. * Starts the playback of the animation.
  38437. *
  38438. * @return {AnimationAction} A reference to this animation action.
  38439. */
  38440. play() {
  38441. this._mixer._activateAction( this );
  38442. return this;
  38443. }
  38444. /**
  38445. * Stops the playback of the animation.
  38446. *
  38447. * @return {AnimationAction} A reference to this animation action.
  38448. */
  38449. stop() {
  38450. this._mixer._deactivateAction( this );
  38451. return this.reset();
  38452. }
  38453. /**
  38454. * Resets the playback of the animation.
  38455. *
  38456. * @return {AnimationAction} A reference to this animation action.
  38457. */
  38458. reset() {
  38459. this.paused = false;
  38460. this.enabled = true;
  38461. this.time = 0; // restart clip
  38462. this._loopCount = -1;// forget previous loops
  38463. this._startTime = null;// forget scheduling
  38464. return this.stopFading().stopWarping();
  38465. }
  38466. /**
  38467. * Returns `true` if the animation is running.
  38468. *
  38469. * @return {boolean} Whether the animation is running or not.
  38470. */
  38471. isRunning() {
  38472. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38473. this._startTime === null && this._mixer._isActiveAction( this );
  38474. }
  38475. /**
  38476. * Returns `true` when {@link AnimationAction#play} has been called.
  38477. *
  38478. * @return {boolean} Whether the animation is scheduled or not.
  38479. */
  38480. isScheduled() {
  38481. return this._mixer._isActiveAction( this );
  38482. }
  38483. /**
  38484. * Defines the time when the animation should start.
  38485. *
  38486. * @param {number} time - The start time in seconds.
  38487. * @return {AnimationAction} A reference to this animation action.
  38488. */
  38489. startAt( time ) {
  38490. this._startTime = time;
  38491. return this;
  38492. }
  38493. /**
  38494. * Configures the loop settings for this action.
  38495. *
  38496. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38497. * @param {number} repetitions - The number of repetitions.
  38498. * @return {AnimationAction} A reference to this animation action.
  38499. */
  38500. setLoop( mode, repetitions ) {
  38501. this.loop = mode;
  38502. this.repetitions = repetitions;
  38503. return this;
  38504. }
  38505. /**
  38506. * Sets the effective weight of this action.
  38507. *
  38508. * An action has no effect and thus an effective weight of zero when the
  38509. * action is disabled.
  38510. *
  38511. * @param {number} weight - The weight to set.
  38512. * @return {AnimationAction} A reference to this animation action.
  38513. */
  38514. setEffectiveWeight( weight ) {
  38515. this.weight = weight;
  38516. // note: same logic as when updated at runtime
  38517. this._effectiveWeight = this.enabled ? weight : 0;
  38518. return this.stopFading();
  38519. }
  38520. /**
  38521. * Returns the effective weight of this action.
  38522. *
  38523. * @return {number} The effective weight.
  38524. */
  38525. getEffectiveWeight() {
  38526. return this._effectiveWeight;
  38527. }
  38528. /**
  38529. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38530. * within the passed time interval.
  38531. *
  38532. * @param {number} duration - The duration of the fade.
  38533. * @return {AnimationAction} A reference to this animation action.
  38534. */
  38535. fadeIn( duration ) {
  38536. return this._scheduleFading( duration, 0, 1 );
  38537. }
  38538. /**
  38539. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38540. * within the passed time interval.
  38541. *
  38542. * @param {number} duration - The duration of the fade.
  38543. * @return {AnimationAction} A reference to this animation action.
  38544. */
  38545. fadeOut( duration ) {
  38546. return this._scheduleFading( duration, 1, 0 );
  38547. }
  38548. /**
  38549. * Causes this action to fade in and the given action to fade out,
  38550. * within the passed time interval.
  38551. *
  38552. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38553. * @param {number} duration - The duration of the fade.
  38554. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38555. * @return {AnimationAction} A reference to this animation action.
  38556. */
  38557. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38558. fadeOutAction.fadeOut( duration );
  38559. this.fadeIn( duration );
  38560. if ( warp === true ) {
  38561. const fadeInDuration = this._clip.duration,
  38562. fadeOutDuration = fadeOutAction._clip.duration,
  38563. startEndRatio = fadeOutDuration / fadeInDuration,
  38564. endStartRatio = fadeInDuration / fadeOutDuration;
  38565. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38566. this.warp( endStartRatio, 1.0, duration );
  38567. }
  38568. return this;
  38569. }
  38570. /**
  38571. * Causes this action to fade out and the given action to fade in,
  38572. * within the passed time interval.
  38573. *
  38574. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38575. * @param {number} duration - The duration of the fade.
  38576. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38577. * @return {AnimationAction} A reference to this animation action.
  38578. */
  38579. crossFadeTo( fadeInAction, duration, warp = false ) {
  38580. return fadeInAction.crossFadeFrom( this, duration, warp );
  38581. }
  38582. /**
  38583. * Stops any fading which is applied to this action.
  38584. *
  38585. * @return {AnimationAction} A reference to this animation action.
  38586. */
  38587. stopFading() {
  38588. const weightInterpolant = this._weightInterpolant;
  38589. if ( weightInterpolant !== null ) {
  38590. this._weightInterpolant = null;
  38591. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38592. }
  38593. return this;
  38594. }
  38595. /**
  38596. * Sets the effective time scale of this action.
  38597. *
  38598. * An action has no effect and thus an effective time scale of zero when the
  38599. * action is paused.
  38600. *
  38601. * @param {number} timeScale - The time scale to set.
  38602. * @return {AnimationAction} A reference to this animation action.
  38603. */
  38604. setEffectiveTimeScale( timeScale ) {
  38605. this.timeScale = timeScale;
  38606. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38607. return this.stopWarping();
  38608. }
  38609. /**
  38610. * Returns the effective time scale of this action.
  38611. *
  38612. * @return {number} The effective time scale.
  38613. */
  38614. getEffectiveTimeScale() {
  38615. return this._effectiveTimeScale;
  38616. }
  38617. /**
  38618. * Sets the duration for a single loop of this action.
  38619. *
  38620. * @param {number} duration - The duration to set.
  38621. * @return {AnimationAction} A reference to this animation action.
  38622. */
  38623. setDuration( duration ) {
  38624. this.timeScale = this._clip.duration / duration;
  38625. return this.stopWarping();
  38626. }
  38627. /**
  38628. * Synchronizes this action with the passed other action.
  38629. *
  38630. * @param {AnimationAction} action - The action to sync with.
  38631. * @return {AnimationAction} A reference to this animation action.
  38632. */
  38633. syncWith( action ) {
  38634. this.time = action.time;
  38635. this.timeScale = action.timeScale;
  38636. return this.stopWarping();
  38637. }
  38638. /**
  38639. * Decelerates this animation's speed to `0` within the passed time interval.
  38640. *
  38641. * @param {number} duration - The duration.
  38642. * @return {AnimationAction} A reference to this animation action.
  38643. */
  38644. halt( duration ) {
  38645. return this.warp( this._effectiveTimeScale, 0, duration );
  38646. }
  38647. /**
  38648. * Changes the playback speed, within the passed time interval, by modifying
  38649. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38650. * `endTimeScale`.
  38651. *
  38652. * @param {number} startTimeScale - The start time scale.
  38653. * @param {number} endTimeScale - The end time scale.
  38654. * @param {number} duration - The duration.
  38655. * @return {AnimationAction} A reference to this animation action.
  38656. */
  38657. warp( startTimeScale, endTimeScale, duration ) {
  38658. const mixer = this._mixer,
  38659. now = mixer.time,
  38660. timeScale = this.timeScale;
  38661. let interpolant = this._timeScaleInterpolant;
  38662. if ( interpolant === null ) {
  38663. interpolant = mixer._lendControlInterpolant();
  38664. this._timeScaleInterpolant = interpolant;
  38665. }
  38666. const times = interpolant.parameterPositions,
  38667. values = interpolant.sampleValues;
  38668. times[ 0 ] = now;
  38669. times[ 1 ] = now + duration;
  38670. values[ 0 ] = startTimeScale / timeScale;
  38671. values[ 1 ] = endTimeScale / timeScale;
  38672. return this;
  38673. }
  38674. /**
  38675. * Stops any scheduled warping which is applied to this action.
  38676. *
  38677. * @return {AnimationAction} A reference to this animation action.
  38678. */
  38679. stopWarping() {
  38680. const timeScaleInterpolant = this._timeScaleInterpolant;
  38681. if ( timeScaleInterpolant !== null ) {
  38682. this._timeScaleInterpolant = null;
  38683. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38684. }
  38685. return this;
  38686. }
  38687. /**
  38688. * Returns the animation mixer of this animation action.
  38689. *
  38690. * @return {AnimationMixer} The animation mixer.
  38691. */
  38692. getMixer() {
  38693. return this._mixer;
  38694. }
  38695. /**
  38696. * Returns the animation clip of this animation action.
  38697. *
  38698. * @return {AnimationClip} The animation clip.
  38699. */
  38700. getClip() {
  38701. return this._clip;
  38702. }
  38703. /**
  38704. * Returns the root object of this animation action.
  38705. *
  38706. * @return {Object3D} The root object.
  38707. */
  38708. getRoot() {
  38709. return this._localRoot || this._mixer._root;
  38710. }
  38711. // Internal
  38712. _update( time, deltaTime, timeDirection, accuIndex ) {
  38713. // called by the mixer
  38714. if ( ! this.enabled ) {
  38715. // call ._updateWeight() to update ._effectiveWeight
  38716. this._updateWeight( time );
  38717. return;
  38718. }
  38719. const startTime = this._startTime;
  38720. if ( startTime !== null ) {
  38721. // check for scheduled start of action
  38722. const timeRunning = ( time - startTime ) * timeDirection;
  38723. if ( timeRunning < 0 || timeDirection === 0 ) {
  38724. deltaTime = 0;
  38725. } else {
  38726. this._startTime = null; // unschedule
  38727. deltaTime = timeDirection * timeRunning;
  38728. }
  38729. }
  38730. // apply time scale and advance time
  38731. deltaTime *= this._updateTimeScale( time );
  38732. const clipTime = this._updateTime( deltaTime );
  38733. // note: _updateTime may disable the action resulting in
  38734. // an effective weight of 0
  38735. const weight = this._updateWeight( time );
  38736. if ( weight > 0 ) {
  38737. const interpolants = this._interpolants;
  38738. const propertyMixers = this._propertyBindings;
  38739. switch ( this.blendMode ) {
  38740. case AdditiveAnimationBlendMode:
  38741. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38742. interpolants[ j ].evaluate( clipTime );
  38743. propertyMixers[ j ].accumulateAdditive( weight );
  38744. }
  38745. break;
  38746. case NormalAnimationBlendMode:
  38747. default:
  38748. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38749. interpolants[ j ].evaluate( clipTime );
  38750. propertyMixers[ j ].accumulate( accuIndex, weight );
  38751. }
  38752. }
  38753. }
  38754. }
  38755. _updateWeight( time ) {
  38756. let weight = 0;
  38757. if ( this.enabled ) {
  38758. weight = this.weight;
  38759. const interpolant = this._weightInterpolant;
  38760. if ( interpolant !== null ) {
  38761. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38762. weight *= interpolantValue;
  38763. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38764. this.stopFading();
  38765. if ( interpolantValue === 0 ) {
  38766. // faded out, disable
  38767. this.enabled = false;
  38768. }
  38769. }
  38770. }
  38771. }
  38772. this._effectiveWeight = weight;
  38773. return weight;
  38774. }
  38775. _updateTimeScale( time ) {
  38776. let timeScale = 0;
  38777. if ( ! this.paused ) {
  38778. timeScale = this.timeScale;
  38779. const interpolant = this._timeScaleInterpolant;
  38780. if ( interpolant !== null ) {
  38781. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38782. timeScale *= interpolantValue;
  38783. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38784. this.stopWarping();
  38785. if ( timeScale === 0 ) {
  38786. // motion has halted, pause
  38787. this.paused = true;
  38788. } else {
  38789. // warp done - apply final time scale
  38790. this.timeScale = timeScale;
  38791. }
  38792. }
  38793. }
  38794. }
  38795. this._effectiveTimeScale = timeScale;
  38796. return timeScale;
  38797. }
  38798. _updateTime( deltaTime ) {
  38799. const duration = this._clip.duration;
  38800. const loop = this.loop;
  38801. let time = this.time + deltaTime;
  38802. let loopCount = this._loopCount;
  38803. const pingPong = ( loop === LoopPingPong );
  38804. if ( deltaTime === 0 ) {
  38805. if ( loopCount === -1 ) return time;
  38806. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38807. }
  38808. if ( loop === LoopOnce ) {
  38809. if ( loopCount === -1 ) {
  38810. // just started
  38811. this._loopCount = 0;
  38812. this._setEndings( true, true, false );
  38813. }
  38814. handle_stop: {
  38815. if ( time >= duration ) {
  38816. time = duration;
  38817. } else if ( time < 0 ) {
  38818. time = 0;
  38819. } else {
  38820. this.time = time;
  38821. break handle_stop;
  38822. }
  38823. if ( this.clampWhenFinished ) this.paused = true;
  38824. else this.enabled = false;
  38825. this.time = time;
  38826. this._mixer.dispatchEvent( {
  38827. type: 'finished', action: this,
  38828. direction: deltaTime < 0 ? -1 : 1
  38829. } );
  38830. }
  38831. } else { // repetitive Repeat or PingPong
  38832. if ( loopCount === -1 ) {
  38833. // just started
  38834. if ( deltaTime >= 0 ) {
  38835. loopCount = 0;
  38836. this._setEndings( true, this.repetitions === 0, pingPong );
  38837. } else {
  38838. // when looping in reverse direction, the initial
  38839. // transition through zero counts as a repetition,
  38840. // so leave loopCount at -1
  38841. this._setEndings( this.repetitions === 0, true, pingPong );
  38842. }
  38843. }
  38844. if ( time >= duration || time < 0 ) {
  38845. // wrap around
  38846. const loopDelta = Math.floor( time / duration ); // signed
  38847. time -= duration * loopDelta;
  38848. loopCount += Math.abs( loopDelta );
  38849. const pending = this.repetitions - loopCount;
  38850. if ( pending <= 0 ) {
  38851. // have to stop (switch state, clamp time, fire event)
  38852. if ( this.clampWhenFinished ) this.paused = true;
  38853. else this.enabled = false;
  38854. time = deltaTime > 0 ? duration : 0;
  38855. this.time = time;
  38856. this._mixer.dispatchEvent( {
  38857. type: 'finished', action: this,
  38858. direction: deltaTime > 0 ? 1 : -1
  38859. } );
  38860. } else {
  38861. // keep running
  38862. if ( pending === 1 ) {
  38863. // entering the last round
  38864. const atStart = deltaTime < 0;
  38865. this._setEndings( atStart, ! atStart, pingPong );
  38866. } else {
  38867. this._setEndings( false, false, pingPong );
  38868. }
  38869. this._loopCount = loopCount;
  38870. this.time = time;
  38871. this._mixer.dispatchEvent( {
  38872. type: 'loop', action: this, loopDelta: loopDelta
  38873. } );
  38874. }
  38875. } else {
  38876. this.time = time;
  38877. }
  38878. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38879. // invert time for the "pong round"
  38880. return duration - time;
  38881. }
  38882. }
  38883. return time;
  38884. }
  38885. _setEndings( atStart, atEnd, pingPong ) {
  38886. const settings = this._interpolantSettings;
  38887. if ( pingPong ) {
  38888. settings.endingStart = ZeroSlopeEnding;
  38889. settings.endingEnd = ZeroSlopeEnding;
  38890. } else {
  38891. // assuming for LoopOnce atStart == atEnd == true
  38892. if ( atStart ) {
  38893. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38894. } else {
  38895. settings.endingStart = WrapAroundEnding;
  38896. }
  38897. if ( atEnd ) {
  38898. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38899. } else {
  38900. settings.endingEnd = WrapAroundEnding;
  38901. }
  38902. }
  38903. }
  38904. _scheduleFading( duration, weightNow, weightThen ) {
  38905. const mixer = this._mixer, now = mixer.time;
  38906. let interpolant = this._weightInterpolant;
  38907. if ( interpolant === null ) {
  38908. interpolant = mixer._lendControlInterpolant();
  38909. this._weightInterpolant = interpolant;
  38910. }
  38911. const times = interpolant.parameterPositions,
  38912. values = interpolant.sampleValues;
  38913. times[ 0 ] = now;
  38914. values[ 0 ] = weightNow;
  38915. times[ 1 ] = now + duration;
  38916. values[ 1 ] = weightThen;
  38917. return this;
  38918. }
  38919. }
  38920. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38921. /**
  38922. * `AnimationMixer` is a player for animations on a particular object in
  38923. * the scene. When multiple objects in the scene are animated independently,
  38924. * one `AnimationMixer` may be used for each object.
  38925. */
  38926. class AnimationMixer extends EventDispatcher {
  38927. /**
  38928. * Constructs a new animation mixer.
  38929. *
  38930. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38931. */
  38932. constructor( root ) {
  38933. super();
  38934. this._root = root;
  38935. this._initMemoryManager();
  38936. this._accuIndex = 0;
  38937. /**
  38938. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38939. *
  38940. * @type {number}
  38941. * @default 0
  38942. */
  38943. this.time = 0;
  38944. /**
  38945. * A scaling factor for the global time.
  38946. *
  38947. * Note: Setting this member to `0` and later back to `1` is a
  38948. * possibility to pause/unpause all actions that are controlled by this
  38949. * mixer.
  38950. *
  38951. * @type {number}
  38952. * @default 1
  38953. */
  38954. this.timeScale = 1.0;
  38955. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  38956. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  38957. }
  38958. }
  38959. _bindAction( action, prototypeAction ) {
  38960. const root = action._localRoot || this._root,
  38961. tracks = action._clip.tracks,
  38962. nTracks = tracks.length,
  38963. bindings = action._propertyBindings,
  38964. interpolants = action._interpolants,
  38965. rootUuid = root.uuid,
  38966. bindingsByRoot = this._bindingsByRootAndName;
  38967. let bindingsByName = bindingsByRoot[ rootUuid ];
  38968. if ( bindingsByName === undefined ) {
  38969. bindingsByName = {};
  38970. bindingsByRoot[ rootUuid ] = bindingsByName;
  38971. }
  38972. for ( let i = 0; i !== nTracks; ++ i ) {
  38973. const track = tracks[ i ],
  38974. trackName = track.name;
  38975. let binding = bindingsByName[ trackName ];
  38976. if ( binding !== undefined ) {
  38977. ++ binding.referenceCount;
  38978. bindings[ i ] = binding;
  38979. } else {
  38980. binding = bindings[ i ];
  38981. if ( binding !== undefined ) {
  38982. // existing binding, make sure the cache knows
  38983. if ( binding._cacheIndex === null ) {
  38984. ++ binding.referenceCount;
  38985. this._addInactiveBinding( binding, rootUuid, trackName );
  38986. }
  38987. continue;
  38988. }
  38989. const path = prototypeAction && prototypeAction.
  38990. _propertyBindings[ i ].binding.parsedPath;
  38991. binding = new PropertyMixer(
  38992. PropertyBinding.create( root, trackName, path ),
  38993. track.ValueTypeName, track.getValueSize() );
  38994. ++ binding.referenceCount;
  38995. this._addInactiveBinding( binding, rootUuid, trackName );
  38996. bindings[ i ] = binding;
  38997. }
  38998. interpolants[ i ].resultBuffer = binding.buffer;
  38999. }
  39000. }
  39001. _activateAction( action ) {
  39002. if ( ! this._isActiveAction( action ) ) {
  39003. if ( action._cacheIndex === null ) {
  39004. // this action has been forgotten by the cache, but the user
  39005. // appears to be still using it -> rebind
  39006. const rootUuid = ( action._localRoot || this._root ).uuid,
  39007. clipUuid = action._clip.uuid,
  39008. actionsForClip = this._actionsByClip[ clipUuid ];
  39009. this._bindAction( action,
  39010. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39011. this._addInactiveAction( action, clipUuid, rootUuid );
  39012. }
  39013. const bindings = action._propertyBindings;
  39014. // increment reference counts / sort out state
  39015. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39016. const binding = bindings[ i ];
  39017. if ( binding.useCount ++ === 0 ) {
  39018. this._lendBinding( binding );
  39019. binding.saveOriginalState();
  39020. }
  39021. }
  39022. this._lendAction( action );
  39023. }
  39024. }
  39025. _deactivateAction( action ) {
  39026. if ( this._isActiveAction( action ) ) {
  39027. const bindings = action._propertyBindings;
  39028. // decrement reference counts / sort out state
  39029. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39030. const binding = bindings[ i ];
  39031. if ( -- binding.useCount === 0 ) {
  39032. binding.restoreOriginalState();
  39033. this._takeBackBinding( binding );
  39034. }
  39035. }
  39036. this._takeBackAction( action );
  39037. }
  39038. }
  39039. // Memory manager
  39040. _initMemoryManager() {
  39041. this._actions = []; // 'nActiveActions' followed by inactive ones
  39042. this._nActiveActions = 0;
  39043. this._actionsByClip = {};
  39044. // inside:
  39045. // {
  39046. // knownActions: Array< AnimationAction > - used as prototypes
  39047. // actionByRoot: AnimationAction - lookup
  39048. // }
  39049. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39050. this._nActiveBindings = 0;
  39051. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39052. this._controlInterpolants = []; // same game as above
  39053. this._nActiveControlInterpolants = 0;
  39054. const scope = this;
  39055. this.stats = {
  39056. actions: {
  39057. get total() {
  39058. return scope._actions.length;
  39059. },
  39060. get inUse() {
  39061. return scope._nActiveActions;
  39062. }
  39063. },
  39064. bindings: {
  39065. get total() {
  39066. return scope._bindings.length;
  39067. },
  39068. get inUse() {
  39069. return scope._nActiveBindings;
  39070. }
  39071. },
  39072. controlInterpolants: {
  39073. get total() {
  39074. return scope._controlInterpolants.length;
  39075. },
  39076. get inUse() {
  39077. return scope._nActiveControlInterpolants;
  39078. }
  39079. }
  39080. };
  39081. }
  39082. // Memory management for AnimationAction objects
  39083. _isActiveAction( action ) {
  39084. const index = action._cacheIndex;
  39085. return index !== null && index < this._nActiveActions;
  39086. }
  39087. _addInactiveAction( action, clipUuid, rootUuid ) {
  39088. const actions = this._actions,
  39089. actionsByClip = this._actionsByClip;
  39090. let actionsForClip = actionsByClip[ clipUuid ];
  39091. if ( actionsForClip === undefined ) {
  39092. actionsForClip = {
  39093. knownActions: [ action ],
  39094. actionByRoot: {}
  39095. };
  39096. action._byClipCacheIndex = 0;
  39097. actionsByClip[ clipUuid ] = actionsForClip;
  39098. } else {
  39099. const knownActions = actionsForClip.knownActions;
  39100. action._byClipCacheIndex = knownActions.length;
  39101. knownActions.push( action );
  39102. }
  39103. action._cacheIndex = actions.length;
  39104. actions.push( action );
  39105. actionsForClip.actionByRoot[ rootUuid ] = action;
  39106. }
  39107. _removeInactiveAction( action ) {
  39108. const actions = this._actions,
  39109. lastInactiveAction = actions[ actions.length - 1 ],
  39110. cacheIndex = action._cacheIndex;
  39111. lastInactiveAction._cacheIndex = cacheIndex;
  39112. actions[ cacheIndex ] = lastInactiveAction;
  39113. actions.pop();
  39114. action._cacheIndex = null;
  39115. const clipUuid = action._clip.uuid,
  39116. actionsByClip = this._actionsByClip,
  39117. actionsForClip = actionsByClip[ clipUuid ],
  39118. knownActionsForClip = actionsForClip.knownActions,
  39119. lastKnownAction =
  39120. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39121. byClipCacheIndex = action._byClipCacheIndex;
  39122. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39123. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39124. knownActionsForClip.pop();
  39125. action._byClipCacheIndex = null;
  39126. const actionByRoot = actionsForClip.actionByRoot,
  39127. rootUuid = ( action._localRoot || this._root ).uuid;
  39128. delete actionByRoot[ rootUuid ];
  39129. if ( knownActionsForClip.length === 0 ) {
  39130. delete actionsByClip[ clipUuid ];
  39131. }
  39132. this._removeInactiveBindingsForAction( action );
  39133. }
  39134. _removeInactiveBindingsForAction( action ) {
  39135. const bindings = action._propertyBindings;
  39136. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39137. const binding = bindings[ i ];
  39138. if ( -- binding.referenceCount === 0 ) {
  39139. this._removeInactiveBinding( binding );
  39140. }
  39141. }
  39142. }
  39143. _lendAction( action ) {
  39144. // [ active actions | inactive actions ]
  39145. // [ active actions >| inactive actions ]
  39146. // s a
  39147. // <-swap->
  39148. // a s
  39149. const actions = this._actions,
  39150. prevIndex = action._cacheIndex,
  39151. lastActiveIndex = this._nActiveActions ++,
  39152. firstInactiveAction = actions[ lastActiveIndex ];
  39153. action._cacheIndex = lastActiveIndex;
  39154. actions[ lastActiveIndex ] = action;
  39155. firstInactiveAction._cacheIndex = prevIndex;
  39156. actions[ prevIndex ] = firstInactiveAction;
  39157. }
  39158. _takeBackAction( action ) {
  39159. // [ active actions | inactive actions ]
  39160. // [ active actions |< inactive actions ]
  39161. // a s
  39162. // <-swap->
  39163. // s a
  39164. const actions = this._actions,
  39165. prevIndex = action._cacheIndex,
  39166. firstInactiveIndex = -- this._nActiveActions,
  39167. lastActiveAction = actions[ firstInactiveIndex ];
  39168. action._cacheIndex = firstInactiveIndex;
  39169. actions[ firstInactiveIndex ] = action;
  39170. lastActiveAction._cacheIndex = prevIndex;
  39171. actions[ prevIndex ] = lastActiveAction;
  39172. }
  39173. // Memory management for PropertyMixer objects
  39174. _addInactiveBinding( binding, rootUuid, trackName ) {
  39175. const bindingsByRoot = this._bindingsByRootAndName,
  39176. bindings = this._bindings;
  39177. let bindingByName = bindingsByRoot[ rootUuid ];
  39178. if ( bindingByName === undefined ) {
  39179. bindingByName = {};
  39180. bindingsByRoot[ rootUuid ] = bindingByName;
  39181. }
  39182. bindingByName[ trackName ] = binding;
  39183. binding._cacheIndex = bindings.length;
  39184. bindings.push( binding );
  39185. }
  39186. _removeInactiveBinding( binding ) {
  39187. const bindings = this._bindings,
  39188. propBinding = binding.binding,
  39189. rootUuid = propBinding.rootNode.uuid,
  39190. trackName = propBinding.path,
  39191. bindingsByRoot = this._bindingsByRootAndName,
  39192. bindingByName = bindingsByRoot[ rootUuid ],
  39193. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39194. cacheIndex = binding._cacheIndex;
  39195. lastInactiveBinding._cacheIndex = cacheIndex;
  39196. bindings[ cacheIndex ] = lastInactiveBinding;
  39197. bindings.pop();
  39198. delete bindingByName[ trackName ];
  39199. if ( Object.keys( bindingByName ).length === 0 ) {
  39200. delete bindingsByRoot[ rootUuid ];
  39201. }
  39202. }
  39203. _lendBinding( binding ) {
  39204. const bindings = this._bindings,
  39205. prevIndex = binding._cacheIndex,
  39206. lastActiveIndex = this._nActiveBindings ++,
  39207. firstInactiveBinding = bindings[ lastActiveIndex ];
  39208. binding._cacheIndex = lastActiveIndex;
  39209. bindings[ lastActiveIndex ] = binding;
  39210. firstInactiveBinding._cacheIndex = prevIndex;
  39211. bindings[ prevIndex ] = firstInactiveBinding;
  39212. }
  39213. _takeBackBinding( binding ) {
  39214. const bindings = this._bindings,
  39215. prevIndex = binding._cacheIndex,
  39216. firstInactiveIndex = -- this._nActiveBindings,
  39217. lastActiveBinding = bindings[ firstInactiveIndex ];
  39218. binding._cacheIndex = firstInactiveIndex;
  39219. bindings[ firstInactiveIndex ] = binding;
  39220. lastActiveBinding._cacheIndex = prevIndex;
  39221. bindings[ prevIndex ] = lastActiveBinding;
  39222. }
  39223. // Memory management of Interpolants for weight and time scale
  39224. _lendControlInterpolant() {
  39225. const interpolants = this._controlInterpolants,
  39226. lastActiveIndex = this._nActiveControlInterpolants ++;
  39227. let interpolant = interpolants[ lastActiveIndex ];
  39228. if ( interpolant === undefined ) {
  39229. interpolant = new LinearInterpolant(
  39230. new Float32Array( 2 ), new Float32Array( 2 ),
  39231. 1, _controlInterpolantsResultBuffer );
  39232. interpolant.__cacheIndex = lastActiveIndex;
  39233. interpolants[ lastActiveIndex ] = interpolant;
  39234. }
  39235. return interpolant;
  39236. }
  39237. _takeBackControlInterpolant( interpolant ) {
  39238. const interpolants = this._controlInterpolants,
  39239. prevIndex = interpolant.__cacheIndex,
  39240. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39241. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39242. interpolant.__cacheIndex = firstInactiveIndex;
  39243. interpolants[ firstInactiveIndex ] = interpolant;
  39244. lastActiveInterpolant.__cacheIndex = prevIndex;
  39245. interpolants[ prevIndex ] = lastActiveInterpolant;
  39246. }
  39247. /**
  39248. * Returns an instance of {@link AnimationAction} for the passed clip.
  39249. *
  39250. * If an action fitting the clip and root parameters doesn't yet exist, it
  39251. * will be created by this method. Calling this method several times with the
  39252. * same clip and root parameters always returns the same action.
  39253. *
  39254. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39255. * @param {Object3D} [optionalRoot] - An alternative root object.
  39256. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39257. * @return {?AnimationAction} The animation action.
  39258. */
  39259. clipAction( clip, optionalRoot, blendMode ) {
  39260. const root = optionalRoot || this._root,
  39261. rootUuid = root.uuid;
  39262. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39263. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39264. const actionsForClip = this._actionsByClip[ clipUuid ];
  39265. let prototypeAction = null;
  39266. if ( blendMode === undefined ) {
  39267. if ( clipObject !== null ) {
  39268. blendMode = clipObject.blendMode;
  39269. } else {
  39270. blendMode = NormalAnimationBlendMode;
  39271. }
  39272. }
  39273. if ( actionsForClip !== undefined ) {
  39274. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39275. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39276. return existingAction;
  39277. }
  39278. // we know the clip, so we don't have to parse all
  39279. // the bindings again but can just copy
  39280. prototypeAction = actionsForClip.knownActions[ 0 ];
  39281. // also, take the clip from the prototype action
  39282. if ( clipObject === null )
  39283. clipObject = prototypeAction._clip;
  39284. }
  39285. // clip must be known when specified via string
  39286. if ( clipObject === null ) return null;
  39287. // allocate all resources required to run it
  39288. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39289. this._bindAction( newAction, prototypeAction );
  39290. // and make the action known to the memory manager
  39291. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39292. return newAction;
  39293. }
  39294. /**
  39295. * Returns an existing animation action for the passed clip.
  39296. *
  39297. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39298. * @param {Object3D} [optionalRoot] - An alternative root object.
  39299. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39300. */
  39301. existingAction( clip, optionalRoot ) {
  39302. const root = optionalRoot || this._root,
  39303. rootUuid = root.uuid,
  39304. clipObject = typeof clip === 'string' ?
  39305. AnimationClip.findByName( root, clip ) : clip,
  39306. clipUuid = clipObject ? clipObject.uuid : clip,
  39307. actionsForClip = this._actionsByClip[ clipUuid ];
  39308. if ( actionsForClip !== undefined ) {
  39309. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39310. }
  39311. return null;
  39312. }
  39313. /**
  39314. * Deactivates all previously scheduled actions on this mixer.
  39315. *
  39316. * @return {AnimationMixer} A reference to this animation mixer.
  39317. */
  39318. stopAllAction() {
  39319. const actions = this._actions,
  39320. nActions = this._nActiveActions;
  39321. for ( let i = nActions - 1; i >= 0; -- i ) {
  39322. actions[ i ].stop();
  39323. }
  39324. return this;
  39325. }
  39326. /**
  39327. * Advances the global mixer time and updates the animation.
  39328. *
  39329. * This is usually done in the render loop by passing the delta
  39330. * time from {@link Clock} or {@link Timer}.
  39331. *
  39332. * @param {number} deltaTime - The delta time in seconds.
  39333. * @return {AnimationMixer} A reference to this animation mixer.
  39334. */
  39335. update( deltaTime ) {
  39336. deltaTime *= this.timeScale;
  39337. const actions = this._actions,
  39338. nActions = this._nActiveActions,
  39339. time = this.time += deltaTime,
  39340. timeDirection = Math.sign( deltaTime ),
  39341. accuIndex = this._accuIndex ^= 1;
  39342. // run active actions
  39343. for ( let i = 0; i !== nActions; ++ i ) {
  39344. const action = actions[ i ];
  39345. action._update( time, deltaTime, timeDirection, accuIndex );
  39346. }
  39347. // update scene graph
  39348. const bindings = this._bindings,
  39349. nBindings = this._nActiveBindings;
  39350. for ( let i = 0; i !== nBindings; ++ i ) {
  39351. bindings[ i ].apply( accuIndex );
  39352. }
  39353. return this;
  39354. }
  39355. /**
  39356. * Sets the global mixer to a specific time and updates the animation accordingly.
  39357. *
  39358. * This is useful when you need to jump to an exact time in an animation. The
  39359. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39360. *
  39361. * @param {number} time - The time to set in seconds.
  39362. * @return {AnimationMixer} A reference to this animation mixer.
  39363. */
  39364. setTime( time ) {
  39365. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39366. for ( let i = 0; i < this._actions.length; i ++ ) {
  39367. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39368. }
  39369. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39370. }
  39371. /**
  39372. * Returns this mixer's root object.
  39373. *
  39374. * @return {Object3D} The mixer's root object.
  39375. */
  39376. getRoot() {
  39377. return this._root;
  39378. }
  39379. /**
  39380. * Deallocates all memory resources for a clip. Before using this method make
  39381. * sure to call {@link AnimationAction#stop} for all related actions.
  39382. *
  39383. * @param {AnimationClip} clip - The clip to uncache.
  39384. */
  39385. uncacheClip( clip ) {
  39386. const actions = this._actions,
  39387. clipUuid = clip.uuid,
  39388. actionsByClip = this._actionsByClip,
  39389. actionsForClip = actionsByClip[ clipUuid ];
  39390. if ( actionsForClip !== undefined ) {
  39391. // note: just calling _removeInactiveAction would mess up the
  39392. // iteration state and also require updating the state we can
  39393. // just throw away
  39394. const actionsToRemove = actionsForClip.knownActions;
  39395. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39396. const action = actionsToRemove[ i ];
  39397. this._deactivateAction( action );
  39398. const cacheIndex = action._cacheIndex,
  39399. lastInactiveAction = actions[ actions.length - 1 ];
  39400. action._cacheIndex = null;
  39401. action._byClipCacheIndex = null;
  39402. lastInactiveAction._cacheIndex = cacheIndex;
  39403. actions[ cacheIndex ] = lastInactiveAction;
  39404. actions.pop();
  39405. this._removeInactiveBindingsForAction( action );
  39406. }
  39407. delete actionsByClip[ clipUuid ];
  39408. }
  39409. }
  39410. /**
  39411. * Deallocates all memory resources for a root object. Before using this
  39412. * method make sure to call {@link AnimationAction#stop} for all related
  39413. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39414. * mixer operates on a single root.
  39415. *
  39416. * @param {Object3D} root - The root object to uncache.
  39417. */
  39418. uncacheRoot( root ) {
  39419. const rootUuid = root.uuid,
  39420. actionsByClip = this._actionsByClip;
  39421. for ( const clipUuid in actionsByClip ) {
  39422. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39423. action = actionByRoot[ rootUuid ];
  39424. if ( action !== undefined ) {
  39425. this._deactivateAction( action );
  39426. this._removeInactiveAction( action );
  39427. }
  39428. }
  39429. const bindingsByRoot = this._bindingsByRootAndName,
  39430. bindingByName = bindingsByRoot[ rootUuid ];
  39431. if ( bindingByName !== undefined ) {
  39432. for ( const trackName in bindingByName ) {
  39433. const binding = bindingByName[ trackName ];
  39434. binding.restoreOriginalState();
  39435. this._removeInactiveBinding( binding );
  39436. }
  39437. }
  39438. }
  39439. /**
  39440. * Deallocates all memory resources for an action. The action is identified by the
  39441. * given clip and an optional root object. Before using this method make
  39442. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39443. *
  39444. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39445. * @param {Object3D} [optionalRoot] - An alternative root object.
  39446. */
  39447. uncacheAction( clip, optionalRoot ) {
  39448. const action = this.existingAction( clip, optionalRoot );
  39449. if ( action !== null ) {
  39450. this._deactivateAction( action );
  39451. this._removeInactiveAction( action );
  39452. }
  39453. }
  39454. }
  39455. /**
  39456. * Represents a 3D render target.
  39457. *
  39458. * @augments RenderTarget
  39459. */
  39460. class RenderTarget3D extends RenderTarget {
  39461. /**
  39462. * Constructs a new 3D render target.
  39463. *
  39464. * @param {number} [width=1] - The width of the render target.
  39465. * @param {number} [height=1] - The height of the render target.
  39466. * @param {number} [depth=1] - The height of the render target.
  39467. * @param {RenderTarget~Options} [options] - The configuration object.
  39468. */
  39469. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39470. super( width, height, options );
  39471. /**
  39472. * This flag can be used for type testing.
  39473. *
  39474. * @type {boolean}
  39475. * @readonly
  39476. * @default true
  39477. */
  39478. this.isRenderTarget3D = true;
  39479. this.depth = depth;
  39480. /**
  39481. * Overwritten with a different texture type.
  39482. *
  39483. * @type {Data3DTexture}
  39484. */
  39485. this.texture = new Data3DTexture( null, width, height, depth );
  39486. this._setTextureOptions( options );
  39487. this.texture.isRenderTargetTexture = true;
  39488. }
  39489. }
  39490. /**
  39491. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39492. *
  39493. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39494. * ```js
  39495. * uniforms: {
  39496. * time: { value: 1.0 },
  39497. * resolution: new Uniform( new Vector2() )
  39498. * };
  39499. * ```
  39500. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39501. * in {@link WebGLRenderer}.
  39502. */
  39503. class Uniform {
  39504. /**
  39505. * Constructs a new uniform.
  39506. *
  39507. * @param {any} value - The uniform value.
  39508. */
  39509. constructor( value ) {
  39510. /**
  39511. * The uniform value.
  39512. *
  39513. * @type {any}
  39514. */
  39515. this.value = value;
  39516. }
  39517. /**
  39518. * Returns a new uniform with copied values from this instance.
  39519. * If the value has a `clone()` method, the value is cloned as well.
  39520. *
  39521. * @return {Uniform} A clone of this instance.
  39522. */
  39523. clone() {
  39524. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39525. }
  39526. }
  39527. let _id$1 = 0;
  39528. /**
  39529. * A class for managing multiple uniforms in a single group. The renderer will process
  39530. * such a definition as a single UBO.
  39531. *
  39532. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39533. * in {@link WebGLRenderer}.
  39534. *
  39535. * @augments EventDispatcher
  39536. */
  39537. class UniformsGroup extends EventDispatcher {
  39538. /**
  39539. * Constructs a new uniforms group.
  39540. */
  39541. constructor() {
  39542. super();
  39543. /**
  39544. * This flag can be used for type testing.
  39545. *
  39546. * @type {boolean}
  39547. * @readonly
  39548. * @default true
  39549. */
  39550. this.isUniformsGroup = true;
  39551. /**
  39552. * The ID of the 3D object.
  39553. *
  39554. * @name UniformsGroup#id
  39555. * @type {number}
  39556. * @readonly
  39557. */
  39558. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39559. /**
  39560. * The name of the uniforms group.
  39561. *
  39562. * @type {string}
  39563. */
  39564. this.name = '';
  39565. /**
  39566. * The buffer usage.
  39567. *
  39568. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39569. * @default StaticDrawUsage
  39570. */
  39571. this.usage = StaticDrawUsage;
  39572. /**
  39573. * An array holding the uniforms.
  39574. *
  39575. * @type {Array<Uniform>}
  39576. */
  39577. this.uniforms = [];
  39578. }
  39579. /**
  39580. * Adds the given uniform to this uniforms group.
  39581. *
  39582. * @param {Uniform} uniform - The uniform to add.
  39583. * @return {UniformsGroup} A reference to this uniforms group.
  39584. */
  39585. add( uniform ) {
  39586. this.uniforms.push( uniform );
  39587. return this;
  39588. }
  39589. /**
  39590. * Removes the given uniform from this uniforms group.
  39591. *
  39592. * @param {Uniform} uniform - The uniform to remove.
  39593. * @return {UniformsGroup} A reference to this uniforms group.
  39594. */
  39595. remove( uniform ) {
  39596. const index = this.uniforms.indexOf( uniform );
  39597. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39598. return this;
  39599. }
  39600. /**
  39601. * Sets the name of this uniforms group.
  39602. *
  39603. * @param {string} name - The name to set.
  39604. * @return {UniformsGroup} A reference to this uniforms group.
  39605. */
  39606. setName( name ) {
  39607. this.name = name;
  39608. return this;
  39609. }
  39610. /**
  39611. * Sets the usage of this uniforms group.
  39612. *
  39613. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39614. * @return {UniformsGroup} A reference to this uniforms group.
  39615. */
  39616. setUsage( value ) {
  39617. this.usage = value;
  39618. return this;
  39619. }
  39620. /**
  39621. * Frees the GPU-related resources allocated by this instance. Call this
  39622. * method whenever this instance is no longer used in your app.
  39623. *
  39624. * @fires Texture#dispose
  39625. */
  39626. dispose() {
  39627. this.dispatchEvent( { type: 'dispose' } );
  39628. }
  39629. /**
  39630. * Copies the values of the given uniforms group to this instance.
  39631. *
  39632. * @param {UniformsGroup} source - The uniforms group to copy.
  39633. * @return {UniformsGroup} A reference to this uniforms group.
  39634. */
  39635. copy( source ) {
  39636. this.name = source.name;
  39637. this.usage = source.usage;
  39638. const uniformsSource = source.uniforms;
  39639. this.uniforms.length = 0;
  39640. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39641. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39642. for ( let j = 0; j < uniforms.length; j ++ ) {
  39643. this.uniforms.push( uniforms[ j ].clone() );
  39644. }
  39645. }
  39646. return this;
  39647. }
  39648. /**
  39649. * Returns a new uniforms group with copied values from this instance.
  39650. *
  39651. * @return {UniformsGroup} A clone of this instance.
  39652. */
  39653. clone() {
  39654. return new this.constructor().copy( this );
  39655. }
  39656. }
  39657. /**
  39658. * An instanced version of an interleaved buffer.
  39659. *
  39660. * @augments InterleavedBuffer
  39661. */
  39662. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39663. /**
  39664. * Constructs a new instanced interleaved buffer.
  39665. *
  39666. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39667. * @param {number} stride - The number of typed-array elements per vertex.
  39668. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39669. */
  39670. constructor( array, stride, meshPerAttribute = 1 ) {
  39671. super( array, stride );
  39672. /**
  39673. * This flag can be used for type testing.
  39674. *
  39675. * @type {boolean}
  39676. * @readonly
  39677. * @default true
  39678. */
  39679. this.isInstancedInterleavedBuffer = true;
  39680. /**
  39681. * Defines how often a value of this buffer attribute should be repeated,
  39682. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39683. *
  39684. * @type {number}
  39685. * @default 1
  39686. */
  39687. this.meshPerAttribute = meshPerAttribute;
  39688. }
  39689. copy( source ) {
  39690. super.copy( source );
  39691. this.meshPerAttribute = source.meshPerAttribute;
  39692. return this;
  39693. }
  39694. clone( data ) {
  39695. const ib = super.clone( data );
  39696. ib.meshPerAttribute = this.meshPerAttribute;
  39697. return ib;
  39698. }
  39699. toJSON( data ) {
  39700. const json = super.toJSON( data );
  39701. json.isInstancedInterleavedBuffer = true;
  39702. json.meshPerAttribute = this.meshPerAttribute;
  39703. return json;
  39704. }
  39705. }
  39706. /**
  39707. * An alternative version of a buffer attribute with more control over the VBO.
  39708. *
  39709. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39710. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39711. *
  39712. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39713. * or even produces the VBOs in question.
  39714. *
  39715. * Notice that this class can only be used with {@link WebGLRenderer}.
  39716. */
  39717. class GLBufferAttribute {
  39718. /**
  39719. * Constructs a new GL buffer attribute.
  39720. *
  39721. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39722. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39723. * @param {number} itemSize - The item size.
  39724. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39725. * @param {number} count - The expected number of vertices in VBO.
  39726. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39727. */
  39728. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39729. /**
  39730. * This flag can be used for type testing.
  39731. *
  39732. * @type {boolean}
  39733. * @readonly
  39734. * @default true
  39735. */
  39736. this.isGLBufferAttribute = true;
  39737. /**
  39738. * The name of the buffer attribute.
  39739. *
  39740. * @type {string}
  39741. */
  39742. this.name = '';
  39743. /**
  39744. * The native WebGL buffer.
  39745. *
  39746. * @type {WebGLBuffer}
  39747. */
  39748. this.buffer = buffer;
  39749. /**
  39750. * The native data type.
  39751. *
  39752. * @type {number}
  39753. */
  39754. this.type = type;
  39755. /**
  39756. * The item size, see {@link BufferAttribute#itemSize}.
  39757. *
  39758. * @type {number}
  39759. */
  39760. this.itemSize = itemSize;
  39761. /**
  39762. * The corresponding size (in bytes) for the given `type` parameter.
  39763. *
  39764. * @type {number}
  39765. */
  39766. this.elementSize = elementSize;
  39767. /**
  39768. * The expected number of vertices in VBO.
  39769. *
  39770. * @type {number}
  39771. */
  39772. this.count = count;
  39773. /**
  39774. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39775. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39776. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39777. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39778. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39779. *
  39780. * @type {boolean}
  39781. */
  39782. this.normalized = normalized;
  39783. /**
  39784. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39785. *
  39786. * @type {number}
  39787. */
  39788. this.version = 0;
  39789. }
  39790. /**
  39791. * Flag to indicate that this attribute has changed and should be re-sent to
  39792. * the GPU. Set this to `true` when you modify the value of the array.
  39793. *
  39794. * @type {number}
  39795. * @default false
  39796. * @param {boolean} value
  39797. */
  39798. set needsUpdate( value ) {
  39799. if ( value === true ) this.version ++;
  39800. }
  39801. /**
  39802. * Sets the given native WebGL buffer.
  39803. *
  39804. * @param {WebGLBuffer} buffer - The buffer to set.
  39805. * @return {BufferAttribute} A reference to this instance.
  39806. */
  39807. setBuffer( buffer ) {
  39808. this.buffer = buffer;
  39809. return this;
  39810. }
  39811. /**
  39812. * Sets the given native data type and element size.
  39813. *
  39814. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39815. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39816. * @return {BufferAttribute} A reference to this instance.
  39817. */
  39818. setType( type, elementSize ) {
  39819. this.type = type;
  39820. this.elementSize = elementSize;
  39821. return this;
  39822. }
  39823. /**
  39824. * Sets the item size.
  39825. *
  39826. * @param {number} itemSize - The item size.
  39827. * @return {BufferAttribute} A reference to this instance.
  39828. */
  39829. setItemSize( itemSize ) {
  39830. this.itemSize = itemSize;
  39831. return this;
  39832. }
  39833. /**
  39834. * Sets the count (the expected number of vertices in VBO).
  39835. *
  39836. * @param {number} count - The count.
  39837. * @return {BufferAttribute} A reference to this instance.
  39838. */
  39839. setCount( count ) {
  39840. this.count = count;
  39841. return this;
  39842. }
  39843. }
  39844. const _matrix = /*@__PURE__*/ new Matrix4();
  39845. /**
  39846. * This class is designed to assist with raycasting. Raycasting is used for
  39847. * mouse picking (working out what objects in the 3d space the mouse is over)
  39848. * amongst other things.
  39849. */
  39850. class Raycaster {
  39851. /**
  39852. * Constructs a new raycaster.
  39853. *
  39854. * @param {Vector3} origin - The origin vector where the ray casts from.
  39855. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39856. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39857. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39858. */
  39859. constructor( origin, direction, near = 0, far = Infinity ) {
  39860. /**
  39861. * The ray used for raycasting.
  39862. *
  39863. * @type {Ray}
  39864. */
  39865. this.ray = new Ray( origin, direction );
  39866. /**
  39867. * All results returned are further away than near. Near can't be negative.
  39868. *
  39869. * @type {number}
  39870. * @default 0
  39871. */
  39872. this.near = near;
  39873. /**
  39874. * All results returned are closer than far. Far can't be lower than near.
  39875. *
  39876. * @type {number}
  39877. * @default Infinity
  39878. */
  39879. this.far = far;
  39880. /**
  39881. * The camera to use when raycasting against view-dependent objects such as
  39882. * billboarded objects like sprites. This field can be set manually or
  39883. * is set when calling `setFromCamera()`.
  39884. *
  39885. * @type {?Camera}
  39886. * @default null
  39887. */
  39888. this.camera = null;
  39889. /**
  39890. * Allows to selectively ignore 3D objects when performing intersection tests.
  39891. * The following code example ensures that only 3D objects on layer `1` will be
  39892. * honored by raycaster.
  39893. * ```js
  39894. * raycaster.layers.set( 1 );
  39895. * object.layers.enable( 1 );
  39896. * ```
  39897. *
  39898. * @type {Layers}
  39899. */
  39900. this.layers = new Layers();
  39901. /**
  39902. * A parameter object that configures the raycasting. It has the structure:
  39903. *
  39904. * ```
  39905. * {
  39906. * Mesh: {},
  39907. * Line: { threshold: 1 },
  39908. * LOD: {},
  39909. * Points: { threshold: 1 },
  39910. * Sprite: {}
  39911. * }
  39912. * ```
  39913. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39914. *
  39915. * @type {Object}
  39916. */
  39917. this.params = {
  39918. Mesh: {},
  39919. Line: { threshold: 1 },
  39920. LOD: {},
  39921. Points: { threshold: 1 },
  39922. Sprite: {}
  39923. };
  39924. }
  39925. /**
  39926. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39927. *
  39928. * @param {Vector3} origin - The origin vector where the ray casts from.
  39929. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39930. */
  39931. set( origin, direction ) {
  39932. // direction is assumed to be normalized (for accurate distance calculations)
  39933. this.ray.set( origin, direction );
  39934. }
  39935. /**
  39936. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39937. *
  39938. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39939. * X and Y components should be between `-1` and `1`.
  39940. * @param {Camera} camera - The camera from which the ray should originate.
  39941. */
  39942. setFromCamera( coords, camera ) {
  39943. if ( camera.isPerspectiveCamera ) {
  39944. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39945. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39946. this.camera = camera;
  39947. } else if ( camera.isOrthographicCamera ) {
  39948. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39949. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39950. this.camera = camera;
  39951. } else {
  39952. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  39953. }
  39954. }
  39955. /**
  39956. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39957. *
  39958. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39959. * @return {Raycaster} A reference to this raycaster.
  39960. */
  39961. setFromXRController( controller ) {
  39962. _matrix.identity().extractRotation( controller.matrixWorld );
  39963. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39964. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39965. return this;
  39966. }
  39967. /**
  39968. * The intersection point of a raycaster intersection test.
  39969. * @typedef {Object} Raycaster~Intersection
  39970. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39971. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39972. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39973. * @property {Vector3} point - The intersection point, in world coordinates.
  39974. * @property {Object} face - The face that has been intersected.
  39975. * @property {number} faceIndex - The face index.
  39976. * @property {Object3D} object - The 3D object that has been intersected.
  39977. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39978. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39979. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  39980. * @property {number} instanceId - The index number of the instance where the ray
  39981. * intersects the {@link InstancedMesh}.
  39982. */
  39983. /**
  39984. * Checks all intersection between the ray and the object with or without the
  39985. * descendants. Intersections are returned sorted by distance, closest first.
  39986. *
  39987. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39988. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39989. * differently to ray casting than lines or points.
  39990. *
  39991. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39992. * to be detected; intersections of the ray passing through the back of a face will not
  39993. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39994. * to `THREE.DoubleSide`.
  39995. *
  39996. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39997. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39998. * Otherwise it only checks intersection with the object.
  39999. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40000. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40001. */
  40002. intersectObject( object, recursive = true, intersects = [] ) {
  40003. intersect( object, this, intersects, recursive );
  40004. intersects.sort( ascSort );
  40005. return intersects;
  40006. }
  40007. /**
  40008. * Checks all intersection between the ray and the objects with or without
  40009. * the descendants. Intersections are returned sorted by distance, closest first.
  40010. *
  40011. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40012. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40013. * Otherwise it only checks intersection with the object.
  40014. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40015. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40016. */
  40017. intersectObjects( objects, recursive = true, intersects = [] ) {
  40018. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40019. intersect( objects[ i ], this, intersects, recursive );
  40020. }
  40021. intersects.sort( ascSort );
  40022. return intersects;
  40023. }
  40024. }
  40025. function ascSort( a, b ) {
  40026. return a.distance - b.distance;
  40027. }
  40028. function intersect( object, raycaster, intersects, recursive ) {
  40029. let propagate = true;
  40030. if ( object.layers.test( raycaster.layers ) ) {
  40031. const result = object.raycast( raycaster, intersects );
  40032. if ( result === false ) propagate = false;
  40033. }
  40034. if ( propagate === true && recursive === true ) {
  40035. const children = object.children;
  40036. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40037. intersect( children[ i ], raycaster, intersects, true );
  40038. }
  40039. }
  40040. }
  40041. /**
  40042. * This class is an alternative to {@link Clock} with a different API design and behavior.
  40043. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  40044. *
  40045. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  40046. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  40047. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  40048. * is inactive (e.g. tab switched or browser hidden).
  40049. *
  40050. * ```js
  40051. * const timer = new Timer();
  40052. * timer.connect( document ); // use Page Visibility API
  40053. * ```
  40054. */
  40055. class Timer {
  40056. /**
  40057. * Constructs a new timer.
  40058. */
  40059. constructor() {
  40060. this._previousTime = 0;
  40061. this._currentTime = 0;
  40062. this._startTime = performance.now();
  40063. this._delta = 0;
  40064. this._elapsed = 0;
  40065. this._timescale = 1;
  40066. this._document = null;
  40067. this._pageVisibilityHandler = null;
  40068. }
  40069. /**
  40070. * Connect the timer to the given document.Calling this method is not mandatory to
  40071. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40072. * delta values.
  40073. *
  40074. * @param {Document} document - The document.
  40075. */
  40076. connect( document ) {
  40077. this._document = document;
  40078. // use Page Visibility API to avoid large time delta values
  40079. if ( document.hidden !== undefined ) {
  40080. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40081. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40082. }
  40083. }
  40084. /**
  40085. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40086. */
  40087. disconnect() {
  40088. if ( this._pageVisibilityHandler !== null ) {
  40089. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40090. this._pageVisibilityHandler = null;
  40091. }
  40092. this._document = null;
  40093. }
  40094. /**
  40095. * Returns the time delta in seconds.
  40096. *
  40097. * @return {number} The time delta in second.
  40098. */
  40099. getDelta() {
  40100. return this._delta / 1000;
  40101. }
  40102. /**
  40103. * Returns the elapsed time in seconds.
  40104. *
  40105. * @return {number} The elapsed time in second.
  40106. */
  40107. getElapsed() {
  40108. return this._elapsed / 1000;
  40109. }
  40110. /**
  40111. * Returns the timescale.
  40112. *
  40113. * @return {number} The timescale.
  40114. */
  40115. getTimescale() {
  40116. return this._timescale;
  40117. }
  40118. /**
  40119. * Sets the given timescale which scale the time delta computation
  40120. * in `update()`.
  40121. *
  40122. * @param {number} timescale - The timescale to set.
  40123. * @return {Timer} A reference to this timer.
  40124. */
  40125. setTimescale( timescale ) {
  40126. this._timescale = timescale;
  40127. return this;
  40128. }
  40129. /**
  40130. * Resets the time computation for the current simulation step.
  40131. *
  40132. * @return {Timer} A reference to this timer.
  40133. */
  40134. reset() {
  40135. this._currentTime = performance.now() - this._startTime;
  40136. return this;
  40137. }
  40138. /**
  40139. * Can be used to free all internal resources. Usually called when
  40140. * the timer instance isn't required anymore.
  40141. */
  40142. dispose() {
  40143. this.disconnect();
  40144. }
  40145. /**
  40146. * Updates the internal state of the timer. This method should be called
  40147. * once per simulation step and before you perform queries against the timer
  40148. * (e.g. via `getDelta()`).
  40149. *
  40150. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40151. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40152. * time will be determined with `performance.now`.
  40153. * @return {Timer} A reference to this timer.
  40154. */
  40155. update( timestamp ) {
  40156. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40157. this._delta = 0;
  40158. } else {
  40159. this._previousTime = this._currentTime;
  40160. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40161. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40162. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40163. }
  40164. return this;
  40165. }
  40166. }
  40167. function handleVisibilityChange() {
  40168. if ( this._document.hidden === false ) this.reset();
  40169. }
  40170. /**
  40171. * This class can be used to represent points in 3D space as
  40172. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40173. */
  40174. class Spherical {
  40175. /**
  40176. * Constructs a new spherical.
  40177. *
  40178. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40179. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40180. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40181. */
  40182. constructor( radius = 1, phi = 0, theta = 0 ) {
  40183. /**
  40184. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40185. *
  40186. * @type {number}
  40187. * @default 1
  40188. */
  40189. this.radius = radius;
  40190. /**
  40191. * The polar angle in radians from the y (up) axis.
  40192. *
  40193. * @type {number}
  40194. * @default 0
  40195. */
  40196. this.phi = phi;
  40197. /**
  40198. * The equator/azimuthal angle in radians around the y (up) axis.
  40199. *
  40200. * @type {number}
  40201. * @default 0
  40202. */
  40203. this.theta = theta;
  40204. }
  40205. /**
  40206. * Sets the spherical components by copying the given values.
  40207. *
  40208. * @param {number} radius - The radius.
  40209. * @param {number} phi - The polar angle.
  40210. * @param {number} theta - The azimuthal angle.
  40211. * @return {Spherical} A reference to this spherical.
  40212. */
  40213. set( radius, phi, theta ) {
  40214. this.radius = radius;
  40215. this.phi = phi;
  40216. this.theta = theta;
  40217. return this;
  40218. }
  40219. /**
  40220. * Copies the values of the given spherical to this instance.
  40221. *
  40222. * @param {Spherical} other - The spherical to copy.
  40223. * @return {Spherical} A reference to this spherical.
  40224. */
  40225. copy( other ) {
  40226. this.radius = other.radius;
  40227. this.phi = other.phi;
  40228. this.theta = other.theta;
  40229. return this;
  40230. }
  40231. /**
  40232. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40233. * `0.000001`.
  40234. *
  40235. * @return {Spherical} A reference to this spherical.
  40236. */
  40237. makeSafe() {
  40238. const EPS = 0.000001;
  40239. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40240. return this;
  40241. }
  40242. /**
  40243. * Sets the spherical components from the given vector which is assumed to hold
  40244. * Cartesian coordinates.
  40245. *
  40246. * @param {Vector3} v - The vector to set.
  40247. * @return {Spherical} A reference to this spherical.
  40248. */
  40249. setFromVector3( v ) {
  40250. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40251. }
  40252. /**
  40253. * Sets the spherical components from the given Cartesian coordinates.
  40254. *
  40255. * @param {number} x - The x value.
  40256. * @param {number} y - The y value.
  40257. * @param {number} z - The z value.
  40258. * @return {Spherical} A reference to this spherical.
  40259. */
  40260. setFromCartesianCoords( x, y, z ) {
  40261. this.radius = Math.sqrt( x * x + y * y + z * z );
  40262. if ( this.radius === 0 ) {
  40263. this.theta = 0;
  40264. this.phi = 0;
  40265. } else {
  40266. this.theta = Math.atan2( x, z );
  40267. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40268. }
  40269. return this;
  40270. }
  40271. /**
  40272. * Returns a new spherical with copied values from this instance.
  40273. *
  40274. * @return {Spherical} A clone of this instance.
  40275. */
  40276. clone() {
  40277. return new this.constructor().copy( this );
  40278. }
  40279. }
  40280. /**
  40281. * This class can be used to represent points in 3D space as
  40282. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40283. */
  40284. class Cylindrical {
  40285. /**
  40286. * Constructs a new cylindrical.
  40287. *
  40288. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40289. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40290. * @param {number} [y=0] - The height above the x-z plane.
  40291. */
  40292. constructor( radius = 1, theta = 0, y = 0 ) {
  40293. /**
  40294. * The distance from the origin to a point in the x-z plane.
  40295. *
  40296. * @type {number}
  40297. * @default 1
  40298. */
  40299. this.radius = radius;
  40300. /**
  40301. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40302. *
  40303. * @type {number}
  40304. * @default 0
  40305. */
  40306. this.theta = theta;
  40307. /**
  40308. * The height above the x-z plane.
  40309. *
  40310. * @type {number}
  40311. * @default 0
  40312. */
  40313. this.y = y;
  40314. }
  40315. /**
  40316. * Sets the cylindrical components by copying the given values.
  40317. *
  40318. * @param {number} radius - The radius.
  40319. * @param {number} theta - The theta angle.
  40320. * @param {number} y - The height value.
  40321. * @return {Cylindrical} A reference to this cylindrical.
  40322. */
  40323. set( radius, theta, y ) {
  40324. this.radius = radius;
  40325. this.theta = theta;
  40326. this.y = y;
  40327. return this;
  40328. }
  40329. /**
  40330. * Copies the values of the given cylindrical to this instance.
  40331. *
  40332. * @param {Cylindrical} other - The cylindrical to copy.
  40333. * @return {Cylindrical} A reference to this cylindrical.
  40334. */
  40335. copy( other ) {
  40336. this.radius = other.radius;
  40337. this.theta = other.theta;
  40338. this.y = other.y;
  40339. return this;
  40340. }
  40341. /**
  40342. * Sets the cylindrical components from the given vector which is assumed to hold
  40343. * Cartesian coordinates.
  40344. *
  40345. * @param {Vector3} v - The vector to set.
  40346. * @return {Cylindrical} A reference to this cylindrical.
  40347. */
  40348. setFromVector3( v ) {
  40349. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40350. }
  40351. /**
  40352. * Sets the cylindrical components from the given Cartesian coordinates.
  40353. *
  40354. * @param {number} x - The x value.
  40355. * @param {number} y - The x value.
  40356. * @param {number} z - The x value.
  40357. * @return {Cylindrical} A reference to this cylindrical.
  40358. */
  40359. setFromCartesianCoords( x, y, z ) {
  40360. this.radius = Math.sqrt( x * x + z * z );
  40361. this.theta = Math.atan2( x, z );
  40362. this.y = y;
  40363. return this;
  40364. }
  40365. /**
  40366. * Returns a new cylindrical with copied values from this instance.
  40367. *
  40368. * @return {Cylindrical} A clone of this instance.
  40369. */
  40370. clone() {
  40371. return new this.constructor().copy( this );
  40372. }
  40373. }
  40374. /**
  40375. * Represents a 2x2 matrix.
  40376. *
  40377. * A Note on Row-Major and Column-Major Ordering:
  40378. *
  40379. * The constructor and {@link Matrix2#set} method take arguments in
  40380. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40381. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40382. * This means that calling:
  40383. * ```js
  40384. * const m = new THREE.Matrix2();
  40385. * m.set( 11, 12,
  40386. * 21, 22 );
  40387. * ```
  40388. * will result in the elements array containing:
  40389. * ```js
  40390. * m.elements = [ 11, 21,
  40391. * 12, 22 ];
  40392. * ```
  40393. * and internally all calculations are performed using column-major ordering.
  40394. * However, as the actual ordering makes no difference mathematically and
  40395. * most people are used to thinking about matrices in row-major order, the
  40396. * three.js documentation shows matrices in row-major order. Just bear in
  40397. * mind that if you are reading the source code, you'll have to take the
  40398. * transpose of any matrices outlined here to make sense of the calculations.
  40399. */
  40400. class Matrix2 {
  40401. /**
  40402. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40403. * in row-major order. If no arguments are provided, the constructor
  40404. * initializes the matrix as an identity matrix.
  40405. *
  40406. * @param {number} [n11] - 1-1 matrix element.
  40407. * @param {number} [n12] - 1-2 matrix element.
  40408. * @param {number} [n21] - 2-1 matrix element.
  40409. * @param {number} [n22] - 2-2 matrix element.
  40410. */
  40411. constructor( n11, n12, n21, n22 ) {
  40412. /**
  40413. * This flag can be used for type testing.
  40414. *
  40415. * @type {boolean}
  40416. * @readonly
  40417. * @default true
  40418. */
  40419. Matrix2.prototype.isMatrix2 = true;
  40420. /**
  40421. * A column-major list of matrix values.
  40422. *
  40423. * @type {Array<number>}
  40424. */
  40425. this.elements = [
  40426. 1, 0,
  40427. 0, 1,
  40428. ];
  40429. if ( n11 !== undefined ) {
  40430. this.set( n11, n12, n21, n22 );
  40431. }
  40432. }
  40433. /**
  40434. * Sets this matrix to the 2x2 identity matrix.
  40435. *
  40436. * @return {Matrix2} A reference to this matrix.
  40437. */
  40438. identity() {
  40439. this.set(
  40440. 1, 0,
  40441. 0, 1,
  40442. );
  40443. return this;
  40444. }
  40445. /**
  40446. * Sets the elements of the matrix from the given array.
  40447. *
  40448. * @param {Array<number>} array - The matrix elements in column-major order.
  40449. * @param {number} [offset=0] - Index of the first element in the array.
  40450. * @return {Matrix2} A reference to this matrix.
  40451. */
  40452. fromArray( array, offset = 0 ) {
  40453. for ( let i = 0; i < 4; i ++ ) {
  40454. this.elements[ i ] = array[ i + offset ];
  40455. }
  40456. return this;
  40457. }
  40458. /**
  40459. * Sets the elements of the matrix.The arguments are supposed to be
  40460. * in row-major order.
  40461. *
  40462. * @param {number} n11 - 1-1 matrix element.
  40463. * @param {number} n12 - 1-2 matrix element.
  40464. * @param {number} n21 - 2-1 matrix element.
  40465. * @param {number} n22 - 2-2 matrix element.
  40466. * @return {Matrix2} A reference to this matrix.
  40467. */
  40468. set( n11, n12, n21, n22 ) {
  40469. const te = this.elements;
  40470. te[ 0 ] = n11; te[ 2 ] = n12;
  40471. te[ 1 ] = n21; te[ 3 ] = n22;
  40472. return this;
  40473. }
  40474. }
  40475. const _vector$4 = /*@__PURE__*/ new Vector2();
  40476. /**
  40477. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40478. */
  40479. class Box2 {
  40480. /**
  40481. * Constructs a new bounding box.
  40482. *
  40483. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40484. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40485. */
  40486. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40487. /**
  40488. * This flag can be used for type testing.
  40489. *
  40490. * @type {boolean}
  40491. * @readonly
  40492. * @default true
  40493. */
  40494. this.isBox2 = true;
  40495. /**
  40496. * The lower boundary of the box.
  40497. *
  40498. * @type {Vector2}
  40499. */
  40500. this.min = min;
  40501. /**
  40502. * The upper boundary of the box.
  40503. *
  40504. * @type {Vector2}
  40505. */
  40506. this.max = max;
  40507. }
  40508. /**
  40509. * Sets the lower and upper boundaries of this box.
  40510. * Please note that this method only copies the values from the given objects.
  40511. *
  40512. * @param {Vector2} min - The lower boundary of the box.
  40513. * @param {Vector2} max - The upper boundary of the box.
  40514. * @return {Box2} A reference to this bounding box.
  40515. */
  40516. set( min, max ) {
  40517. this.min.copy( min );
  40518. this.max.copy( max );
  40519. return this;
  40520. }
  40521. /**
  40522. * Sets the upper and lower bounds of this box so it encloses the position data
  40523. * in the given array.
  40524. *
  40525. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40526. * @return {Box2} A reference to this bounding box.
  40527. */
  40528. setFromPoints( points ) {
  40529. this.makeEmpty();
  40530. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40531. this.expandByPoint( points[ i ] );
  40532. }
  40533. return this;
  40534. }
  40535. /**
  40536. * Centers this box on the given center vector and sets this box's width, height and
  40537. * depth to the given size values.
  40538. *
  40539. * @param {Vector2} center - The center of the box.
  40540. * @param {Vector2} size - The x and y dimensions of the box.
  40541. * @return {Box2} A reference to this bounding box.
  40542. */
  40543. setFromCenterAndSize( center, size ) {
  40544. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40545. this.min.copy( center ).sub( halfSize );
  40546. this.max.copy( center ).add( halfSize );
  40547. return this;
  40548. }
  40549. /**
  40550. * Returns a new box with copied values from this instance.
  40551. *
  40552. * @return {Box2} A clone of this instance.
  40553. */
  40554. clone() {
  40555. return new this.constructor().copy( this );
  40556. }
  40557. /**
  40558. * Copies the values of the given box to this instance.
  40559. *
  40560. * @param {Box2} box - The box to copy.
  40561. * @return {Box2} A reference to this bounding box.
  40562. */
  40563. copy( box ) {
  40564. this.min.copy( box.min );
  40565. this.max.copy( box.max );
  40566. return this;
  40567. }
  40568. /**
  40569. * Makes this box empty which means in encloses a zero space in 2D.
  40570. *
  40571. * @return {Box2} A reference to this bounding box.
  40572. */
  40573. makeEmpty() {
  40574. this.min.x = this.min.y = + Infinity;
  40575. this.max.x = this.max.y = - Infinity;
  40576. return this;
  40577. }
  40578. /**
  40579. * Returns true if this box includes zero points within its bounds.
  40580. * Note that a box with equal lower and upper bounds still includes one
  40581. * point, the one both bounds share.
  40582. *
  40583. * @return {boolean} Whether this box is empty or not.
  40584. */
  40585. isEmpty() {
  40586. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40587. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40588. }
  40589. /**
  40590. * Returns the center point of this box.
  40591. *
  40592. * @param {Vector2} target - The target vector that is used to store the method's result.
  40593. * @return {Vector2} The center point.
  40594. */
  40595. getCenter( target ) {
  40596. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40597. }
  40598. /**
  40599. * Returns the dimensions of this box.
  40600. *
  40601. * @param {Vector2} target - The target vector that is used to store the method's result.
  40602. * @return {Vector2} The size.
  40603. */
  40604. getSize( target ) {
  40605. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40606. }
  40607. /**
  40608. * Expands the boundaries of this box to include the given point.
  40609. *
  40610. * @param {Vector2} point - The point that should be included by the bounding box.
  40611. * @return {Box2} A reference to this bounding box.
  40612. */
  40613. expandByPoint( point ) {
  40614. this.min.min( point );
  40615. this.max.max( point );
  40616. return this;
  40617. }
  40618. /**
  40619. * Expands this box equilaterally by the given vector. The width of this
  40620. * box will be expanded by the x component of the vector in both
  40621. * directions. The height of this box will be expanded by the y component of
  40622. * the vector in both directions.
  40623. *
  40624. * @param {Vector2} vector - The vector that should expand the bounding box.
  40625. * @return {Box2} A reference to this bounding box.
  40626. */
  40627. expandByVector( vector ) {
  40628. this.min.sub( vector );
  40629. this.max.add( vector );
  40630. return this;
  40631. }
  40632. /**
  40633. * Expands each dimension of the box by the given scalar. If negative, the
  40634. * dimensions of the box will be contracted.
  40635. *
  40636. * @param {number} scalar - The scalar value that should expand the bounding box.
  40637. * @return {Box2} A reference to this bounding box.
  40638. */
  40639. expandByScalar( scalar ) {
  40640. this.min.addScalar( - scalar );
  40641. this.max.addScalar( scalar );
  40642. return this;
  40643. }
  40644. /**
  40645. * Returns `true` if the given point lies within or on the boundaries of this box.
  40646. *
  40647. * @param {Vector2} point - The point to test.
  40648. * @return {boolean} Whether the bounding box contains the given point or not.
  40649. */
  40650. containsPoint( point ) {
  40651. return point.x >= this.min.x && point.x <= this.max.x &&
  40652. point.y >= this.min.y && point.y <= this.max.y;
  40653. }
  40654. /**
  40655. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40656. * If this box and the given one are identical, this function also returns `true`.
  40657. *
  40658. * @param {Box2} box - The bounding box to test.
  40659. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40660. */
  40661. containsBox( box ) {
  40662. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40663. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40664. }
  40665. /**
  40666. * Returns a point as a proportion of this box's width and height.
  40667. *
  40668. * @param {Vector2} point - A point in 2D space.
  40669. * @param {Vector2} target - The target vector that is used to store the method's result.
  40670. * @return {Vector2} A point as a proportion of this box's width and height.
  40671. */
  40672. getParameter( point, target ) {
  40673. // This can potentially have a divide by zero if the box
  40674. // has a size dimension of 0.
  40675. return target.set(
  40676. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40677. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40678. );
  40679. }
  40680. /**
  40681. * Returns `true` if the given bounding box intersects with this bounding box.
  40682. *
  40683. * @param {Box2} box - The bounding box to test.
  40684. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40685. */
  40686. intersectsBox( box ) {
  40687. // using 4 splitting planes to rule out intersections
  40688. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40689. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40690. }
  40691. /**
  40692. * Clamps the given point within the bounds of this box.
  40693. *
  40694. * @param {Vector2} point - The point to clamp.
  40695. * @param {Vector2} target - The target vector that is used to store the method's result.
  40696. * @return {Vector2} The clamped point.
  40697. */
  40698. clampPoint( point, target ) {
  40699. return target.copy( point ).clamp( this.min, this.max );
  40700. }
  40701. /**
  40702. * Returns the euclidean distance from any edge of this box to the specified point. If
  40703. * the given point lies inside of this box, the distance will be `0`.
  40704. *
  40705. * @param {Vector2} point - The point to compute the distance to.
  40706. * @return {number} The euclidean distance.
  40707. */
  40708. distanceToPoint( point ) {
  40709. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40710. }
  40711. /**
  40712. * Computes the intersection of this bounding box and the given one, setting the upper
  40713. * bound of this box to the lesser of the two boxes' upper bounds and the
  40714. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40715. * there's no overlap, makes this box empty.
  40716. *
  40717. * @param {Box2} box - The bounding box to intersect with.
  40718. * @return {Box2} A reference to this bounding box.
  40719. */
  40720. intersect( box ) {
  40721. this.min.max( box.min );
  40722. this.max.min( box.max );
  40723. if ( this.isEmpty() ) this.makeEmpty();
  40724. return this;
  40725. }
  40726. /**
  40727. * Computes the union of this box and another and the given one, setting the upper
  40728. * bound of this box to the greater of the two boxes' upper bounds and the
  40729. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40730. *
  40731. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40732. * @return {Box2} A reference to this bounding box.
  40733. */
  40734. union( box ) {
  40735. this.min.min( box.min );
  40736. this.max.max( box.max );
  40737. return this;
  40738. }
  40739. /**
  40740. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40741. * effectively moving it in 2D space.
  40742. *
  40743. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40744. * @return {Box2} A reference to this bounding box.
  40745. */
  40746. translate( offset ) {
  40747. this.min.add( offset );
  40748. this.max.add( offset );
  40749. return this;
  40750. }
  40751. /**
  40752. * Returns `true` if this bounding box is equal with the given one.
  40753. *
  40754. * @param {Box2} box - The box to test for equality.
  40755. * @return {boolean} Whether this bounding box is equal with the given one.
  40756. */
  40757. equals( box ) {
  40758. return box.min.equals( this.min ) && box.max.equals( this.max );
  40759. }
  40760. }
  40761. const _startP = /*@__PURE__*/ new Vector3();
  40762. const _startEnd = /*@__PURE__*/ new Vector3();
  40763. const _d1 = /*@__PURE__*/ new Vector3();
  40764. const _d2 = /*@__PURE__*/ new Vector3();
  40765. const _r = /*@__PURE__*/ new Vector3();
  40766. const _c1 = /*@__PURE__*/ new Vector3();
  40767. const _c2 = /*@__PURE__*/ new Vector3();
  40768. /**
  40769. * An analytical line segment in 3D space represented by a start and end point.
  40770. */
  40771. class Line3 {
  40772. /**
  40773. * Constructs a new line segment.
  40774. *
  40775. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40776. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40777. */
  40778. constructor( start = new Vector3(), end = new Vector3() ) {
  40779. /**
  40780. * Start of the line segment.
  40781. *
  40782. * @type {Vector3}
  40783. */
  40784. this.start = start;
  40785. /**
  40786. * End of the line segment.
  40787. *
  40788. * @type {Vector3}
  40789. */
  40790. this.end = end;
  40791. }
  40792. /**
  40793. * Sets the start and end values by copying the given vectors.
  40794. *
  40795. * @param {Vector3} start - The start point.
  40796. * @param {Vector3} end - The end point.
  40797. * @return {Line3} A reference to this line segment.
  40798. */
  40799. set( start, end ) {
  40800. this.start.copy( start );
  40801. this.end.copy( end );
  40802. return this;
  40803. }
  40804. /**
  40805. * Copies the values of the given line segment to this instance.
  40806. *
  40807. * @param {Line3} line - The line segment to copy.
  40808. * @return {Line3} A reference to this line segment.
  40809. */
  40810. copy( line ) {
  40811. this.start.copy( line.start );
  40812. this.end.copy( line.end );
  40813. return this;
  40814. }
  40815. /**
  40816. * Returns the center of the line segment.
  40817. *
  40818. * @param {Vector3} target - The target vector that is used to store the method's result.
  40819. * @return {Vector3} The center point.
  40820. */
  40821. getCenter( target ) {
  40822. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40823. }
  40824. /**
  40825. * Returns the delta vector of the line segment's start and end point.
  40826. *
  40827. * @param {Vector3} target - The target vector that is used to store the method's result.
  40828. * @return {Vector3} The delta vector.
  40829. */
  40830. delta( target ) {
  40831. return target.subVectors( this.end, this.start );
  40832. }
  40833. /**
  40834. * Returns the squared Euclidean distance between the line' start and end point.
  40835. *
  40836. * @return {number} The squared Euclidean distance.
  40837. */
  40838. distanceSq() {
  40839. return this.start.distanceToSquared( this.end );
  40840. }
  40841. /**
  40842. * Returns the Euclidean distance between the line' start and end point.
  40843. *
  40844. * @return {number} The Euclidean distance.
  40845. */
  40846. distance() {
  40847. return this.start.distanceTo( this.end );
  40848. }
  40849. /**
  40850. * Returns a vector at a certain position along the line segment.
  40851. *
  40852. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40853. * @param {Vector3} target - The target vector that is used to store the method's result.
  40854. * @return {Vector3} The delta vector.
  40855. */
  40856. at( t, target ) {
  40857. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40858. }
  40859. /**
  40860. * Returns a point parameter based on the closest point as projected on the line segment.
  40861. *
  40862. * @param {Vector3} point - The point for which to return a point parameter.
  40863. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40864. * @return {number} The point parameter.
  40865. */
  40866. closestPointToPointParameter( point, clampToLine ) {
  40867. _startP.subVectors( point, this.start );
  40868. _startEnd.subVectors( this.end, this.start );
  40869. const startEnd2 = _startEnd.dot( _startEnd );
  40870. const startEnd_startP = _startEnd.dot( _startP );
  40871. let t = startEnd_startP / startEnd2;
  40872. if ( clampToLine ) {
  40873. t = clamp( t, 0, 1 );
  40874. }
  40875. return t;
  40876. }
  40877. /**
  40878. * Returns the closest point on the line for a given point.
  40879. *
  40880. * @param {Vector3} point - The point to compute the closest point on the line for.
  40881. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40882. * @param {Vector3} target - The target vector that is used to store the method's result.
  40883. * @return {Vector3} The closest point on the line.
  40884. */
  40885. closestPointToPoint( point, clampToLine, target ) {
  40886. const t = this.closestPointToPointParameter( point, clampToLine );
  40887. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40888. }
  40889. /**
  40890. * Returns the closest squared distance between this line segment and the given one.
  40891. *
  40892. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40893. * @param {Vector3} [c1] - The closest point on this line segment.
  40894. * @param {Vector3} [c2] - The closest point on the given line segment.
  40895. * @return {number} The squared distance between this line segment and the given one.
  40896. */
  40897. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40898. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40899. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40900. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40901. // distance between between S1(s) and S2(t)
  40902. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40903. let s, t;
  40904. const p1 = this.start;
  40905. const p2 = line.start;
  40906. const q1 = this.end;
  40907. const q2 = line.end;
  40908. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40909. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40910. _r.subVectors( p1, p2 );
  40911. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40912. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40913. const f = _d2.dot( _r );
  40914. // Check if either or both segments degenerate into points
  40915. if ( a <= EPSILON && e <= EPSILON ) {
  40916. // Both segments degenerate into points
  40917. c1.copy( p1 );
  40918. c2.copy( p2 );
  40919. c1.sub( c2 );
  40920. return c1.dot( c1 );
  40921. }
  40922. if ( a <= EPSILON ) {
  40923. // First segment degenerates into a point
  40924. s = 0;
  40925. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40926. t = clamp( t, 0, 1 );
  40927. } else {
  40928. const c = _d1.dot( _r );
  40929. if ( e <= EPSILON ) {
  40930. // Second segment degenerates into a point
  40931. t = 0;
  40932. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40933. } else {
  40934. // The general nondegenerate case starts here
  40935. const b = _d1.dot( _d2 );
  40936. const denom = a * e - b * b; // Always nonnegative
  40937. // If segments not parallel, compute closest point on L1 to L2 and
  40938. // clamp to segment S1. Else pick arbitrary s (here 0)
  40939. if ( denom !== 0 ) {
  40940. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40941. } else {
  40942. s = 0;
  40943. }
  40944. // Compute point on L2 closest to S1(s) using
  40945. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40946. t = ( b * s + f ) / e;
  40947. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40948. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40949. // and clamp s to [0, 1]
  40950. if ( t < 0 ) {
  40951. t = 0.;
  40952. s = clamp( - c / a, 0, 1 );
  40953. } else if ( t > 1 ) {
  40954. t = 1;
  40955. s = clamp( ( b - c ) / a, 0, 1 );
  40956. }
  40957. }
  40958. }
  40959. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40960. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40961. c1.sub( c2 );
  40962. return c1.dot( c1 );
  40963. }
  40964. /**
  40965. * Applies a 4x4 transformation matrix to this line segment.
  40966. *
  40967. * @param {Matrix4} matrix - The transformation matrix.
  40968. * @return {Line3} A reference to this line segment.
  40969. */
  40970. applyMatrix4( matrix ) {
  40971. this.start.applyMatrix4( matrix );
  40972. this.end.applyMatrix4( matrix );
  40973. return this;
  40974. }
  40975. /**
  40976. * Returns `true` if this line segment is equal with the given one.
  40977. *
  40978. * @param {Line3} line - The line segment to test for equality.
  40979. * @return {boolean} Whether this line segment is equal with the given one.
  40980. */
  40981. equals( line ) {
  40982. return line.start.equals( this.start ) && line.end.equals( this.end );
  40983. }
  40984. /**
  40985. * Returns a new line segment with copied values from this instance.
  40986. *
  40987. * @return {Line3} A clone of this instance.
  40988. */
  40989. clone() {
  40990. return new this.constructor().copy( this );
  40991. }
  40992. }
  40993. const _vector$3 = /*@__PURE__*/ new Vector3();
  40994. /**
  40995. * This displays a cone shaped helper object for a {@link SpotLight}.
  40996. *
  40997. * When the spot light or its target are transformed or light properties are
  40998. * changed, it's necessary to call the `update()` method of the respective helper.
  40999. *
  41000. * ```js
  41001. * const spotLight = new THREE.SpotLight( 0xffffff );
  41002. * spotLight.position.set( 10, 10, 10 );
  41003. * scene.add( spotLight );
  41004. *
  41005. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41006. * scene.add( spotLightHelper );
  41007. * ```
  41008. *
  41009. * @augments Object3D
  41010. */
  41011. class SpotLightHelper extends Object3D {
  41012. /**
  41013. * Constructs a new spot light helper.
  41014. *
  41015. * @param {HemisphereLight} light - The light to be visualized.
  41016. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41017. * the color of the light.
  41018. */
  41019. constructor( light, color ) {
  41020. super();
  41021. /**
  41022. * The light being visualized.
  41023. *
  41024. * @type {SpotLight}
  41025. */
  41026. this.light = light;
  41027. this.matrixAutoUpdate = false;
  41028. /**
  41029. * The color parameter passed in the constructor.
  41030. * If not set, the helper will take the color of the light.
  41031. *
  41032. * @type {number|Color|string}
  41033. */
  41034. this.color = color;
  41035. this.type = 'SpotLightHelper';
  41036. const geometry = new BufferGeometry();
  41037. const positions = [
  41038. 0, 0, 0, 0, 0, 1,
  41039. 0, 0, 0, 1, 0, 1,
  41040. 0, 0, 0, -1, 0, 1,
  41041. 0, 0, 0, 0, 1, 1,
  41042. 0, 0, 0, 0, -1, 1
  41043. ];
  41044. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41045. const p1 = ( i / l ) * Math.PI * 2;
  41046. const p2 = ( j / l ) * Math.PI * 2;
  41047. positions.push(
  41048. Math.cos( p1 ), Math.sin( p1 ), 1,
  41049. Math.cos( p2 ), Math.sin( p2 ), 1
  41050. );
  41051. }
  41052. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41053. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41054. this.cone = new LineSegments( geometry, material );
  41055. this.add( this.cone );
  41056. this.update();
  41057. }
  41058. /**
  41059. * Frees the GPU-related resources allocated by this instance. Call this
  41060. * method whenever this instance is no longer used in your app.
  41061. */
  41062. dispose() {
  41063. this.cone.geometry.dispose();
  41064. this.cone.material.dispose();
  41065. }
  41066. /**
  41067. * Updates the helper to match the position and direction of the
  41068. * light being visualized.
  41069. */
  41070. update() {
  41071. this.light.updateWorldMatrix( true, false );
  41072. this.light.target.updateWorldMatrix( true, false );
  41073. // update the local matrix based on the parent and light target transforms
  41074. if ( this.parent ) {
  41075. this.parent.updateWorldMatrix( true );
  41076. this.matrix
  41077. .copy( this.parent.matrixWorld )
  41078. .invert()
  41079. .multiply( this.light.matrixWorld );
  41080. } else {
  41081. this.matrix.copy( this.light.matrixWorld );
  41082. }
  41083. this.matrixWorld.copy( this.light.matrixWorld );
  41084. const coneLength = this.light.distance ? this.light.distance : 1000;
  41085. const coneWidth = coneLength * Math.tan( this.light.angle );
  41086. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41087. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41088. this.cone.lookAt( _vector$3 );
  41089. if ( this.color !== undefined ) {
  41090. this.cone.material.color.set( this.color );
  41091. } else {
  41092. this.cone.material.color.copy( this.light.color );
  41093. }
  41094. }
  41095. }
  41096. const _vector$2 = /*@__PURE__*/ new Vector3();
  41097. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41098. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41099. /**
  41100. * A helper object to assist with visualizing a {@link Skeleton}.
  41101. *
  41102. * ```js
  41103. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41104. * scene.add( helper );
  41105. * ```
  41106. *
  41107. * @augments LineSegments
  41108. */
  41109. class SkeletonHelper extends LineSegments {
  41110. /**
  41111. * Constructs a new skeleton helper.
  41112. *
  41113. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41114. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41115. */
  41116. constructor( object ) {
  41117. const bones = getBoneList( object );
  41118. const geometry = new BufferGeometry();
  41119. const vertices = [];
  41120. const colors = [];
  41121. for ( let i = 0; i < bones.length; i ++ ) {
  41122. const bone = bones[ i ];
  41123. if ( bone.parent && bone.parent.isBone ) {
  41124. vertices.push( 0, 0, 0 );
  41125. vertices.push( 0, 0, 0 );
  41126. colors.push( 0, 0, 0 );
  41127. colors.push( 0, 0, 0 );
  41128. }
  41129. }
  41130. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41131. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41132. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41133. super( geometry, material );
  41134. /**
  41135. * This flag can be used for type testing.
  41136. *
  41137. * @type {boolean}
  41138. * @readonly
  41139. * @default true
  41140. */
  41141. this.isSkeletonHelper = true;
  41142. this.type = 'SkeletonHelper';
  41143. /**
  41144. * The object being visualized.
  41145. *
  41146. * @type {Object3D}
  41147. */
  41148. this.root = object;
  41149. /**
  41150. * The list of bones that the helper visualizes.
  41151. *
  41152. * @type {Array<Bone>}
  41153. */
  41154. this.bones = bones;
  41155. this.matrix = object.matrixWorld;
  41156. this.matrixAutoUpdate = false;
  41157. // colors
  41158. const color1 = new Color( 0x0000ff );
  41159. const color2 = new Color( 0x00ff00 );
  41160. this.setColors( color1, color2 );
  41161. }
  41162. updateMatrixWorld( force ) {
  41163. const bones = this.bones;
  41164. const geometry = this.geometry;
  41165. const position = geometry.getAttribute( 'position' );
  41166. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41167. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41168. const bone = bones[ i ];
  41169. if ( bone.parent && bone.parent.isBone ) {
  41170. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41171. _vector$2.setFromMatrixPosition( _boneMatrix );
  41172. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41173. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41174. _vector$2.setFromMatrixPosition( _boneMatrix );
  41175. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41176. j += 2;
  41177. }
  41178. }
  41179. geometry.getAttribute( 'position' ).needsUpdate = true;
  41180. super.updateMatrixWorld( force );
  41181. }
  41182. /**
  41183. * Defines the colors of the helper.
  41184. *
  41185. * @param {Color} color1 - The first line color for each bone.
  41186. * @param {Color} color2 - The second line color for each bone.
  41187. * @return {SkeletonHelper} A reference to this helper.
  41188. */
  41189. setColors( color1, color2 ) {
  41190. const geometry = this.geometry;
  41191. const colorAttribute = geometry.getAttribute( 'color' );
  41192. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41193. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41194. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41195. }
  41196. colorAttribute.needsUpdate = true;
  41197. return this;
  41198. }
  41199. /**
  41200. * Frees the GPU-related resources allocated by this instance. Call this
  41201. * method whenever this instance is no longer used in your app.
  41202. */
  41203. dispose() {
  41204. this.geometry.dispose();
  41205. this.material.dispose();
  41206. }
  41207. }
  41208. function getBoneList( object ) {
  41209. const boneList = [];
  41210. if ( object.isBone === true ) {
  41211. boneList.push( object );
  41212. }
  41213. for ( let i = 0; i < object.children.length; i ++ ) {
  41214. boneList.push( ...getBoneList( object.children[ i ] ) );
  41215. }
  41216. return boneList;
  41217. }
  41218. /**
  41219. * This displays a helper object consisting of a spherical mesh for
  41220. * visualizing an instance of {@link PointLight}.
  41221. *
  41222. * ```js
  41223. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41224. * pointLight.position.set( 10, 10, 10 );
  41225. * scene.add( pointLight );
  41226. *
  41227. * const sphereSize = 1;
  41228. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41229. * scene.add( pointLightHelper );
  41230. * ```
  41231. *
  41232. * @augments Mesh
  41233. */
  41234. class PointLightHelper extends Mesh {
  41235. /**
  41236. * Constructs a new point light helper.
  41237. *
  41238. * @param {PointLight} light - The light to be visualized.
  41239. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41240. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41241. * the color of the light.
  41242. */
  41243. constructor( light, sphereSize, color ) {
  41244. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41245. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41246. super( geometry, material );
  41247. /**
  41248. * The light being visualized.
  41249. *
  41250. * @type {PointLight}
  41251. */
  41252. this.light = light;
  41253. /**
  41254. * The color parameter passed in the constructor.
  41255. * If not set, the helper will take the color of the light.
  41256. *
  41257. * @type {number|Color|string}
  41258. */
  41259. this.color = color;
  41260. this.type = 'PointLightHelper';
  41261. this.matrix = this.light.matrixWorld;
  41262. this.matrixAutoUpdate = false;
  41263. this.update();
  41264. /*
  41265. // TODO: delete this comment?
  41266. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41267. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41268. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41269. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41270. const d = light.distance;
  41271. if ( d === 0.0 ) {
  41272. this.lightDistance.visible = false;
  41273. } else {
  41274. this.lightDistance.scale.set( d, d, d );
  41275. }
  41276. this.add( this.lightDistance );
  41277. */
  41278. }
  41279. /**
  41280. * Frees the GPU-related resources allocated by this instance. Call this
  41281. * method whenever this instance is no longer used in your app.
  41282. */
  41283. dispose() {
  41284. this.geometry.dispose();
  41285. this.material.dispose();
  41286. }
  41287. /**
  41288. * Updates the helper to match the position of the
  41289. * light being visualized.
  41290. */
  41291. update() {
  41292. this.light.updateWorldMatrix( true, false );
  41293. if ( this.color !== undefined ) {
  41294. this.material.color.set( this.color );
  41295. } else {
  41296. this.material.color.copy( this.light.color );
  41297. }
  41298. /*
  41299. const d = this.light.distance;
  41300. if ( d === 0.0 ) {
  41301. this.lightDistance.visible = false;
  41302. } else {
  41303. this.lightDistance.visible = true;
  41304. this.lightDistance.scale.set( d, d, d );
  41305. }
  41306. */
  41307. }
  41308. }
  41309. const _vector$1 = /*@__PURE__*/ new Vector3();
  41310. const _color1 = /*@__PURE__*/ new Color();
  41311. const _color2 = /*@__PURE__*/ new Color();
  41312. /**
  41313. * Creates a visual aid consisting of a spherical mesh for a
  41314. * given {@link HemisphereLight}.
  41315. *
  41316. * When the hemisphere light is transformed or its light properties are changed,
  41317. * it's necessary to call the `update()` method of the respective helper.
  41318. *
  41319. * ```js
  41320. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41321. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41322. * scene.add( helper );
  41323. * ```
  41324. *
  41325. * @augments Object3D
  41326. */
  41327. class HemisphereLightHelper extends Object3D {
  41328. /**
  41329. * Constructs a new hemisphere light helper.
  41330. *
  41331. * @param {HemisphereLight} light - The light to be visualized.
  41332. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41333. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41334. * the color of the light.
  41335. */
  41336. constructor( light, size, color ) {
  41337. super();
  41338. /**
  41339. * The light being visualized.
  41340. *
  41341. * @type {HemisphereLight}
  41342. */
  41343. this.light = light;
  41344. this.matrix = light.matrixWorld;
  41345. this.matrixAutoUpdate = false;
  41346. /**
  41347. * The color parameter passed in the constructor.
  41348. * If not set, the helper will take the color of the light.
  41349. *
  41350. * @type {number|Color|string}
  41351. */
  41352. this.color = color;
  41353. this.type = 'HemisphereLightHelper';
  41354. const geometry = new OctahedronGeometry( size );
  41355. geometry.rotateY( Math.PI * 0.5 );
  41356. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41357. if ( this.color === undefined ) this.material.vertexColors = true;
  41358. const position = geometry.getAttribute( 'position' );
  41359. const colors = new Float32Array( position.count * 3 );
  41360. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41361. this.add( new Mesh( geometry, this.material ) );
  41362. this.update();
  41363. }
  41364. /**
  41365. * Frees the GPU-related resources allocated by this instance. Call this
  41366. * method whenever this instance is no longer used in your app.
  41367. */
  41368. dispose() {
  41369. this.children[ 0 ].geometry.dispose();
  41370. this.children[ 0 ].material.dispose();
  41371. }
  41372. /**
  41373. * Updates the helper to match the position and direction of the
  41374. * light being visualized.
  41375. */
  41376. update() {
  41377. const mesh = this.children[ 0 ];
  41378. if ( this.color !== undefined ) {
  41379. this.material.color.set( this.color );
  41380. } else {
  41381. const colors = mesh.geometry.getAttribute( 'color' );
  41382. _color1.copy( this.light.color );
  41383. _color2.copy( this.light.groundColor );
  41384. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41385. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41386. colors.setXYZ( i, color.r, color.g, color.b );
  41387. }
  41388. colors.needsUpdate = true;
  41389. }
  41390. this.light.updateWorldMatrix( true, false );
  41391. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41392. }
  41393. }
  41394. /**
  41395. * The helper is an object to define grids. Grids are two-dimensional
  41396. * arrays of lines.
  41397. *
  41398. * ```js
  41399. * const size = 10;
  41400. * const divisions = 10;
  41401. *
  41402. * const gridHelper = new THREE.GridHelper( size, divisions );
  41403. * scene.add( gridHelper );
  41404. * ```
  41405. *
  41406. * @augments LineSegments
  41407. */
  41408. class GridHelper extends LineSegments {
  41409. /**
  41410. * Constructs a new grid helper.
  41411. *
  41412. * @param {number} [size=10] - The size of the grid.
  41413. * @param {number} [divisions=10] - The number of divisions across the grid.
  41414. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41415. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41416. */
  41417. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41418. color1 = new Color( color1 );
  41419. color2 = new Color( color2 );
  41420. const center = divisions / 2;
  41421. const step = size / divisions;
  41422. const halfSize = size / 2;
  41423. const vertices = [], colors = [];
  41424. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41425. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41426. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41427. const color = i === center ? color1 : color2;
  41428. color.toArray( colors, j ); j += 3;
  41429. color.toArray( colors, j ); j += 3;
  41430. color.toArray( colors, j ); j += 3;
  41431. color.toArray( colors, j ); j += 3;
  41432. }
  41433. const geometry = new BufferGeometry();
  41434. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41435. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41436. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41437. super( geometry, material );
  41438. this.type = 'GridHelper';
  41439. }
  41440. /**
  41441. * Frees the GPU-related resources allocated by this instance. Call this
  41442. * method whenever this instance is no longer used in your app.
  41443. */
  41444. dispose() {
  41445. this.geometry.dispose();
  41446. this.material.dispose();
  41447. }
  41448. }
  41449. /**
  41450. * This helper is an object to define polar grids. Grids are
  41451. * two-dimensional arrays of lines.
  41452. *
  41453. * ```js
  41454. * const radius = 10;
  41455. * const sectors = 16;
  41456. * const rings = 8;
  41457. * const divisions = 64;
  41458. *
  41459. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41460. * scene.add( helper );
  41461. * ```
  41462. *
  41463. * @augments LineSegments
  41464. */
  41465. class PolarGridHelper extends LineSegments {
  41466. /**
  41467. * Constructs a new polar grid helper.
  41468. *
  41469. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41470. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41471. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41472. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41473. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41474. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41475. */
  41476. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41477. color1 = new Color( color1 );
  41478. color2 = new Color( color2 );
  41479. const vertices = [];
  41480. const colors = [];
  41481. // create the sectors
  41482. if ( sectors > 1 ) {
  41483. for ( let i = 0; i < sectors; i ++ ) {
  41484. const v = ( i / sectors ) * ( Math.PI * 2 );
  41485. const x = Math.sin( v ) * radius;
  41486. const z = Math.cos( v ) * radius;
  41487. vertices.push( 0, 0, 0 );
  41488. vertices.push( x, 0, z );
  41489. const color = ( i & 1 ) ? color1 : color2;
  41490. colors.push( color.r, color.g, color.b );
  41491. colors.push( color.r, color.g, color.b );
  41492. }
  41493. }
  41494. // create the rings
  41495. for ( let i = 0; i < rings; i ++ ) {
  41496. const color = ( i & 1 ) ? color1 : color2;
  41497. const r = radius - ( radius / rings * i );
  41498. for ( let j = 0; j < divisions; j ++ ) {
  41499. // first vertex
  41500. let v = ( j / divisions ) * ( Math.PI * 2 );
  41501. let x = Math.sin( v ) * r;
  41502. let z = Math.cos( v ) * r;
  41503. vertices.push( x, 0, z );
  41504. colors.push( color.r, color.g, color.b );
  41505. // second vertex
  41506. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41507. x = Math.sin( v ) * r;
  41508. z = Math.cos( v ) * r;
  41509. vertices.push( x, 0, z );
  41510. colors.push( color.r, color.g, color.b );
  41511. }
  41512. }
  41513. const geometry = new BufferGeometry();
  41514. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41515. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41516. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41517. super( geometry, material );
  41518. this.type = 'PolarGridHelper';
  41519. }
  41520. /**
  41521. * Frees the GPU-related resources allocated by this instance. Call this
  41522. * method whenever this instance is no longer used in your app.
  41523. */
  41524. dispose() {
  41525. this.geometry.dispose();
  41526. this.material.dispose();
  41527. }
  41528. }
  41529. const _v1 = /*@__PURE__*/ new Vector3();
  41530. const _v2 = /*@__PURE__*/ new Vector3();
  41531. const _v3 = /*@__PURE__*/ new Vector3();
  41532. /**
  41533. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41534. * effect on the scene. This consists of a plane and a line representing the
  41535. * light's position and direction.
  41536. *
  41537. * When the directional light or its target are transformed or light properties
  41538. * are changed, it's necessary to call the `update()` method of the respective helper.
  41539. *
  41540. * ```js
  41541. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41542. * scene.add( light );
  41543. *
  41544. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41545. * scene.add( helper );
  41546. * ```
  41547. *
  41548. * @augments Object3D
  41549. */
  41550. class DirectionalLightHelper extends Object3D {
  41551. /**
  41552. * Constructs a new directional light helper.
  41553. *
  41554. * @param {DirectionalLight} light - The light to be visualized.
  41555. * @param {number} [size=1] - The dimensions of the plane.
  41556. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41557. * the color of the light.
  41558. */
  41559. constructor( light, size, color ) {
  41560. super();
  41561. /**
  41562. * The light being visualized.
  41563. *
  41564. * @type {DirectionalLight}
  41565. */
  41566. this.light = light;
  41567. this.matrix = light.matrixWorld;
  41568. this.matrixAutoUpdate = false;
  41569. /**
  41570. * The color parameter passed in the constructor.
  41571. * If not set, the helper will take the color of the light.
  41572. *
  41573. * @type {number|Color|string}
  41574. */
  41575. this.color = color;
  41576. this.type = 'DirectionalLightHelper';
  41577. if ( size === undefined ) size = 1;
  41578. let geometry = new BufferGeometry();
  41579. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41580. - size, size, 0,
  41581. size, size, 0,
  41582. size, - size, 0,
  41583. - size, - size, 0,
  41584. - size, size, 0
  41585. ], 3 ) );
  41586. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41587. /**
  41588. * Contains the line showing the location of the directional light.
  41589. *
  41590. * @type {Line}
  41591. */
  41592. this.lightPlane = new Line( geometry, material );
  41593. this.add( this.lightPlane );
  41594. geometry = new BufferGeometry();
  41595. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41596. /**
  41597. * Represents the target line of the directional light.
  41598. *
  41599. * @type {Line}
  41600. */
  41601. this.targetLine = new Line( geometry, material );
  41602. this.add( this.targetLine );
  41603. this.update();
  41604. }
  41605. /**
  41606. * Frees the GPU-related resources allocated by this instance. Call this
  41607. * method whenever this instance is no longer used in your app.
  41608. */
  41609. dispose() {
  41610. this.lightPlane.geometry.dispose();
  41611. this.lightPlane.material.dispose();
  41612. this.targetLine.geometry.dispose();
  41613. this.targetLine.material.dispose();
  41614. }
  41615. /**
  41616. * Updates the helper to match the position and direction of the
  41617. * light being visualized.
  41618. */
  41619. update() {
  41620. this.light.updateWorldMatrix( true, false );
  41621. this.light.target.updateWorldMatrix( true, false );
  41622. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41623. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41624. _v3.subVectors( _v2, _v1 );
  41625. this.lightPlane.lookAt( _v2 );
  41626. if ( this.color !== undefined ) {
  41627. this.lightPlane.material.color.set( this.color );
  41628. this.targetLine.material.color.set( this.color );
  41629. } else {
  41630. this.lightPlane.material.color.copy( this.light.color );
  41631. this.targetLine.material.color.copy( this.light.color );
  41632. }
  41633. this.targetLine.lookAt( _v2 );
  41634. this.targetLine.scale.z = _v3.length();
  41635. }
  41636. }
  41637. const _vector = /*@__PURE__*/ new Vector3();
  41638. const _camera = /*@__PURE__*/ new Camera();
  41639. /**
  41640. * This helps with visualizing what a camera contains in its frustum. It
  41641. * visualizes the frustum of a camera using a line segments.
  41642. *
  41643. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41644. *
  41645. * `CameraHelper` must be a child of the scene.
  41646. *
  41647. * When the camera is transformed or its projection matrix is changed, it's necessary
  41648. * to call the `update()` method of the respective helper.
  41649. *
  41650. * ```js
  41651. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41652. * const helper = new THREE.CameraHelper( camera );
  41653. * scene.add( helper );
  41654. * ```
  41655. *
  41656. * @augments LineSegments
  41657. */
  41658. class CameraHelper extends LineSegments {
  41659. /**
  41660. * Constructs a new arrow helper.
  41661. *
  41662. * @param {Camera} camera - The camera to visualize.
  41663. */
  41664. constructor( camera ) {
  41665. const geometry = new BufferGeometry();
  41666. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41667. const vertices = [];
  41668. const colors = [];
  41669. const pointMap = {};
  41670. // near
  41671. addLine( 'n1', 'n2' );
  41672. addLine( 'n2', 'n4' );
  41673. addLine( 'n4', 'n3' );
  41674. addLine( 'n3', 'n1' );
  41675. // far
  41676. addLine( 'f1', 'f2' );
  41677. addLine( 'f2', 'f4' );
  41678. addLine( 'f4', 'f3' );
  41679. addLine( 'f3', 'f1' );
  41680. // sides
  41681. addLine( 'n1', 'f1' );
  41682. addLine( 'n2', 'f2' );
  41683. addLine( 'n3', 'f3' );
  41684. addLine( 'n4', 'f4' );
  41685. // cone
  41686. addLine( 'p', 'n1' );
  41687. addLine( 'p', 'n2' );
  41688. addLine( 'p', 'n3' );
  41689. addLine( 'p', 'n4' );
  41690. // up
  41691. addLine( 'u1', 'u2' );
  41692. addLine( 'u2', 'u3' );
  41693. addLine( 'u3', 'u1' );
  41694. // target
  41695. addLine( 'c', 't' );
  41696. addLine( 'p', 'c' );
  41697. // cross
  41698. addLine( 'cn1', 'cn2' );
  41699. addLine( 'cn3', 'cn4' );
  41700. addLine( 'cf1', 'cf2' );
  41701. addLine( 'cf3', 'cf4' );
  41702. function addLine( a, b ) {
  41703. addPoint( a );
  41704. addPoint( b );
  41705. }
  41706. function addPoint( id ) {
  41707. vertices.push( 0, 0, 0 );
  41708. colors.push( 0, 0, 0 );
  41709. if ( pointMap[ id ] === undefined ) {
  41710. pointMap[ id ] = [];
  41711. }
  41712. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41713. }
  41714. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41715. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41716. super( geometry, material );
  41717. this.type = 'CameraHelper';
  41718. /**
  41719. * The camera being visualized.
  41720. *
  41721. * @type {Camera}
  41722. */
  41723. this.camera = camera;
  41724. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41725. this.matrix = camera.matrixWorld;
  41726. this.matrixAutoUpdate = false;
  41727. /**
  41728. * This contains the points used to visualize the camera.
  41729. *
  41730. * @type {Object<string,Array<number>>}
  41731. */
  41732. this.pointMap = pointMap;
  41733. this.update();
  41734. // colors
  41735. const colorFrustum = new Color( 0xffaa00 );
  41736. const colorCone = new Color( 0xff0000 );
  41737. const colorUp = new Color( 0x00aaff );
  41738. const colorTarget = new Color( 0xffffff );
  41739. const colorCross = new Color( 0x333333 );
  41740. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41741. }
  41742. /**
  41743. * Defines the colors of the helper.
  41744. *
  41745. * @param {Color} frustum - The frustum line color.
  41746. * @param {Color} cone - The cone line color.
  41747. * @param {Color} up - The up line color.
  41748. * @param {Color} target - The target line color.
  41749. * @param {Color} cross - The cross line color.
  41750. * @return {CameraHelper} A reference to this helper.
  41751. */
  41752. setColors( frustum, cone, up, target, cross ) {
  41753. const geometry = this.geometry;
  41754. const colorAttribute = geometry.getAttribute( 'color' );
  41755. // near
  41756. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41757. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41758. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41759. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41760. // far
  41761. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41762. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41763. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41764. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41765. // sides
  41766. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41767. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41768. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41769. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41770. // cone
  41771. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41772. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41773. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41774. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41775. // up
  41776. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41777. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41778. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41779. // target
  41780. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41781. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41782. // cross
  41783. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41784. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41785. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41786. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41787. colorAttribute.needsUpdate = true;
  41788. return this;
  41789. }
  41790. /**
  41791. * Updates the helper based on the projection matrix of the camera.
  41792. */
  41793. update() {
  41794. const geometry = this.geometry;
  41795. const pointMap = this.pointMap;
  41796. const w = 1, h = 1;
  41797. let nearZ, farZ;
  41798. // we need just camera projection matrix inverse
  41799. // world matrix must be identity
  41800. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41801. // Adjust z values based on coordinate system
  41802. if ( this.camera.reversedDepth === true ) {
  41803. nearZ = 1;
  41804. farZ = 0;
  41805. } else {
  41806. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41807. nearZ = -1;
  41808. farZ = 1;
  41809. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41810. nearZ = 0;
  41811. farZ = 1;
  41812. } else {
  41813. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41814. }
  41815. }
  41816. // center / target
  41817. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41818. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41819. // near
  41820. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41821. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41822. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41823. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41824. // far
  41825. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41826. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41827. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41828. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41829. // up
  41830. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41831. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41832. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41833. // cross
  41834. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41835. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41836. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41837. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41838. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41839. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41840. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41841. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41842. geometry.getAttribute( 'position' ).needsUpdate = true;
  41843. }
  41844. /**
  41845. * Frees the GPU-related resources allocated by this instance. Call this
  41846. * method whenever this instance is no longer used in your app.
  41847. */
  41848. dispose() {
  41849. this.geometry.dispose();
  41850. this.material.dispose();
  41851. }
  41852. }
  41853. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41854. _vector.set( x, y, z ).unproject( camera );
  41855. const points = pointMap[ point ];
  41856. if ( points !== undefined ) {
  41857. const position = geometry.getAttribute( 'position' );
  41858. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41859. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41860. }
  41861. }
  41862. }
  41863. const _box = /*@__PURE__*/ new Box3();
  41864. /**
  41865. * Helper object to graphically show the world-axis-aligned bounding box
  41866. * around an object. The actual bounding box is handled with {@link Box3},
  41867. * this is just a visual helper for debugging. It can be automatically
  41868. * resized with {@link BoxHelper#update} when the object it's created from
  41869. * is transformed. Note that the object must have a geometry for this to work,
  41870. * so it won't work with sprites.
  41871. *
  41872. * ```js
  41873. * const sphere = new THREE.SphereGeometry();
  41874. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41875. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41876. * scene.add( box );
  41877. * ```
  41878. *
  41879. * @augments LineSegments
  41880. */
  41881. class BoxHelper extends LineSegments {
  41882. /**
  41883. * Constructs a new box helper.
  41884. *
  41885. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41886. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41887. */
  41888. constructor( object, color = 0xffff00 ) {
  41889. 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 ] );
  41890. const positions = new Float32Array( 8 * 3 );
  41891. const geometry = new BufferGeometry();
  41892. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41893. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41894. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41895. /**
  41896. * The 3D object being visualized.
  41897. *
  41898. * @type {Object3D}
  41899. */
  41900. this.object = object;
  41901. this.type = 'BoxHelper';
  41902. this.matrixAutoUpdate = false;
  41903. this.update();
  41904. }
  41905. /**
  41906. * Updates the helper's geometry to match the dimensions of the object,
  41907. * including any children.
  41908. */
  41909. update() {
  41910. if ( this.object !== undefined ) {
  41911. _box.setFromObject( this.object );
  41912. }
  41913. if ( _box.isEmpty() ) return;
  41914. const min = _box.min;
  41915. const max = _box.max;
  41916. /*
  41917. 5____4
  41918. 1/___0/|
  41919. | 6__|_7
  41920. 2/___3/
  41921. 0: max.x, max.y, max.z
  41922. 1: min.x, max.y, max.z
  41923. 2: min.x, min.y, max.z
  41924. 3: max.x, min.y, max.z
  41925. 4: max.x, max.y, min.z
  41926. 5: min.x, max.y, min.z
  41927. 6: min.x, min.y, min.z
  41928. 7: max.x, min.y, min.z
  41929. */
  41930. const position = this.geometry.attributes.position;
  41931. const array = position.array;
  41932. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41933. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41934. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41935. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41936. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41937. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41938. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41939. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41940. position.needsUpdate = true;
  41941. this.geometry.computeBoundingSphere();
  41942. }
  41943. /**
  41944. * Updates the wireframe box for the passed object.
  41945. *
  41946. * @param {Object3D} object - The 3D object to create the helper for.
  41947. * @return {BoxHelper} A reference to this instance.
  41948. */
  41949. setFromObject( object ) {
  41950. this.object = object;
  41951. this.update();
  41952. return this;
  41953. }
  41954. copy( source, recursive ) {
  41955. super.copy( source, recursive );
  41956. this.object = source.object;
  41957. return this;
  41958. }
  41959. /**
  41960. * Frees the GPU-related resources allocated by this instance. Call this
  41961. * method whenever this instance is no longer used in your app.
  41962. */
  41963. dispose() {
  41964. this.geometry.dispose();
  41965. this.material.dispose();
  41966. }
  41967. }
  41968. /**
  41969. * A helper object to visualize an instance of {@link Box3}.
  41970. *
  41971. * ```js
  41972. * const box = new THREE.Box3();
  41973. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41974. *
  41975. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41976. * scene.add( helper )
  41977. * ```
  41978. *
  41979. * @augments LineSegments
  41980. */
  41981. class Box3Helper extends LineSegments {
  41982. /**
  41983. * Constructs a new box3 helper.
  41984. *
  41985. * @param {Box3} box - The box to visualize.
  41986. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41987. */
  41988. constructor( box, color = 0xffff00 ) {
  41989. 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 ] );
  41990. 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 ];
  41991. const geometry = new BufferGeometry();
  41992. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41993. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41994. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41995. /**
  41996. * The box being visualized.
  41997. *
  41998. * @type {Box3}
  41999. */
  42000. this.box = box;
  42001. this.type = 'Box3Helper';
  42002. this.geometry.computeBoundingSphere();
  42003. }
  42004. updateMatrixWorld( force ) {
  42005. const box = this.box;
  42006. if ( box.isEmpty() ) return;
  42007. box.getCenter( this.position );
  42008. box.getSize( this.scale );
  42009. this.scale.multiplyScalar( 0.5 );
  42010. super.updateMatrixWorld( force );
  42011. }
  42012. /**
  42013. * Frees the GPU-related resources allocated by this instance. Call this
  42014. * method whenever this instance is no longer used in your app.
  42015. */
  42016. dispose() {
  42017. this.geometry.dispose();
  42018. this.material.dispose();
  42019. }
  42020. }
  42021. /**
  42022. * A helper object to visualize an instance of {@link Plane}.
  42023. *
  42024. * ```js
  42025. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42026. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42027. * scene.add( helper );
  42028. * ```
  42029. *
  42030. * @augments Line
  42031. */
  42032. class PlaneHelper extends Line {
  42033. /**
  42034. * Constructs a new plane helper.
  42035. *
  42036. * @param {Plane} plane - The plane to be visualized.
  42037. * @param {number} [size=1] - The side length of plane helper.
  42038. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42039. */
  42040. constructor( plane, size = 1, hex = 0xffff00 ) {
  42041. const color = hex;
  42042. 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 ];
  42043. const geometry = new BufferGeometry();
  42044. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42045. geometry.computeBoundingSphere();
  42046. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42047. this.type = 'PlaneHelper';
  42048. /**
  42049. * The plane being visualized.
  42050. *
  42051. * @type {Plane}
  42052. */
  42053. this.plane = plane;
  42054. /**
  42055. * The side length of plane helper.
  42056. *
  42057. * @type {number}
  42058. * @default 1
  42059. */
  42060. this.size = size;
  42061. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42062. const geometry2 = new BufferGeometry();
  42063. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42064. geometry2.computeBoundingSphere();
  42065. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42066. }
  42067. updateMatrixWorld( force ) {
  42068. this.position.set( 0, 0, 0 );
  42069. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42070. this.lookAt( this.plane.normal );
  42071. this.translateZ( - this.plane.constant );
  42072. super.updateMatrixWorld( force );
  42073. }
  42074. /**
  42075. * Updates the helper to match the position and direction of the
  42076. * light being visualized.
  42077. */
  42078. dispose() {
  42079. this.geometry.dispose();
  42080. this.material.dispose();
  42081. this.children[ 0 ].geometry.dispose();
  42082. this.children[ 0 ].material.dispose();
  42083. }
  42084. }
  42085. const _axis = /*@__PURE__*/ new Vector3();
  42086. let _lineGeometry, _coneGeometry;
  42087. /**
  42088. * An 3D arrow object for visualizing directions.
  42089. *
  42090. * ```js
  42091. * const dir = new THREE.Vector3( 1, 2, 0 );
  42092. *
  42093. * //normalize the direction vector (convert to vector of length 1)
  42094. * dir.normalize();
  42095. *
  42096. * const origin = new THREE.Vector3( 0, 0, 0 );
  42097. * const length = 1;
  42098. * const hex = 0xffff00;
  42099. *
  42100. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42101. * scene.add( arrowHelper );
  42102. * ```
  42103. *
  42104. * @augments Object3D
  42105. */
  42106. class ArrowHelper extends Object3D {
  42107. /**
  42108. * Constructs a new arrow helper.
  42109. *
  42110. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42111. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42112. * @param {number} [length=1] - Length of the arrow in world units.
  42113. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42114. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42115. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42116. */
  42117. 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 ) {
  42118. super();
  42119. this.type = 'ArrowHelper';
  42120. if ( _lineGeometry === undefined ) {
  42121. _lineGeometry = new BufferGeometry();
  42122. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42123. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42124. _coneGeometry.translate( 0, -0.5, 0 );
  42125. }
  42126. this.position.copy( origin );
  42127. /**
  42128. * The line part of the arrow helper.
  42129. *
  42130. * @type {Line}
  42131. */
  42132. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42133. this.line.matrixAutoUpdate = false;
  42134. this.add( this.line );
  42135. /**
  42136. * The cone part of the arrow helper.
  42137. *
  42138. * @type {Mesh}
  42139. */
  42140. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42141. this.cone.matrixAutoUpdate = false;
  42142. this.add( this.cone );
  42143. this.setDirection( dir );
  42144. this.setLength( length, headLength, headWidth );
  42145. }
  42146. /**
  42147. * Sets the direction of the helper.
  42148. *
  42149. * @param {Vector3} dir - The normalized direction vector.
  42150. */
  42151. setDirection( dir ) {
  42152. // dir is assumed to be normalized
  42153. if ( dir.y > 0.99999 ) {
  42154. this.quaternion.set( 0, 0, 0, 1 );
  42155. } else if ( dir.y < -0.99999 ) {
  42156. this.quaternion.set( 1, 0, 0, 0 );
  42157. } else {
  42158. _axis.set( dir.z, 0, - dir.x ).normalize();
  42159. const radians = Math.acos( dir.y );
  42160. this.quaternion.setFromAxisAngle( _axis, radians );
  42161. }
  42162. }
  42163. /**
  42164. * Sets the length of the helper.
  42165. *
  42166. * @param {number} length - Length of the arrow in world units.
  42167. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42168. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42169. */
  42170. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42171. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42172. this.line.updateMatrix();
  42173. this.cone.scale.set( headWidth, headLength, headWidth );
  42174. this.cone.position.y = length;
  42175. this.cone.updateMatrix();
  42176. }
  42177. /**
  42178. * Sets the color of the helper.
  42179. *
  42180. * @param {number|Color|string} color - The color to set.
  42181. */
  42182. setColor( color ) {
  42183. this.line.material.color.set( color );
  42184. this.cone.material.color.set( color );
  42185. }
  42186. copy( source ) {
  42187. super.copy( source, false );
  42188. this.line.copy( source.line );
  42189. this.cone.copy( source.cone );
  42190. return this;
  42191. }
  42192. /**
  42193. * Frees the GPU-related resources allocated by this instance. Call this
  42194. * method whenever this instance is no longer used in your app.
  42195. */
  42196. dispose() {
  42197. this.line.geometry.dispose();
  42198. this.line.material.dispose();
  42199. this.cone.geometry.dispose();
  42200. this.cone.material.dispose();
  42201. }
  42202. }
  42203. /**
  42204. * An axis object to visualize the 3 axes in a simple way.
  42205. * The X axis is red. The Y axis is green. The Z axis is blue.
  42206. *
  42207. * ```js
  42208. * const axesHelper = new THREE.AxesHelper( 5 );
  42209. * scene.add( axesHelper );
  42210. * ```
  42211. *
  42212. * @augments LineSegments
  42213. */
  42214. class AxesHelper extends LineSegments {
  42215. /**
  42216. * Constructs a new axes helper.
  42217. *
  42218. * @param {number} [size=1] - Size of the lines representing the axes.
  42219. */
  42220. constructor( size = 1 ) {
  42221. const vertices = [
  42222. 0, 0, 0, size, 0, 0,
  42223. 0, 0, 0, 0, size, 0,
  42224. 0, 0, 0, 0, 0, size
  42225. ];
  42226. const colors = [
  42227. 1, 0, 0, 1, 0.6, 0,
  42228. 0, 1, 0, 0.6, 1, 0,
  42229. 0, 0, 1, 0, 0.6, 1
  42230. ];
  42231. const geometry = new BufferGeometry();
  42232. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42233. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42234. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42235. super( geometry, material );
  42236. this.type = 'AxesHelper';
  42237. }
  42238. /**
  42239. * Defines the colors of the axes helper.
  42240. *
  42241. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42242. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42243. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42244. * @return {AxesHelper} A reference to this axes helper.
  42245. */
  42246. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42247. const color = new Color();
  42248. const array = this.geometry.attributes.color.array;
  42249. color.set( xAxisColor );
  42250. color.toArray( array, 0 );
  42251. color.toArray( array, 3 );
  42252. color.set( yAxisColor );
  42253. color.toArray( array, 6 );
  42254. color.toArray( array, 9 );
  42255. color.set( zAxisColor );
  42256. color.toArray( array, 12 );
  42257. color.toArray( array, 15 );
  42258. this.geometry.attributes.color.needsUpdate = true;
  42259. return this;
  42260. }
  42261. /**
  42262. * Frees the GPU-related resources allocated by this instance. Call this
  42263. * method whenever this instance is no longer used in your app.
  42264. */
  42265. dispose() {
  42266. this.geometry.dispose();
  42267. this.material.dispose();
  42268. }
  42269. }
  42270. /**
  42271. * This class is used to convert a series of paths to an array of
  42272. * shapes. It is specifically used in context of fonts and SVG.
  42273. */
  42274. class ShapePath {
  42275. /**
  42276. * Constructs a new shape path.
  42277. */
  42278. constructor() {
  42279. this.type = 'ShapePath';
  42280. /**
  42281. * The color of the shape.
  42282. *
  42283. * @type {Color}
  42284. */
  42285. this.color = new Color();
  42286. /**
  42287. * The paths that have been generated for this shape.
  42288. *
  42289. * @type {Array<Path>}
  42290. * @default null
  42291. */
  42292. this.subPaths = [];
  42293. /**
  42294. * The current path that is being generated.
  42295. *
  42296. * @type {?Path}
  42297. * @default null
  42298. */
  42299. this.currentPath = null;
  42300. }
  42301. /**
  42302. * Creates a new path and moves it current point to the given one.
  42303. *
  42304. * @param {number} x - The x coordinate.
  42305. * @param {number} y - The y coordinate.
  42306. * @return {ShapePath} A reference to this shape path.
  42307. */
  42308. moveTo( x, y ) {
  42309. this.currentPath = new Path();
  42310. this.subPaths.push( this.currentPath );
  42311. this.currentPath.moveTo( x, y );
  42312. return this;
  42313. }
  42314. /**
  42315. * Adds an instance of {@link LineCurve} to the path by connecting
  42316. * the current point with the given one.
  42317. *
  42318. * @param {number} x - The x coordinate of the end point.
  42319. * @param {number} y - The y coordinate of the end point.
  42320. * @return {ShapePath} A reference to this shape path.
  42321. */
  42322. lineTo( x, y ) {
  42323. this.currentPath.lineTo( x, y );
  42324. return this;
  42325. }
  42326. /**
  42327. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42328. * the current point with the given one.
  42329. *
  42330. * @param {number} aCPx - The x coordinate of the control point.
  42331. * @param {number} aCPy - The y coordinate of the control point.
  42332. * @param {number} aX - The x coordinate of the end point.
  42333. * @param {number} aY - The y coordinate of the end point.
  42334. * @return {ShapePath} A reference to this shape path.
  42335. */
  42336. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42337. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42338. return this;
  42339. }
  42340. /**
  42341. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42342. * the current point with the given one.
  42343. *
  42344. * @param {number} aCP1x - The x coordinate of the first control point.
  42345. * @param {number} aCP1y - The y coordinate of the first control point.
  42346. * @param {number} aCP2x - The x coordinate of the second control point.
  42347. * @param {number} aCP2y - The y coordinate of the second control point.
  42348. * @param {number} aX - The x coordinate of the end point.
  42349. * @param {number} aY - The y coordinate of the end point.
  42350. * @return {ShapePath} A reference to this shape path.
  42351. */
  42352. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42353. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42354. return this;
  42355. }
  42356. /**
  42357. * Adds an instance of {@link SplineCurve} to the path by connecting
  42358. * the current point with the given list of points.
  42359. *
  42360. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42361. * @return {ShapePath} A reference to this shape path.
  42362. */
  42363. splineThru( pts ) {
  42364. this.currentPath.splineThru( pts );
  42365. return this;
  42366. }
  42367. /**
  42368. * Converts the paths into an array of shapes.
  42369. *
  42370. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42371. * If this flag is set to `true`, then those are flipped.
  42372. * @return {Array<Shape>} An array of shapes.
  42373. */
  42374. toShapes( isCCW ) {
  42375. function toShapesNoHoles( inSubpaths ) {
  42376. const shapes = [];
  42377. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42378. const tmpPath = inSubpaths[ i ];
  42379. const tmpShape = new Shape();
  42380. tmpShape.curves = tmpPath.curves;
  42381. shapes.push( tmpShape );
  42382. }
  42383. return shapes;
  42384. }
  42385. function isPointInsidePolygon( inPt, inPolygon ) {
  42386. const polyLen = inPolygon.length;
  42387. // inPt on polygon contour => immediate success or
  42388. // toggling of inside/outside at every single! intersection point of an edge
  42389. // with the horizontal line through inPt, left of inPt
  42390. // not counting lowerY endpoints of edges and whole edges on that line
  42391. let inside = false;
  42392. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42393. let edgeLowPt = inPolygon[ p ];
  42394. let edgeHighPt = inPolygon[ q ];
  42395. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42396. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42397. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42398. // not parallel
  42399. if ( edgeDy < 0 ) {
  42400. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42401. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42402. }
  42403. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42404. if ( inPt.y === edgeLowPt.y ) {
  42405. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42406. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42407. } else {
  42408. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42409. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42410. if ( perpEdge < 0 ) continue;
  42411. inside = ! inside; // true intersection left of inPt
  42412. }
  42413. } else {
  42414. // parallel or collinear
  42415. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42416. // edge lies on the same horizontal line as inPt
  42417. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42418. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42419. // continue;
  42420. }
  42421. }
  42422. return inside;
  42423. }
  42424. const isClockWise = ShapeUtils.isClockWise;
  42425. const subPaths = this.subPaths;
  42426. if ( subPaths.length === 0 ) return [];
  42427. let solid, tmpPath, tmpShape;
  42428. const shapes = [];
  42429. if ( subPaths.length === 1 ) {
  42430. tmpPath = subPaths[ 0 ];
  42431. tmpShape = new Shape();
  42432. tmpShape.curves = tmpPath.curves;
  42433. shapes.push( tmpShape );
  42434. return shapes;
  42435. }
  42436. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42437. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42438. // log("Holes first", holesFirst);
  42439. const betterShapeHoles = [];
  42440. const newShapes = [];
  42441. let newShapeHoles = [];
  42442. let mainIdx = 0;
  42443. let tmpPoints;
  42444. newShapes[ mainIdx ] = undefined;
  42445. newShapeHoles[ mainIdx ] = [];
  42446. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42447. tmpPath = subPaths[ i ];
  42448. tmpPoints = tmpPath.getPoints();
  42449. solid = isClockWise( tmpPoints );
  42450. solid = isCCW ? ! solid : solid;
  42451. if ( solid ) {
  42452. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42453. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42454. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42455. if ( holesFirst ) mainIdx ++;
  42456. newShapeHoles[ mainIdx ] = [];
  42457. //log('cw', i);
  42458. } else {
  42459. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42460. //log('ccw', i);
  42461. }
  42462. }
  42463. // only Holes? -> probably all Shapes with wrong orientation
  42464. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42465. if ( newShapes.length > 1 ) {
  42466. let ambiguous = false;
  42467. let toChange = 0;
  42468. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42469. betterShapeHoles[ sIdx ] = [];
  42470. }
  42471. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42472. const sho = newShapeHoles[ sIdx ];
  42473. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42474. const ho = sho[ hIdx ];
  42475. let hole_unassigned = true;
  42476. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42477. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42478. if ( sIdx !== s2Idx ) toChange ++;
  42479. if ( hole_unassigned ) {
  42480. hole_unassigned = false;
  42481. betterShapeHoles[ s2Idx ].push( ho );
  42482. } else {
  42483. ambiguous = true;
  42484. }
  42485. }
  42486. }
  42487. if ( hole_unassigned ) {
  42488. betterShapeHoles[ sIdx ].push( ho );
  42489. }
  42490. }
  42491. }
  42492. if ( toChange > 0 && ambiguous === false ) {
  42493. newShapeHoles = betterShapeHoles;
  42494. }
  42495. }
  42496. let tmpHoles;
  42497. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42498. tmpShape = newShapes[ i ].s;
  42499. shapes.push( tmpShape );
  42500. tmpHoles = newShapeHoles[ i ];
  42501. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42502. tmpShape.holes.push( tmpHoles[ j ].h );
  42503. }
  42504. }
  42505. //log("shape", shapes);
  42506. return shapes;
  42507. }
  42508. }
  42509. /**
  42510. * Abstract base class for controls.
  42511. *
  42512. * @abstract
  42513. * @augments EventDispatcher
  42514. */
  42515. class Controls extends EventDispatcher {
  42516. /**
  42517. * Constructs a new controls instance.
  42518. *
  42519. * @param {Object3D} object - The object that is managed by the controls.
  42520. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42521. */
  42522. constructor( object, domElement = null ) {
  42523. super();
  42524. /**
  42525. * The object that is managed by the controls.
  42526. *
  42527. * @type {Object3D}
  42528. */
  42529. this.object = object;
  42530. /**
  42531. * The HTML element used for event listeners.
  42532. *
  42533. * @type {?HTMLElement}
  42534. * @default null
  42535. */
  42536. this.domElement = domElement;
  42537. /**
  42538. * Whether the controls responds to user input or not.
  42539. *
  42540. * @type {boolean}
  42541. * @default true
  42542. */
  42543. this.enabled = true;
  42544. /**
  42545. * The internal state of the controls.
  42546. *
  42547. * @type {number}
  42548. * @default -1
  42549. */
  42550. this.state = -1;
  42551. /**
  42552. * This object defines the keyboard input of the controls.
  42553. *
  42554. * @type {Object}
  42555. */
  42556. this.keys = {};
  42557. /**
  42558. * This object defines what type of actions are assigned to the available mouse buttons.
  42559. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42560. *
  42561. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42562. */
  42563. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42564. /**
  42565. * This object defines what type of actions are assigned to what kind of touch interaction.
  42566. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42567. *
  42568. * @type {{ONE: ?number, TWO: ?number}}
  42569. */
  42570. this.touches = { ONE: null, TWO: null };
  42571. }
  42572. /**
  42573. * Connects the controls to the DOM. This method has so called "side effects" since
  42574. * it adds the module's event listeners to the DOM.
  42575. *
  42576. * @param {HTMLElement} element - The DOM element to connect to.
  42577. */
  42578. connect( element ) {
  42579. if ( element === undefined ) {
  42580. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42581. return;
  42582. }
  42583. if ( this.domElement !== null ) this.disconnect();
  42584. this.domElement = element;
  42585. }
  42586. /**
  42587. * Disconnects the controls from the DOM.
  42588. */
  42589. disconnect() {}
  42590. /**
  42591. * Call this method if you no longer want use to the controls. It frees all internal
  42592. * resources and removes all event listeners.
  42593. */
  42594. dispose() {}
  42595. /**
  42596. * Controls should implement this method if they have to update their internal state
  42597. * per simulation step.
  42598. *
  42599. * @param {number} [delta] - The time delta in seconds.
  42600. */
  42601. update( /* delta */ ) {}
  42602. }
  42603. /**
  42604. * Scales the texture as large as possible within its surface without cropping
  42605. * or stretching the texture. The method preserves the original aspect ratio of
  42606. * the texture. Akin to CSS `object-fit: contain`
  42607. *
  42608. * @param {Texture} texture - The texture.
  42609. * @param {number} aspect - The texture's aspect ratio.
  42610. * @return {Texture} The updated texture.
  42611. */
  42612. function contain( texture, aspect ) {
  42613. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42614. if ( imageAspect > aspect ) {
  42615. texture.repeat.x = 1;
  42616. texture.repeat.y = imageAspect / aspect;
  42617. texture.offset.x = 0;
  42618. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42619. } else {
  42620. texture.repeat.x = aspect / imageAspect;
  42621. texture.repeat.y = 1;
  42622. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42623. texture.offset.y = 0;
  42624. }
  42625. return texture;
  42626. }
  42627. /**
  42628. * Scales the texture to the smallest possible size to fill the surface, leaving
  42629. * no empty space. The method preserves the original aspect ratio of the texture.
  42630. * Akin to CSS `object-fit: cover`.
  42631. *
  42632. * @param {Texture} texture - The texture.
  42633. * @param {number} aspect - The texture's aspect ratio.
  42634. * @return {Texture} The updated texture.
  42635. */
  42636. function cover( texture, aspect ) {
  42637. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42638. if ( imageAspect > aspect ) {
  42639. texture.repeat.x = aspect / imageAspect;
  42640. texture.repeat.y = 1;
  42641. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42642. texture.offset.y = 0;
  42643. } else {
  42644. texture.repeat.x = 1;
  42645. texture.repeat.y = imageAspect / aspect;
  42646. texture.offset.x = 0;
  42647. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42648. }
  42649. return texture;
  42650. }
  42651. /**
  42652. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42653. *
  42654. * @param {Texture} texture - The texture.
  42655. * @return {Texture} The updated texture.
  42656. */
  42657. function fill( texture ) {
  42658. texture.repeat.x = 1;
  42659. texture.repeat.y = 1;
  42660. texture.offset.x = 0;
  42661. texture.offset.y = 0;
  42662. return texture;
  42663. }
  42664. /**
  42665. * Determines how many bytes must be used to represent the texture.
  42666. *
  42667. * @param {number} width - The width of the texture.
  42668. * @param {number} height - The height of the texture.
  42669. * @param {number} format - The texture's format.
  42670. * @param {number} type - The texture's type.
  42671. * @return {number} The byte length.
  42672. */
  42673. function getByteLength( width, height, format, type ) {
  42674. const typeByteLength = getTextureTypeByteLength( type );
  42675. switch ( format ) {
  42676. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42677. case AlphaFormat:
  42678. return width * height;
  42679. case RedFormat:
  42680. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42681. case RedIntegerFormat:
  42682. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42683. case RGFormat:
  42684. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42685. case RGIntegerFormat:
  42686. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42687. case RGBFormat:
  42688. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42689. case RGBAFormat:
  42690. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42691. case RGBAIntegerFormat:
  42692. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42693. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42694. case RGB_S3TC_DXT1_Format:
  42695. case RGBA_S3TC_DXT1_Format:
  42696. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42697. case RGBA_S3TC_DXT3_Format:
  42698. case RGBA_S3TC_DXT5_Format:
  42699. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42700. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42701. case RGB_PVRTC_2BPPV1_Format:
  42702. case RGBA_PVRTC_2BPPV1_Format:
  42703. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42704. case RGB_PVRTC_4BPPV1_Format:
  42705. case RGBA_PVRTC_4BPPV1_Format:
  42706. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42707. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42708. case RGB_ETC1_Format:
  42709. case RGB_ETC2_Format:
  42710. case R11_EAC_Format:
  42711. case SIGNED_R11_EAC_Format:
  42712. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42713. case RGBA_ETC2_EAC_Format:
  42714. case RG11_EAC_Format:
  42715. case SIGNED_RG11_EAC_Format:
  42716. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42717. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42718. case RGBA_ASTC_4x4_Format:
  42719. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42720. case RGBA_ASTC_5x4_Format:
  42721. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42722. case RGBA_ASTC_5x5_Format:
  42723. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42724. case RGBA_ASTC_6x5_Format:
  42725. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42726. case RGBA_ASTC_6x6_Format:
  42727. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42728. case RGBA_ASTC_8x5_Format:
  42729. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42730. case RGBA_ASTC_8x6_Format:
  42731. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42732. case RGBA_ASTC_8x8_Format:
  42733. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42734. case RGBA_ASTC_10x5_Format:
  42735. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42736. case RGBA_ASTC_10x6_Format:
  42737. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42738. case RGBA_ASTC_10x8_Format:
  42739. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42740. case RGBA_ASTC_10x10_Format:
  42741. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42742. case RGBA_ASTC_12x10_Format:
  42743. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42744. case RGBA_ASTC_12x12_Format:
  42745. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42746. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42747. case RGBA_BPTC_Format:
  42748. case RGB_BPTC_SIGNED_Format:
  42749. case RGB_BPTC_UNSIGNED_Format:
  42750. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42751. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42752. case RED_RGTC1_Format:
  42753. case SIGNED_RED_RGTC1_Format:
  42754. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42755. case RED_GREEN_RGTC2_Format:
  42756. case SIGNED_RED_GREEN_RGTC2_Format:
  42757. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42758. }
  42759. throw new Error(
  42760. `Unable to determine texture byte length for ${format} format.`,
  42761. );
  42762. }
  42763. function getTextureTypeByteLength( type ) {
  42764. switch ( type ) {
  42765. case UnsignedByteType:
  42766. case ByteType:
  42767. return { byteLength: 1, components: 1 };
  42768. case UnsignedShortType:
  42769. case ShortType:
  42770. case HalfFloatType:
  42771. return { byteLength: 2, components: 1 };
  42772. case UnsignedShort4444Type:
  42773. case UnsignedShort5551Type:
  42774. return { byteLength: 2, components: 4 };
  42775. case UnsignedIntType:
  42776. case IntType:
  42777. case FloatType:
  42778. return { byteLength: 4, components: 1 };
  42779. case UnsignedInt5999Type:
  42780. case UnsignedInt101111Type:
  42781. return { byteLength: 4, components: 3 };
  42782. }
  42783. throw new Error( `Unknown texture type ${type}.` );
  42784. }
  42785. /**
  42786. * A class containing utility functions for textures.
  42787. *
  42788. * @hideconstructor
  42789. */
  42790. class TextureUtils {
  42791. /**
  42792. * Scales the texture as large as possible within its surface without cropping
  42793. * or stretching the texture. The method preserves the original aspect ratio of
  42794. * the texture. Akin to CSS `object-fit: contain`
  42795. *
  42796. * @param {Texture} texture - The texture.
  42797. * @param {number} aspect - The texture's aspect ratio.
  42798. * @return {Texture} The updated texture.
  42799. */
  42800. static contain( texture, aspect ) {
  42801. return contain( texture, aspect );
  42802. }
  42803. /**
  42804. * Scales the texture to the smallest possible size to fill the surface, leaving
  42805. * no empty space. The method preserves the original aspect ratio of the texture.
  42806. * Akin to CSS `object-fit: cover`.
  42807. *
  42808. * @param {Texture} texture - The texture.
  42809. * @param {number} aspect - The texture's aspect ratio.
  42810. * @return {Texture} The updated texture.
  42811. */
  42812. static cover( texture, aspect ) {
  42813. return cover( texture, aspect );
  42814. }
  42815. /**
  42816. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42817. *
  42818. * @param {Texture} texture - The texture.
  42819. * @return {Texture} The updated texture.
  42820. */
  42821. static fill( texture ) {
  42822. return fill( texture );
  42823. }
  42824. /**
  42825. * Determines how many bytes must be used to represent the texture.
  42826. *
  42827. * @param {number} width - The width of the texture.
  42828. * @param {number} height - The height of the texture.
  42829. * @param {number} format - The texture's format.
  42830. * @param {number} type - The texture's type.
  42831. * @return {number} The byte length.
  42832. */
  42833. static getByteLength( width, height, format, type ) {
  42834. return getByteLength( width, height, format, type );
  42835. }
  42836. }
  42837. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42838. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42839. revision: REVISION,
  42840. } } ) );
  42841. }
  42842. if ( typeof window !== 'undefined' ) {
  42843. if ( window.__THREE__ ) {
  42844. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42845. } else {
  42846. window.__THREE__ = REVISION;
  42847. }
  42848. }
  42849. function WebGLAnimation() {
  42850. let context = null;
  42851. let isAnimating = false;
  42852. let animationLoop = null;
  42853. let requestId = null;
  42854. function onAnimationFrame( time, frame ) {
  42855. animationLoop( time, frame );
  42856. requestId = context.requestAnimationFrame( onAnimationFrame );
  42857. }
  42858. return {
  42859. start: function () {
  42860. if ( isAnimating === true ) return;
  42861. if ( animationLoop === null ) return;
  42862. requestId = context.requestAnimationFrame( onAnimationFrame );
  42863. isAnimating = true;
  42864. },
  42865. stop: function () {
  42866. context.cancelAnimationFrame( requestId );
  42867. isAnimating = false;
  42868. },
  42869. setAnimationLoop: function ( callback ) {
  42870. animationLoop = callback;
  42871. },
  42872. setContext: function ( value ) {
  42873. context = value;
  42874. }
  42875. };
  42876. }
  42877. function WebGLAttributes( gl ) {
  42878. const buffers = new WeakMap();
  42879. function createBuffer( attribute, bufferType ) {
  42880. const array = attribute.array;
  42881. const usage = attribute.usage;
  42882. const size = array.byteLength;
  42883. const buffer = gl.createBuffer();
  42884. gl.bindBuffer( bufferType, buffer );
  42885. gl.bufferData( bufferType, array, usage );
  42886. attribute.onUploadCallback();
  42887. let type;
  42888. if ( array instanceof Float32Array ) {
  42889. type = gl.FLOAT;
  42890. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42891. type = gl.HALF_FLOAT;
  42892. } else if ( array instanceof Uint16Array ) {
  42893. if ( attribute.isFloat16BufferAttribute ) {
  42894. type = gl.HALF_FLOAT;
  42895. } else {
  42896. type = gl.UNSIGNED_SHORT;
  42897. }
  42898. } else if ( array instanceof Int16Array ) {
  42899. type = gl.SHORT;
  42900. } else if ( array instanceof Uint32Array ) {
  42901. type = gl.UNSIGNED_INT;
  42902. } else if ( array instanceof Int32Array ) {
  42903. type = gl.INT;
  42904. } else if ( array instanceof Int8Array ) {
  42905. type = gl.BYTE;
  42906. } else if ( array instanceof Uint8Array ) {
  42907. type = gl.UNSIGNED_BYTE;
  42908. } else if ( array instanceof Uint8ClampedArray ) {
  42909. type = gl.UNSIGNED_BYTE;
  42910. } else {
  42911. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42912. }
  42913. return {
  42914. buffer: buffer,
  42915. type: type,
  42916. bytesPerElement: array.BYTES_PER_ELEMENT,
  42917. version: attribute.version,
  42918. size: size
  42919. };
  42920. }
  42921. function updateBuffer( buffer, attribute, bufferType ) {
  42922. const array = attribute.array;
  42923. const updateRanges = attribute.updateRanges;
  42924. gl.bindBuffer( bufferType, buffer );
  42925. if ( updateRanges.length === 0 ) {
  42926. // Not using update ranges
  42927. gl.bufferSubData( bufferType, 0, array );
  42928. } else {
  42929. // Before applying update ranges, we merge any adjacent / overlapping
  42930. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42931. // to performance improvements for applications which make heavy use of
  42932. // update ranges. Likely due to GPU command overhead.
  42933. //
  42934. // Note that to reduce garbage collection between frames, we merge the
  42935. // update ranges in-place. This is safe because this method will clear the
  42936. // update ranges once updated.
  42937. updateRanges.sort( ( a, b ) => a.start - b.start );
  42938. // To merge the update ranges in-place, we work from left to right in the
  42939. // existing updateRanges array, merging ranges. This may result in a final
  42940. // array which is smaller than the original. This index tracks the last
  42941. // index representing a merged range, any data after this index can be
  42942. // trimmed once the merge algorithm is completed.
  42943. let mergeIndex = 0;
  42944. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42945. const previousRange = updateRanges[ mergeIndex ];
  42946. const range = updateRanges[ i ];
  42947. // We add one here to merge adjacent ranges. This is safe because ranges
  42948. // operate over positive integers.
  42949. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42950. previousRange.count = Math.max(
  42951. previousRange.count,
  42952. range.start + range.count - previousRange.start
  42953. );
  42954. } else {
  42955. ++ mergeIndex;
  42956. updateRanges[ mergeIndex ] = range;
  42957. }
  42958. }
  42959. // Trim the array to only contain the merged ranges.
  42960. updateRanges.length = mergeIndex + 1;
  42961. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42962. const range = updateRanges[ i ];
  42963. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42964. array, range.start, range.count );
  42965. }
  42966. attribute.clearUpdateRanges();
  42967. }
  42968. attribute.onUploadCallback();
  42969. }
  42970. //
  42971. function get( attribute ) {
  42972. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42973. return buffers.get( attribute );
  42974. }
  42975. function remove( attribute ) {
  42976. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42977. const data = buffers.get( attribute );
  42978. if ( data ) {
  42979. gl.deleteBuffer( data.buffer );
  42980. buffers.delete( attribute );
  42981. }
  42982. }
  42983. function update( attribute, bufferType ) {
  42984. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42985. if ( attribute.isGLBufferAttribute ) {
  42986. const cached = buffers.get( attribute );
  42987. if ( ! cached || cached.version < attribute.version ) {
  42988. buffers.set( attribute, {
  42989. buffer: attribute.buffer,
  42990. type: attribute.type,
  42991. bytesPerElement: attribute.elementSize,
  42992. version: attribute.version
  42993. } );
  42994. }
  42995. return;
  42996. }
  42997. const data = buffers.get( attribute );
  42998. if ( data === undefined ) {
  42999. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  43000. } else if ( data.version < attribute.version ) {
  43001. if ( data.size !== attribute.array.byteLength ) {
  43002. 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.' );
  43003. }
  43004. updateBuffer( data.buffer, attribute, bufferType );
  43005. data.version = attribute.version;
  43006. }
  43007. }
  43008. return {
  43009. get: get,
  43010. remove: remove,
  43011. update: update
  43012. };
  43013. }
  43014. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  43015. 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";
  43016. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  43017. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  43018. 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";
  43019. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  43020. 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";
  43021. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  43022. 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\tvec3 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 ).rgb;\n\t}\n#endif";
  43023. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  43024. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  43025. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  43026. 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";
  43027. 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";
  43028. 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";
  43029. 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";
  43030. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  43031. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  43032. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  43033. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  43034. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  43035. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  43036. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  43037. 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";
  43038. 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";
  43039. 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";
  43040. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  43041. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  43042. 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";
  43043. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  43044. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  43045. 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}";
  43046. 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#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  43047. 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";
  43048. 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";
  43049. 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";
  43050. 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";
  43051. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  43052. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  43053. 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";
  43054. 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";
  43055. 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}";
  43056. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  43057. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  43058. 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";
  43059. 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";
  43060. 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";
  43061. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  43062. 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";
  43063. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  43064. 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";
  43065. 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";
  43066. 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 + ( vec3( 1.0 ) - 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}\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}";
  43067. 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";
  43068. 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( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\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";
  43069. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\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";
  43070. 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";
  43071. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43072. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43073. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  43074. 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";
  43075. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  43076. 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";
  43077. 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";
  43078. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  43079. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  43080. 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";
  43081. 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";
  43082. 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";
  43083. 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";
  43084. 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";
  43085. 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;";
  43086. 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";
  43087. 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";
  43088. 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";
  43089. 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";
  43090. 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";
  43091. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  43092. 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";
  43093. 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";
  43094. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43095. 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 );";
  43096. 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\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  43097. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43098. 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;";
  43099. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43100. 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";
  43101. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43102. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43103. 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 ) * 6.28318530718;\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\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 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\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\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\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\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\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 ) * 6.28318530718;\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\tshadow = step( depth, dp );\n\t\t\t#else\n\t\t\t\tshadow = step( dp, depth );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  43104. 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";
  43105. 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";
  43106. 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}";
  43107. 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";
  43108. 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";
  43109. 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";
  43110. 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";
  43111. 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";
  43112. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43113. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43114. 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; }";
  43115. 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";
  43116. 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";
  43117. 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";
  43118. 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";
  43119. 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";
  43120. 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";
  43121. 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}";
  43122. 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}";
  43123. 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}";
  43124. 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}";
  43125. 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}";
  43126. 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}";
  43127. 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}";
  43128. 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}";
  43129. 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}";
  43130. 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}";
  43131. 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}";
  43132. 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}";
  43133. 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}";
  43134. 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}";
  43135. 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}";
  43136. 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}";
  43137. 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}";
  43138. 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 <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\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}";
  43139. 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}";
  43140. 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}";
  43141. 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}";
  43142. 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}";
  43143. 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}";
  43144. 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 <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\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}";
  43145. 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}";
  43146. 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}";
  43147. 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}";
  43148. 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}";
  43149. 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}";
  43150. 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}";
  43151. 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}";
  43152. 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}";
  43153. 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}";
  43154. 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}";
  43155. const ShaderChunk = {
  43156. alphahash_fragment: alphahash_fragment,
  43157. alphahash_pars_fragment: alphahash_pars_fragment,
  43158. alphamap_fragment: alphamap_fragment,
  43159. alphamap_pars_fragment: alphamap_pars_fragment,
  43160. alphatest_fragment: alphatest_fragment,
  43161. alphatest_pars_fragment: alphatest_pars_fragment,
  43162. aomap_fragment: aomap_fragment,
  43163. aomap_pars_fragment: aomap_pars_fragment,
  43164. batching_pars_vertex: batching_pars_vertex,
  43165. batching_vertex: batching_vertex,
  43166. begin_vertex: begin_vertex,
  43167. beginnormal_vertex: beginnormal_vertex,
  43168. bsdfs: bsdfs,
  43169. iridescence_fragment: iridescence_fragment,
  43170. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43171. clipping_planes_fragment: clipping_planes_fragment,
  43172. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43173. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43174. clipping_planes_vertex: clipping_planes_vertex,
  43175. color_fragment: color_fragment,
  43176. color_pars_fragment: color_pars_fragment,
  43177. color_pars_vertex: color_pars_vertex,
  43178. color_vertex: color_vertex,
  43179. common: common,
  43180. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43181. defaultnormal_vertex: defaultnormal_vertex,
  43182. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43183. displacementmap_vertex: displacementmap_vertex,
  43184. emissivemap_fragment: emissivemap_fragment,
  43185. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43186. colorspace_fragment: colorspace_fragment,
  43187. colorspace_pars_fragment: colorspace_pars_fragment,
  43188. envmap_fragment: envmap_fragment,
  43189. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43190. envmap_pars_fragment: envmap_pars_fragment,
  43191. envmap_pars_vertex: envmap_pars_vertex,
  43192. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43193. envmap_vertex: envmap_vertex,
  43194. fog_vertex: fog_vertex,
  43195. fog_pars_vertex: fog_pars_vertex,
  43196. fog_fragment: fog_fragment,
  43197. fog_pars_fragment: fog_pars_fragment,
  43198. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43199. lightmap_pars_fragment: lightmap_pars_fragment,
  43200. lights_lambert_fragment: lights_lambert_fragment,
  43201. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43202. lights_pars_begin: lights_pars_begin,
  43203. lights_toon_fragment: lights_toon_fragment,
  43204. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43205. lights_phong_fragment: lights_phong_fragment,
  43206. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43207. lights_physical_fragment: lights_physical_fragment,
  43208. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43209. lights_fragment_begin: lights_fragment_begin,
  43210. lights_fragment_maps: lights_fragment_maps,
  43211. lights_fragment_end: lights_fragment_end,
  43212. logdepthbuf_fragment: logdepthbuf_fragment,
  43213. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43214. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43215. logdepthbuf_vertex: logdepthbuf_vertex,
  43216. map_fragment: map_fragment,
  43217. map_pars_fragment: map_pars_fragment,
  43218. map_particle_fragment: map_particle_fragment,
  43219. map_particle_pars_fragment: map_particle_pars_fragment,
  43220. metalnessmap_fragment: metalnessmap_fragment,
  43221. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43222. morphinstance_vertex: morphinstance_vertex,
  43223. morphcolor_vertex: morphcolor_vertex,
  43224. morphnormal_vertex: morphnormal_vertex,
  43225. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43226. morphtarget_vertex: morphtarget_vertex,
  43227. normal_fragment_begin: normal_fragment_begin,
  43228. normal_fragment_maps: normal_fragment_maps,
  43229. normal_pars_fragment: normal_pars_fragment,
  43230. normal_pars_vertex: normal_pars_vertex,
  43231. normal_vertex: normal_vertex,
  43232. normalmap_pars_fragment: normalmap_pars_fragment,
  43233. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43234. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43235. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43236. iridescence_pars_fragment: iridescence_pars_fragment,
  43237. opaque_fragment: opaque_fragment,
  43238. packing: packing,
  43239. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43240. project_vertex: project_vertex,
  43241. dithering_fragment: dithering_fragment,
  43242. dithering_pars_fragment: dithering_pars_fragment,
  43243. roughnessmap_fragment: roughnessmap_fragment,
  43244. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43245. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43246. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43247. shadowmap_vertex: shadowmap_vertex,
  43248. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43249. skinbase_vertex: skinbase_vertex,
  43250. skinning_pars_vertex: skinning_pars_vertex,
  43251. skinning_vertex: skinning_vertex,
  43252. skinnormal_vertex: skinnormal_vertex,
  43253. specularmap_fragment: specularmap_fragment,
  43254. specularmap_pars_fragment: specularmap_pars_fragment,
  43255. tonemapping_fragment: tonemapping_fragment,
  43256. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43257. transmission_fragment: transmission_fragment,
  43258. transmission_pars_fragment: transmission_pars_fragment,
  43259. uv_pars_fragment: uv_pars_fragment,
  43260. uv_pars_vertex: uv_pars_vertex,
  43261. uv_vertex: uv_vertex,
  43262. worldpos_vertex: worldpos_vertex,
  43263. background_vert: vertex$h,
  43264. background_frag: fragment$h,
  43265. backgroundCube_vert: vertex$g,
  43266. backgroundCube_frag: fragment$g,
  43267. cube_vert: vertex$f,
  43268. cube_frag: fragment$f,
  43269. depth_vert: vertex$e,
  43270. depth_frag: fragment$e,
  43271. distance_vert: vertex$d,
  43272. distance_frag: fragment$d,
  43273. equirect_vert: vertex$c,
  43274. equirect_frag: fragment$c,
  43275. linedashed_vert: vertex$b,
  43276. linedashed_frag: fragment$b,
  43277. meshbasic_vert: vertex$a,
  43278. meshbasic_frag: fragment$a,
  43279. meshlambert_vert: vertex$9,
  43280. meshlambert_frag: fragment$9,
  43281. meshmatcap_vert: vertex$8,
  43282. meshmatcap_frag: fragment$8,
  43283. meshnormal_vert: vertex$7,
  43284. meshnormal_frag: fragment$7,
  43285. meshphong_vert: vertex$6,
  43286. meshphong_frag: fragment$6,
  43287. meshphysical_vert: vertex$5,
  43288. meshphysical_frag: fragment$5,
  43289. meshtoon_vert: vertex$4,
  43290. meshtoon_frag: fragment$4,
  43291. points_vert: vertex$3,
  43292. points_frag: fragment$3,
  43293. shadow_vert: vertex$2,
  43294. shadow_frag: fragment$2,
  43295. sprite_vert: vertex$1,
  43296. sprite_frag: fragment$1
  43297. };
  43298. // Uniforms library for shared webgl shaders
  43299. const UniformsLib = {
  43300. common: {
  43301. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43302. opacity: { value: 1.0 },
  43303. map: { value: null },
  43304. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43305. alphaMap: { value: null },
  43306. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43307. alphaTest: { value: 0 }
  43308. },
  43309. specularmap: {
  43310. specularMap: { value: null },
  43311. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43312. },
  43313. envmap: {
  43314. envMap: { value: null },
  43315. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43316. flipEnvMap: { value: -1 },
  43317. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43318. ior: { value: 1.5 }, // physical
  43319. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43320. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43321. },
  43322. aomap: {
  43323. aoMap: { value: null },
  43324. aoMapIntensity: { value: 1 },
  43325. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43326. },
  43327. lightmap: {
  43328. lightMap: { value: null },
  43329. lightMapIntensity: { value: 1 },
  43330. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43331. },
  43332. bumpmap: {
  43333. bumpMap: { value: null },
  43334. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43335. bumpScale: { value: 1 }
  43336. },
  43337. normalmap: {
  43338. normalMap: { value: null },
  43339. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43340. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43341. },
  43342. displacementmap: {
  43343. displacementMap: { value: null },
  43344. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43345. displacementScale: { value: 1 },
  43346. displacementBias: { value: 0 }
  43347. },
  43348. emissivemap: {
  43349. emissiveMap: { value: null },
  43350. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43351. },
  43352. metalnessmap: {
  43353. metalnessMap: { value: null },
  43354. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43355. },
  43356. roughnessmap: {
  43357. roughnessMap: { value: null },
  43358. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43359. },
  43360. gradientmap: {
  43361. gradientMap: { value: null }
  43362. },
  43363. fog: {
  43364. fogDensity: { value: 0.00025 },
  43365. fogNear: { value: 1 },
  43366. fogFar: { value: 2000 },
  43367. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43368. },
  43369. lights: {
  43370. ambientLightColor: { value: [] },
  43371. lightProbe: { value: [] },
  43372. directionalLights: { value: [], properties: {
  43373. direction: {},
  43374. color: {}
  43375. } },
  43376. directionalLightShadows: { value: [], properties: {
  43377. shadowIntensity: 1,
  43378. shadowBias: {},
  43379. shadowNormalBias: {},
  43380. shadowRadius: {},
  43381. shadowMapSize: {}
  43382. } },
  43383. directionalShadowMatrix: { value: [] },
  43384. spotLights: { value: [], properties: {
  43385. color: {},
  43386. position: {},
  43387. direction: {},
  43388. distance: {},
  43389. coneCos: {},
  43390. penumbraCos: {},
  43391. decay: {}
  43392. } },
  43393. spotLightShadows: { value: [], properties: {
  43394. shadowIntensity: 1,
  43395. shadowBias: {},
  43396. shadowNormalBias: {},
  43397. shadowRadius: {},
  43398. shadowMapSize: {}
  43399. } },
  43400. spotLightMap: { value: [] },
  43401. spotLightMatrix: { value: [] },
  43402. pointLights: { value: [], properties: {
  43403. color: {},
  43404. position: {},
  43405. decay: {},
  43406. distance: {}
  43407. } },
  43408. pointLightShadows: { value: [], properties: {
  43409. shadowIntensity: 1,
  43410. shadowBias: {},
  43411. shadowNormalBias: {},
  43412. shadowRadius: {},
  43413. shadowMapSize: {},
  43414. shadowCameraNear: {},
  43415. shadowCameraFar: {}
  43416. } },
  43417. pointShadowMatrix: { value: [] },
  43418. hemisphereLights: { value: [], properties: {
  43419. direction: {},
  43420. skyColor: {},
  43421. groundColor: {}
  43422. } },
  43423. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43424. rectAreaLights: { value: [], properties: {
  43425. color: {},
  43426. position: {},
  43427. width: {},
  43428. height: {}
  43429. } },
  43430. ltc_1: { value: null },
  43431. ltc_2: { value: null }
  43432. },
  43433. points: {
  43434. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43435. opacity: { value: 1.0 },
  43436. size: { value: 1.0 },
  43437. scale: { value: 1.0 },
  43438. map: { value: null },
  43439. alphaMap: { value: null },
  43440. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43441. alphaTest: { value: 0 },
  43442. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43443. },
  43444. sprite: {
  43445. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43446. opacity: { value: 1.0 },
  43447. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43448. rotation: { value: 0.0 },
  43449. map: { value: null },
  43450. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43451. alphaMap: { value: null },
  43452. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43453. alphaTest: { value: 0 }
  43454. }
  43455. };
  43456. const ShaderLib = {
  43457. basic: {
  43458. uniforms: /*@__PURE__*/ mergeUniforms( [
  43459. UniformsLib.common,
  43460. UniformsLib.specularmap,
  43461. UniformsLib.envmap,
  43462. UniformsLib.aomap,
  43463. UniformsLib.lightmap,
  43464. UniformsLib.fog
  43465. ] ),
  43466. vertexShader: ShaderChunk.meshbasic_vert,
  43467. fragmentShader: ShaderChunk.meshbasic_frag
  43468. },
  43469. lambert: {
  43470. uniforms: /*@__PURE__*/ mergeUniforms( [
  43471. UniformsLib.common,
  43472. UniformsLib.specularmap,
  43473. UniformsLib.envmap,
  43474. UniformsLib.aomap,
  43475. UniformsLib.lightmap,
  43476. UniformsLib.emissivemap,
  43477. UniformsLib.bumpmap,
  43478. UniformsLib.normalmap,
  43479. UniformsLib.displacementmap,
  43480. UniformsLib.fog,
  43481. UniformsLib.lights,
  43482. {
  43483. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43484. }
  43485. ] ),
  43486. vertexShader: ShaderChunk.meshlambert_vert,
  43487. fragmentShader: ShaderChunk.meshlambert_frag
  43488. },
  43489. phong: {
  43490. uniforms: /*@__PURE__*/ mergeUniforms( [
  43491. UniformsLib.common,
  43492. UniformsLib.specularmap,
  43493. UniformsLib.envmap,
  43494. UniformsLib.aomap,
  43495. UniformsLib.lightmap,
  43496. UniformsLib.emissivemap,
  43497. UniformsLib.bumpmap,
  43498. UniformsLib.normalmap,
  43499. UniformsLib.displacementmap,
  43500. UniformsLib.fog,
  43501. UniformsLib.lights,
  43502. {
  43503. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43504. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43505. shininess: { value: 30 }
  43506. }
  43507. ] ),
  43508. vertexShader: ShaderChunk.meshphong_vert,
  43509. fragmentShader: ShaderChunk.meshphong_frag
  43510. },
  43511. standard: {
  43512. uniforms: /*@__PURE__*/ mergeUniforms( [
  43513. UniformsLib.common,
  43514. UniformsLib.envmap,
  43515. UniformsLib.aomap,
  43516. UniformsLib.lightmap,
  43517. UniformsLib.emissivemap,
  43518. UniformsLib.bumpmap,
  43519. UniformsLib.normalmap,
  43520. UniformsLib.displacementmap,
  43521. UniformsLib.roughnessmap,
  43522. UniformsLib.metalnessmap,
  43523. UniformsLib.fog,
  43524. UniformsLib.lights,
  43525. {
  43526. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43527. roughness: { value: 1.0 },
  43528. metalness: { value: 0.0 },
  43529. envMapIntensity: { value: 1 }
  43530. }
  43531. ] ),
  43532. vertexShader: ShaderChunk.meshphysical_vert,
  43533. fragmentShader: ShaderChunk.meshphysical_frag
  43534. },
  43535. toon: {
  43536. uniforms: /*@__PURE__*/ mergeUniforms( [
  43537. UniformsLib.common,
  43538. UniformsLib.aomap,
  43539. UniformsLib.lightmap,
  43540. UniformsLib.emissivemap,
  43541. UniformsLib.bumpmap,
  43542. UniformsLib.normalmap,
  43543. UniformsLib.displacementmap,
  43544. UniformsLib.gradientmap,
  43545. UniformsLib.fog,
  43546. UniformsLib.lights,
  43547. {
  43548. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43549. }
  43550. ] ),
  43551. vertexShader: ShaderChunk.meshtoon_vert,
  43552. fragmentShader: ShaderChunk.meshtoon_frag
  43553. },
  43554. matcap: {
  43555. uniforms: /*@__PURE__*/ mergeUniforms( [
  43556. UniformsLib.common,
  43557. UniformsLib.bumpmap,
  43558. UniformsLib.normalmap,
  43559. UniformsLib.displacementmap,
  43560. UniformsLib.fog,
  43561. {
  43562. matcap: { value: null }
  43563. }
  43564. ] ),
  43565. vertexShader: ShaderChunk.meshmatcap_vert,
  43566. fragmentShader: ShaderChunk.meshmatcap_frag
  43567. },
  43568. points: {
  43569. uniforms: /*@__PURE__*/ mergeUniforms( [
  43570. UniformsLib.points,
  43571. UniformsLib.fog
  43572. ] ),
  43573. vertexShader: ShaderChunk.points_vert,
  43574. fragmentShader: ShaderChunk.points_frag
  43575. },
  43576. dashed: {
  43577. uniforms: /*@__PURE__*/ mergeUniforms( [
  43578. UniformsLib.common,
  43579. UniformsLib.fog,
  43580. {
  43581. scale: { value: 1 },
  43582. dashSize: { value: 1 },
  43583. totalSize: { value: 2 }
  43584. }
  43585. ] ),
  43586. vertexShader: ShaderChunk.linedashed_vert,
  43587. fragmentShader: ShaderChunk.linedashed_frag
  43588. },
  43589. depth: {
  43590. uniforms: /*@__PURE__*/ mergeUniforms( [
  43591. UniformsLib.common,
  43592. UniformsLib.displacementmap
  43593. ] ),
  43594. vertexShader: ShaderChunk.depth_vert,
  43595. fragmentShader: ShaderChunk.depth_frag
  43596. },
  43597. normal: {
  43598. uniforms: /*@__PURE__*/ mergeUniforms( [
  43599. UniformsLib.common,
  43600. UniformsLib.bumpmap,
  43601. UniformsLib.normalmap,
  43602. UniformsLib.displacementmap,
  43603. {
  43604. opacity: { value: 1.0 }
  43605. }
  43606. ] ),
  43607. vertexShader: ShaderChunk.meshnormal_vert,
  43608. fragmentShader: ShaderChunk.meshnormal_frag
  43609. },
  43610. sprite: {
  43611. uniforms: /*@__PURE__*/ mergeUniforms( [
  43612. UniformsLib.sprite,
  43613. UniformsLib.fog
  43614. ] ),
  43615. vertexShader: ShaderChunk.sprite_vert,
  43616. fragmentShader: ShaderChunk.sprite_frag
  43617. },
  43618. background: {
  43619. uniforms: {
  43620. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43621. t2D: { value: null },
  43622. backgroundIntensity: { value: 1 }
  43623. },
  43624. vertexShader: ShaderChunk.background_vert,
  43625. fragmentShader: ShaderChunk.background_frag
  43626. },
  43627. backgroundCube: {
  43628. uniforms: {
  43629. envMap: { value: null },
  43630. flipEnvMap: { value: -1 },
  43631. backgroundBlurriness: { value: 0 },
  43632. backgroundIntensity: { value: 1 },
  43633. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43634. },
  43635. vertexShader: ShaderChunk.backgroundCube_vert,
  43636. fragmentShader: ShaderChunk.backgroundCube_frag
  43637. },
  43638. cube: {
  43639. uniforms: {
  43640. tCube: { value: null },
  43641. tFlip: { value: -1 },
  43642. opacity: { value: 1.0 }
  43643. },
  43644. vertexShader: ShaderChunk.cube_vert,
  43645. fragmentShader: ShaderChunk.cube_frag
  43646. },
  43647. equirect: {
  43648. uniforms: {
  43649. tEquirect: { value: null },
  43650. },
  43651. vertexShader: ShaderChunk.equirect_vert,
  43652. fragmentShader: ShaderChunk.equirect_frag
  43653. },
  43654. distance: {
  43655. uniforms: /*@__PURE__*/ mergeUniforms( [
  43656. UniformsLib.common,
  43657. UniformsLib.displacementmap,
  43658. {
  43659. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43660. nearDistance: { value: 1 },
  43661. farDistance: { value: 1000 }
  43662. }
  43663. ] ),
  43664. vertexShader: ShaderChunk.distance_vert,
  43665. fragmentShader: ShaderChunk.distance_frag
  43666. },
  43667. shadow: {
  43668. uniforms: /*@__PURE__*/ mergeUniforms( [
  43669. UniformsLib.lights,
  43670. UniformsLib.fog,
  43671. {
  43672. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43673. opacity: { value: 1.0 }
  43674. },
  43675. ] ),
  43676. vertexShader: ShaderChunk.shadow_vert,
  43677. fragmentShader: ShaderChunk.shadow_frag
  43678. }
  43679. };
  43680. ShaderLib.physical = {
  43681. uniforms: /*@__PURE__*/ mergeUniforms( [
  43682. ShaderLib.standard.uniforms,
  43683. {
  43684. clearcoat: { value: 0 },
  43685. clearcoatMap: { value: null },
  43686. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43687. clearcoatNormalMap: { value: null },
  43688. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43689. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43690. clearcoatRoughness: { value: 0 },
  43691. clearcoatRoughnessMap: { value: null },
  43692. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43693. dispersion: { value: 0 },
  43694. iridescence: { value: 0 },
  43695. iridescenceMap: { value: null },
  43696. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43697. iridescenceIOR: { value: 1.3 },
  43698. iridescenceThicknessMinimum: { value: 100 },
  43699. iridescenceThicknessMaximum: { value: 400 },
  43700. iridescenceThicknessMap: { value: null },
  43701. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43702. sheen: { value: 0 },
  43703. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43704. sheenColorMap: { value: null },
  43705. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43706. sheenRoughness: { value: 1 },
  43707. sheenRoughnessMap: { value: null },
  43708. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43709. transmission: { value: 0 },
  43710. transmissionMap: { value: null },
  43711. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43712. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43713. transmissionSamplerMap: { value: null },
  43714. thickness: { value: 0 },
  43715. thicknessMap: { value: null },
  43716. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43717. attenuationDistance: { value: 0 },
  43718. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43719. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43720. specularColorMap: { value: null },
  43721. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43722. specularIntensity: { value: 1 },
  43723. specularIntensityMap: { value: null },
  43724. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43725. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43726. anisotropyMap: { value: null },
  43727. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43728. }
  43729. ] ),
  43730. vertexShader: ShaderChunk.meshphysical_vert,
  43731. fragmentShader: ShaderChunk.meshphysical_frag
  43732. };
  43733. const _rgb = { r: 0, b: 0, g: 0 };
  43734. const _e1$1 = /*@__PURE__*/ new Euler();
  43735. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43736. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43737. const clearColor = new Color( 0x000000 );
  43738. let clearAlpha = alpha === true ? 0 : 1;
  43739. let planeMesh;
  43740. let boxMesh;
  43741. let currentBackground = null;
  43742. let currentBackgroundVersion = 0;
  43743. let currentTonemapping = null;
  43744. function getBackground( scene ) {
  43745. let background = scene.isScene === true ? scene.background : null;
  43746. if ( background && background.isTexture ) {
  43747. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43748. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43749. }
  43750. return background;
  43751. }
  43752. function render( scene ) {
  43753. let forceClear = false;
  43754. const background = getBackground( scene );
  43755. if ( background === null ) {
  43756. setClear( clearColor, clearAlpha );
  43757. } else if ( background && background.isColor ) {
  43758. setClear( background, 1 );
  43759. forceClear = true;
  43760. }
  43761. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43762. if ( environmentBlendMode === 'additive' ) {
  43763. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43764. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43765. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43766. }
  43767. if ( renderer.autoClear || forceClear ) {
  43768. // buffers might not be writable which is required to ensure a correct clear
  43769. state.buffers.depth.setTest( true );
  43770. state.buffers.depth.setMask( true );
  43771. state.buffers.color.setMask( true );
  43772. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43773. }
  43774. }
  43775. function addToRenderList( renderList, scene ) {
  43776. const background = getBackground( scene );
  43777. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43778. if ( boxMesh === undefined ) {
  43779. boxMesh = new Mesh(
  43780. new BoxGeometry( 1, 1, 1 ),
  43781. new ShaderMaterial( {
  43782. name: 'BackgroundCubeMaterial',
  43783. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43784. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43785. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43786. side: BackSide,
  43787. depthTest: false,
  43788. depthWrite: false,
  43789. fog: false,
  43790. allowOverride: false
  43791. } )
  43792. );
  43793. boxMesh.geometry.deleteAttribute( 'normal' );
  43794. boxMesh.geometry.deleteAttribute( 'uv' );
  43795. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43796. this.matrixWorld.copyPosition( camera.matrixWorld );
  43797. };
  43798. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43799. Object.defineProperty( boxMesh.material, 'envMap', {
  43800. get: function () {
  43801. return this.uniforms.envMap.value;
  43802. }
  43803. } );
  43804. objects.update( boxMesh );
  43805. }
  43806. _e1$1.copy( scene.backgroundRotation );
  43807. // accommodate left-handed frame
  43808. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43809. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43810. // environment maps which are not cube render targets or PMREMs follow a different convention
  43811. _e1$1.y *= -1;
  43812. _e1$1.z *= -1;
  43813. }
  43814. boxMesh.material.uniforms.envMap.value = background;
  43815. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43816. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43817. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43818. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43819. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43820. if ( currentBackground !== background ||
  43821. currentBackgroundVersion !== background.version ||
  43822. currentTonemapping !== renderer.toneMapping ) {
  43823. boxMesh.material.needsUpdate = true;
  43824. currentBackground = background;
  43825. currentBackgroundVersion = background.version;
  43826. currentTonemapping = renderer.toneMapping;
  43827. }
  43828. boxMesh.layers.enableAll();
  43829. // push to the pre-sorted opaque render list
  43830. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43831. } else if ( background && background.isTexture ) {
  43832. if ( planeMesh === undefined ) {
  43833. planeMesh = new Mesh(
  43834. new PlaneGeometry( 2, 2 ),
  43835. new ShaderMaterial( {
  43836. name: 'BackgroundMaterial',
  43837. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43838. vertexShader: ShaderLib.background.vertexShader,
  43839. fragmentShader: ShaderLib.background.fragmentShader,
  43840. side: FrontSide,
  43841. depthTest: false,
  43842. depthWrite: false,
  43843. fog: false,
  43844. allowOverride: false
  43845. } )
  43846. );
  43847. planeMesh.geometry.deleteAttribute( 'normal' );
  43848. // add "map" material property so the renderer can evaluate it like for built-in materials
  43849. Object.defineProperty( planeMesh.material, 'map', {
  43850. get: function () {
  43851. return this.uniforms.t2D.value;
  43852. }
  43853. } );
  43854. objects.update( planeMesh );
  43855. }
  43856. planeMesh.material.uniforms.t2D.value = background;
  43857. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43858. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43859. if ( background.matrixAutoUpdate === true ) {
  43860. background.updateMatrix();
  43861. }
  43862. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43863. if ( currentBackground !== background ||
  43864. currentBackgroundVersion !== background.version ||
  43865. currentTonemapping !== renderer.toneMapping ) {
  43866. planeMesh.material.needsUpdate = true;
  43867. currentBackground = background;
  43868. currentBackgroundVersion = background.version;
  43869. currentTonemapping = renderer.toneMapping;
  43870. }
  43871. planeMesh.layers.enableAll();
  43872. // push to the pre-sorted opaque render list
  43873. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43874. }
  43875. }
  43876. function setClear( color, alpha ) {
  43877. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43878. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43879. }
  43880. function dispose() {
  43881. if ( boxMesh !== undefined ) {
  43882. boxMesh.geometry.dispose();
  43883. boxMesh.material.dispose();
  43884. boxMesh = undefined;
  43885. }
  43886. if ( planeMesh !== undefined ) {
  43887. planeMesh.geometry.dispose();
  43888. planeMesh.material.dispose();
  43889. planeMesh = undefined;
  43890. }
  43891. }
  43892. return {
  43893. getClearColor: function () {
  43894. return clearColor;
  43895. },
  43896. setClearColor: function ( color, alpha = 1 ) {
  43897. clearColor.set( color );
  43898. clearAlpha = alpha;
  43899. setClear( clearColor, clearAlpha );
  43900. },
  43901. getClearAlpha: function () {
  43902. return clearAlpha;
  43903. },
  43904. setClearAlpha: function ( alpha ) {
  43905. clearAlpha = alpha;
  43906. setClear( clearColor, clearAlpha );
  43907. },
  43908. render: render,
  43909. addToRenderList: addToRenderList,
  43910. dispose: dispose
  43911. };
  43912. }
  43913. function WebGLBindingStates( gl, attributes ) {
  43914. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43915. const bindingStates = {};
  43916. const defaultState = createBindingState( null );
  43917. let currentState = defaultState;
  43918. let forceUpdate = false;
  43919. function setup( object, material, program, geometry, index ) {
  43920. let updateBuffers = false;
  43921. const state = getBindingState( object, geometry, program, material );
  43922. if ( currentState !== state ) {
  43923. currentState = state;
  43924. bindVertexArrayObject( currentState.object );
  43925. }
  43926. updateBuffers = needsUpdate( object, geometry, program, index );
  43927. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43928. if ( index !== null ) {
  43929. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43930. }
  43931. if ( updateBuffers || forceUpdate ) {
  43932. forceUpdate = false;
  43933. setupVertexAttributes( object, material, program, geometry );
  43934. if ( index !== null ) {
  43935. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43936. }
  43937. }
  43938. }
  43939. function createVertexArrayObject() {
  43940. return gl.createVertexArray();
  43941. }
  43942. function bindVertexArrayObject( vao ) {
  43943. return gl.bindVertexArray( vao );
  43944. }
  43945. function deleteVertexArrayObject( vao ) {
  43946. return gl.deleteVertexArray( vao );
  43947. }
  43948. function getBindingState( object, geometry, program, material ) {
  43949. const wireframe = ( material.wireframe === true );
  43950. let objectMap = bindingStates[ geometry.id ];
  43951. if ( objectMap === undefined ) {
  43952. objectMap = {};
  43953. bindingStates[ geometry.id ] = objectMap;
  43954. }
  43955. // Each InstancedMesh requires unique binding states because it contains instanced attributes.
  43956. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  43957. let programMap = objectMap[ objectId ];
  43958. if ( programMap === undefined ) {
  43959. programMap = {};
  43960. objectMap[ objectId ] = programMap;
  43961. }
  43962. let stateMap = programMap[ program.id ];
  43963. if ( stateMap === undefined ) {
  43964. stateMap = {};
  43965. programMap[ program.id ] = stateMap;
  43966. }
  43967. let state = stateMap[ wireframe ];
  43968. if ( state === undefined ) {
  43969. state = createBindingState( createVertexArrayObject() );
  43970. stateMap[ wireframe ] = state;
  43971. }
  43972. return state;
  43973. }
  43974. function createBindingState( vao ) {
  43975. const newAttributes = [];
  43976. const enabledAttributes = [];
  43977. const attributeDivisors = [];
  43978. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43979. newAttributes[ i ] = 0;
  43980. enabledAttributes[ i ] = 0;
  43981. attributeDivisors[ i ] = 0;
  43982. }
  43983. return {
  43984. // for backward compatibility on non-VAO support browser
  43985. geometry: null,
  43986. program: null,
  43987. wireframe: false,
  43988. newAttributes: newAttributes,
  43989. enabledAttributes: enabledAttributes,
  43990. attributeDivisors: attributeDivisors,
  43991. object: vao,
  43992. attributes: {},
  43993. index: null
  43994. };
  43995. }
  43996. function needsUpdate( object, geometry, program, index ) {
  43997. const cachedAttributes = currentState.attributes;
  43998. const geometryAttributes = geometry.attributes;
  43999. let attributesNum = 0;
  44000. const programAttributes = program.getAttributes();
  44001. for ( const name in programAttributes ) {
  44002. const programAttribute = programAttributes[ name ];
  44003. if ( programAttribute.location >= 0 ) {
  44004. const cachedAttribute = cachedAttributes[ name ];
  44005. let geometryAttribute = geometryAttributes[ name ];
  44006. if ( geometryAttribute === undefined ) {
  44007. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44008. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44009. }
  44010. if ( cachedAttribute === undefined ) return true;
  44011. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  44012. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  44013. attributesNum ++;
  44014. }
  44015. }
  44016. if ( currentState.attributesNum !== attributesNum ) return true;
  44017. if ( currentState.index !== index ) return true;
  44018. return false;
  44019. }
  44020. function saveCache( object, geometry, program, index ) {
  44021. const cache = {};
  44022. const attributes = geometry.attributes;
  44023. let attributesNum = 0;
  44024. const programAttributes = program.getAttributes();
  44025. for ( const name in programAttributes ) {
  44026. const programAttribute = programAttributes[ name ];
  44027. if ( programAttribute.location >= 0 ) {
  44028. let attribute = attributes[ name ];
  44029. if ( attribute === undefined ) {
  44030. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  44031. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  44032. }
  44033. const data = {};
  44034. data.attribute = attribute;
  44035. if ( attribute && attribute.data ) {
  44036. data.data = attribute.data;
  44037. }
  44038. cache[ name ] = data;
  44039. attributesNum ++;
  44040. }
  44041. }
  44042. currentState.attributes = cache;
  44043. currentState.attributesNum = attributesNum;
  44044. currentState.index = index;
  44045. }
  44046. function initAttributes() {
  44047. const newAttributes = currentState.newAttributes;
  44048. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  44049. newAttributes[ i ] = 0;
  44050. }
  44051. }
  44052. function enableAttribute( attribute ) {
  44053. enableAttributeAndDivisor( attribute, 0 );
  44054. }
  44055. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  44056. const newAttributes = currentState.newAttributes;
  44057. const enabledAttributes = currentState.enabledAttributes;
  44058. const attributeDivisors = currentState.attributeDivisors;
  44059. newAttributes[ attribute ] = 1;
  44060. if ( enabledAttributes[ attribute ] === 0 ) {
  44061. gl.enableVertexAttribArray( attribute );
  44062. enabledAttributes[ attribute ] = 1;
  44063. }
  44064. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  44065. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  44066. attributeDivisors[ attribute ] = meshPerAttribute;
  44067. }
  44068. }
  44069. function disableUnusedAttributes() {
  44070. const newAttributes = currentState.newAttributes;
  44071. const enabledAttributes = currentState.enabledAttributes;
  44072. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  44073. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  44074. gl.disableVertexAttribArray( i );
  44075. enabledAttributes[ i ] = 0;
  44076. }
  44077. }
  44078. }
  44079. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  44080. if ( integer === true ) {
  44081. gl.vertexAttribIPointer( index, size, type, stride, offset );
  44082. } else {
  44083. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  44084. }
  44085. }
  44086. function setupVertexAttributes( object, material, program, geometry ) {
  44087. initAttributes();
  44088. const geometryAttributes = geometry.attributes;
  44089. const programAttributes = program.getAttributes();
  44090. const materialDefaultAttributeValues = material.defaultAttributeValues;
  44091. for ( const name in programAttributes ) {
  44092. const programAttribute = programAttributes[ name ];
  44093. if ( programAttribute.location >= 0 ) {
  44094. let geometryAttribute = geometryAttributes[ name ];
  44095. if ( geometryAttribute === undefined ) {
  44096. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44097. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44098. }
  44099. if ( geometryAttribute !== undefined ) {
  44100. const normalized = geometryAttribute.normalized;
  44101. const size = geometryAttribute.itemSize;
  44102. const attribute = attributes.get( geometryAttribute );
  44103. // TODO Attribute may not be available on context restore
  44104. if ( attribute === undefined ) continue;
  44105. const buffer = attribute.buffer;
  44106. const type = attribute.type;
  44107. const bytesPerElement = attribute.bytesPerElement;
  44108. // check for integer attributes
  44109. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44110. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44111. const data = geometryAttribute.data;
  44112. const stride = data.stride;
  44113. const offset = geometryAttribute.offset;
  44114. if ( data.isInstancedInterleavedBuffer ) {
  44115. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44116. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44117. }
  44118. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44119. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44120. }
  44121. } else {
  44122. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44123. enableAttribute( programAttribute.location + i );
  44124. }
  44125. }
  44126. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44127. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44128. vertexAttribPointer(
  44129. programAttribute.location + i,
  44130. size / programAttribute.locationSize,
  44131. type,
  44132. normalized,
  44133. stride * bytesPerElement,
  44134. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44135. integer
  44136. );
  44137. }
  44138. } else {
  44139. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44140. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44141. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44142. }
  44143. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44144. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44145. }
  44146. } else {
  44147. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44148. enableAttribute( programAttribute.location + i );
  44149. }
  44150. }
  44151. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44152. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44153. vertexAttribPointer(
  44154. programAttribute.location + i,
  44155. size / programAttribute.locationSize,
  44156. type,
  44157. normalized,
  44158. size * bytesPerElement,
  44159. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44160. integer
  44161. );
  44162. }
  44163. }
  44164. } else if ( materialDefaultAttributeValues !== undefined ) {
  44165. const value = materialDefaultAttributeValues[ name ];
  44166. if ( value !== undefined ) {
  44167. switch ( value.length ) {
  44168. case 2:
  44169. gl.vertexAttrib2fv( programAttribute.location, value );
  44170. break;
  44171. case 3:
  44172. gl.vertexAttrib3fv( programAttribute.location, value );
  44173. break;
  44174. case 4:
  44175. gl.vertexAttrib4fv( programAttribute.location, value );
  44176. break;
  44177. default:
  44178. gl.vertexAttrib1fv( programAttribute.location, value );
  44179. }
  44180. }
  44181. }
  44182. }
  44183. }
  44184. disableUnusedAttributes();
  44185. }
  44186. function dispose() {
  44187. reset();
  44188. for ( const geometryId in bindingStates ) {
  44189. const objectMap = bindingStates[ geometryId ];
  44190. for ( const objectId in objectMap ) {
  44191. const programMap = objectMap[ objectId ];
  44192. for ( const programId in programMap ) {
  44193. const stateMap = programMap[ programId ];
  44194. for ( const wireframe in stateMap ) {
  44195. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44196. delete stateMap[ wireframe ];
  44197. }
  44198. delete programMap[ programId ];
  44199. }
  44200. }
  44201. delete bindingStates[ geometryId ];
  44202. }
  44203. }
  44204. function releaseStatesOfGeometry( geometry ) {
  44205. if ( bindingStates[ geometry.id ] === undefined ) return;
  44206. const objectMap = bindingStates[ geometry.id ];
  44207. for ( const objectId in objectMap ) {
  44208. const programMap = objectMap[ objectId ];
  44209. for ( const programId in programMap ) {
  44210. const stateMap = programMap[ programId ];
  44211. for ( const wireframe in stateMap ) {
  44212. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44213. delete stateMap[ wireframe ];
  44214. }
  44215. delete programMap[ programId ];
  44216. }
  44217. }
  44218. delete bindingStates[ geometry.id ];
  44219. }
  44220. function releaseStatesOfProgram( program ) {
  44221. for ( const geometryId in bindingStates ) {
  44222. const objectMap = bindingStates[ geometryId ];
  44223. for ( const objectId in objectMap ) {
  44224. const programMap = objectMap[ objectId ];
  44225. if ( programMap[ program.id ] === undefined ) continue;
  44226. const stateMap = programMap[ program.id ];
  44227. for ( const wireframe in stateMap ) {
  44228. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44229. delete stateMap[ wireframe ];
  44230. }
  44231. delete programMap[ program.id ];
  44232. }
  44233. }
  44234. }
  44235. function releaseStatesOfObject( object ) {
  44236. for ( const geometryId in bindingStates ) {
  44237. const objectMap = bindingStates[ geometryId ];
  44238. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44239. const programMap = objectMap[ objectId ];
  44240. if ( programMap === undefined ) continue;
  44241. for ( const programId in programMap ) {
  44242. const stateMap = programMap[ programId ];
  44243. for ( const wireframe in stateMap ) {
  44244. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44245. delete stateMap[ wireframe ];
  44246. }
  44247. delete programMap[ programId ];
  44248. }
  44249. delete objectMap[ objectId ];
  44250. if ( Object.keys( objectMap ).length === 0 ) {
  44251. delete bindingStates[ geometryId ];
  44252. }
  44253. }
  44254. }
  44255. function reset() {
  44256. resetDefaultState();
  44257. forceUpdate = true;
  44258. if ( currentState === defaultState ) return;
  44259. currentState = defaultState;
  44260. bindVertexArrayObject( currentState.object );
  44261. }
  44262. // for backward-compatibility
  44263. function resetDefaultState() {
  44264. defaultState.geometry = null;
  44265. defaultState.program = null;
  44266. defaultState.wireframe = false;
  44267. }
  44268. return {
  44269. setup: setup,
  44270. reset: reset,
  44271. resetDefaultState: resetDefaultState,
  44272. dispose: dispose,
  44273. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44274. releaseStatesOfObject: releaseStatesOfObject,
  44275. releaseStatesOfProgram: releaseStatesOfProgram,
  44276. initAttributes: initAttributes,
  44277. enableAttribute: enableAttribute,
  44278. disableUnusedAttributes: disableUnusedAttributes
  44279. };
  44280. }
  44281. function WebGLBufferRenderer( gl, extensions, info ) {
  44282. let mode;
  44283. function setMode( value ) {
  44284. mode = value;
  44285. }
  44286. function render( start, count ) {
  44287. gl.drawArrays( mode, start, count );
  44288. info.update( count, mode, 1 );
  44289. }
  44290. function renderInstances( start, count, primcount ) {
  44291. if ( primcount === 0 ) return;
  44292. gl.drawArraysInstanced( mode, start, count, primcount );
  44293. info.update( count, mode, primcount );
  44294. }
  44295. function renderMultiDraw( starts, counts, drawCount ) {
  44296. if ( drawCount === 0 ) return;
  44297. const extension = extensions.get( 'WEBGL_multi_draw' );
  44298. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44299. let elementCount = 0;
  44300. for ( let i = 0; i < drawCount; i ++ ) {
  44301. elementCount += counts[ i ];
  44302. }
  44303. info.update( elementCount, mode, 1 );
  44304. }
  44305. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44306. if ( drawCount === 0 ) return;
  44307. const extension = extensions.get( 'WEBGL_multi_draw' );
  44308. if ( extension === null ) {
  44309. for ( let i = 0; i < starts.length; i ++ ) {
  44310. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44311. }
  44312. } else {
  44313. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44314. let elementCount = 0;
  44315. for ( let i = 0; i < drawCount; i ++ ) {
  44316. elementCount += counts[ i ] * primcount[ i ];
  44317. }
  44318. info.update( elementCount, mode, 1 );
  44319. }
  44320. }
  44321. //
  44322. this.setMode = setMode;
  44323. this.render = render;
  44324. this.renderInstances = renderInstances;
  44325. this.renderMultiDraw = renderMultiDraw;
  44326. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44327. }
  44328. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44329. let maxAnisotropy;
  44330. function getMaxAnisotropy() {
  44331. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44332. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44333. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44334. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44335. } else {
  44336. maxAnisotropy = 0;
  44337. }
  44338. return maxAnisotropy;
  44339. }
  44340. function textureFormatReadable( textureFormat ) {
  44341. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44342. return false;
  44343. }
  44344. return true;
  44345. }
  44346. function textureTypeReadable( textureType ) {
  44347. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44348. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44349. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44350. return false;
  44351. }
  44352. return true;
  44353. }
  44354. function getMaxPrecision( precision ) {
  44355. if ( precision === 'highp' ) {
  44356. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44357. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44358. return 'highp';
  44359. }
  44360. precision = 'mediump';
  44361. }
  44362. if ( precision === 'mediump' ) {
  44363. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44364. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44365. return 'mediump';
  44366. }
  44367. }
  44368. return 'lowp';
  44369. }
  44370. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44371. const maxPrecision = getMaxPrecision( precision );
  44372. if ( maxPrecision !== precision ) {
  44373. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44374. precision = maxPrecision;
  44375. }
  44376. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44377. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44378. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44379. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44380. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44381. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44382. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44383. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44384. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44385. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44386. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44387. const samples = gl.getParameter( gl.SAMPLES );
  44388. return {
  44389. isWebGL2: true, // keeping this for backwards compatibility
  44390. getMaxAnisotropy: getMaxAnisotropy,
  44391. getMaxPrecision: getMaxPrecision,
  44392. textureFormatReadable: textureFormatReadable,
  44393. textureTypeReadable: textureTypeReadable,
  44394. precision: precision,
  44395. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44396. reversedDepthBuffer: reversedDepthBuffer,
  44397. maxTextures: maxTextures,
  44398. maxVertexTextures: maxVertexTextures,
  44399. maxTextureSize: maxTextureSize,
  44400. maxCubemapSize: maxCubemapSize,
  44401. maxAttributes: maxAttributes,
  44402. maxVertexUniforms: maxVertexUniforms,
  44403. maxVaryings: maxVaryings,
  44404. maxFragmentUniforms: maxFragmentUniforms,
  44405. maxSamples: maxSamples,
  44406. samples: samples
  44407. };
  44408. }
  44409. function WebGLClipping( properties ) {
  44410. const scope = this;
  44411. let globalState = null,
  44412. numGlobalPlanes = 0,
  44413. localClippingEnabled = false,
  44414. renderingShadows = false;
  44415. const plane = new Plane(),
  44416. viewNormalMatrix = new Matrix3(),
  44417. uniform = { value: null, needsUpdate: false };
  44418. this.uniform = uniform;
  44419. this.numPlanes = 0;
  44420. this.numIntersection = 0;
  44421. this.init = function ( planes, enableLocalClipping ) {
  44422. const enabled =
  44423. planes.length !== 0 ||
  44424. enableLocalClipping ||
  44425. // enable state of previous frame - the clipping code has to
  44426. // run another frame in order to reset the state:
  44427. numGlobalPlanes !== 0 ||
  44428. localClippingEnabled;
  44429. localClippingEnabled = enableLocalClipping;
  44430. numGlobalPlanes = planes.length;
  44431. return enabled;
  44432. };
  44433. this.beginShadows = function () {
  44434. renderingShadows = true;
  44435. projectPlanes( null );
  44436. };
  44437. this.endShadows = function () {
  44438. renderingShadows = false;
  44439. };
  44440. this.setGlobalState = function ( planes, camera ) {
  44441. globalState = projectPlanes( planes, camera, 0 );
  44442. };
  44443. this.setState = function ( material, camera, useCache ) {
  44444. const planes = material.clippingPlanes,
  44445. clipIntersection = material.clipIntersection,
  44446. clipShadows = material.clipShadows;
  44447. const materialProperties = properties.get( material );
  44448. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44449. // there's no local clipping
  44450. if ( renderingShadows ) {
  44451. // there's no global clipping
  44452. projectPlanes( null );
  44453. } else {
  44454. resetGlobalState();
  44455. }
  44456. } else {
  44457. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44458. lGlobal = nGlobal * 4;
  44459. let dstArray = materialProperties.clippingState || null;
  44460. uniform.value = dstArray; // ensure unique state
  44461. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44462. for ( let i = 0; i !== lGlobal; ++ i ) {
  44463. dstArray[ i ] = globalState[ i ];
  44464. }
  44465. materialProperties.clippingState = dstArray;
  44466. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44467. this.numPlanes += nGlobal;
  44468. }
  44469. };
  44470. function resetGlobalState() {
  44471. if ( uniform.value !== globalState ) {
  44472. uniform.value = globalState;
  44473. uniform.needsUpdate = numGlobalPlanes > 0;
  44474. }
  44475. scope.numPlanes = numGlobalPlanes;
  44476. scope.numIntersection = 0;
  44477. }
  44478. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44479. const nPlanes = planes !== null ? planes.length : 0;
  44480. let dstArray = null;
  44481. if ( nPlanes !== 0 ) {
  44482. dstArray = uniform.value;
  44483. if ( skipTransform !== true || dstArray === null ) {
  44484. const flatSize = dstOffset + nPlanes * 4,
  44485. viewMatrix = camera.matrixWorldInverse;
  44486. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44487. if ( dstArray === null || dstArray.length < flatSize ) {
  44488. dstArray = new Float32Array( flatSize );
  44489. }
  44490. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44491. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44492. plane.normal.toArray( dstArray, i4 );
  44493. dstArray[ i4 + 3 ] = plane.constant;
  44494. }
  44495. }
  44496. uniform.value = dstArray;
  44497. uniform.needsUpdate = true;
  44498. }
  44499. scope.numPlanes = nPlanes;
  44500. scope.numIntersection = 0;
  44501. return dstArray;
  44502. }
  44503. }
  44504. function WebGLCubeMaps( renderer ) {
  44505. let cubemaps = new WeakMap();
  44506. function mapTextureMapping( texture, mapping ) {
  44507. if ( mapping === EquirectangularReflectionMapping ) {
  44508. texture.mapping = CubeReflectionMapping;
  44509. } else if ( mapping === EquirectangularRefractionMapping ) {
  44510. texture.mapping = CubeRefractionMapping;
  44511. }
  44512. return texture;
  44513. }
  44514. function get( texture ) {
  44515. if ( texture && texture.isTexture ) {
  44516. const mapping = texture.mapping;
  44517. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44518. if ( cubemaps.has( texture ) ) {
  44519. const cubemap = cubemaps.get( texture ).texture;
  44520. return mapTextureMapping( cubemap, texture.mapping );
  44521. } else {
  44522. const image = texture.image;
  44523. if ( image && image.height > 0 ) {
  44524. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44525. renderTarget.fromEquirectangularTexture( renderer, texture );
  44526. cubemaps.set( texture, renderTarget );
  44527. texture.addEventListener( 'dispose', onTextureDispose );
  44528. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44529. } else {
  44530. // image not yet ready. try the conversion next frame
  44531. return null;
  44532. }
  44533. }
  44534. }
  44535. }
  44536. return texture;
  44537. }
  44538. function onTextureDispose( event ) {
  44539. const texture = event.target;
  44540. texture.removeEventListener( 'dispose', onTextureDispose );
  44541. const cubemap = cubemaps.get( texture );
  44542. if ( cubemap !== undefined ) {
  44543. cubemaps.delete( texture );
  44544. cubemap.dispose();
  44545. }
  44546. }
  44547. function dispose() {
  44548. cubemaps = new WeakMap();
  44549. }
  44550. return {
  44551. get: get,
  44552. dispose: dispose
  44553. };
  44554. }
  44555. const LOD_MIN = 4;
  44556. // The standard deviations (radians) associated with the extra mips.
  44557. // Used for scene blur in fromScene() method.
  44558. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44559. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44560. // samples and exit early, but not recompile the shader.
  44561. // Used for scene blur in fromScene() method.
  44562. const MAX_SAMPLES = 20;
  44563. // GGX VNDF importance sampling configuration
  44564. const GGX_SAMPLES = 256;
  44565. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44566. const _clearColor = /*@__PURE__*/ new Color();
  44567. let _oldTarget = null;
  44568. let _oldActiveCubeFace = 0;
  44569. let _oldActiveMipmapLevel = 0;
  44570. let _oldXrEnabled = false;
  44571. const _origin = /*@__PURE__*/ new Vector3();
  44572. /**
  44573. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44574. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44575. * blur to be quickly accessed based on material roughness. It is packed into a
  44576. * special CubeUV format that allows us to perform custom interpolation so that
  44577. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44578. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44579. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44580. * higher roughness levels. In this way we maintain resolution to smoothly
  44581. * interpolate diffuse lighting while limiting sampling computation.
  44582. *
  44583. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44584. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44585. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44586. * used in material rendering for physically-based image-based lighting.
  44587. */
  44588. class PMREMGenerator {
  44589. /**
  44590. * Constructs a new PMREM generator.
  44591. *
  44592. * @param {WebGLRenderer} renderer - The renderer.
  44593. */
  44594. constructor( renderer ) {
  44595. this._renderer = renderer;
  44596. this._pingPongRenderTarget = null;
  44597. this._lodMax = 0;
  44598. this._cubeSize = 0;
  44599. this._sizeLods = [];
  44600. this._sigmas = [];
  44601. this._lodMeshes = [];
  44602. this._backgroundBox = null;
  44603. this._cubemapMaterial = null;
  44604. this._equirectMaterial = null;
  44605. this._blurMaterial = null;
  44606. this._ggxMaterial = null;
  44607. }
  44608. /**
  44609. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44610. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44611. * in radians to be applied to the scene before PMREM generation. Optional near
  44612. * and far planes ensure the scene is rendered in its entirety.
  44613. *
  44614. * @param {Scene} scene - The scene to be captured.
  44615. * @param {number} [sigma=0] - The blur radius in radians.
  44616. * @param {number} [near=0.1] - The near plane distance.
  44617. * @param {number} [far=100] - The far plane distance.
  44618. * @param {Object} [options={}] - The configuration options.
  44619. * @param {number} [options.size=256] - The texture size of the PMREM.
  44620. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44621. * @return {WebGLRenderTarget} The resulting PMREM.
  44622. */
  44623. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44624. const {
  44625. size = 256,
  44626. position = _origin,
  44627. } = options;
  44628. _oldTarget = this._renderer.getRenderTarget();
  44629. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44630. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44631. _oldXrEnabled = this._renderer.xr.enabled;
  44632. this._renderer.xr.enabled = false;
  44633. this._setSize( size );
  44634. const cubeUVRenderTarget = this._allocateTargets();
  44635. cubeUVRenderTarget.depthBuffer = true;
  44636. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44637. if ( sigma > 0 ) {
  44638. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44639. }
  44640. this._applyPMREM( cubeUVRenderTarget );
  44641. this._cleanup( cubeUVRenderTarget );
  44642. return cubeUVRenderTarget;
  44643. }
  44644. /**
  44645. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44646. * or HDR. The ideal input image size is 1k (1024 x 512),
  44647. * as this matches best with the 256 x 256 cubemap output.
  44648. *
  44649. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44650. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44651. * @return {WebGLRenderTarget} The resulting PMREM.
  44652. */
  44653. fromEquirectangular( equirectangular, renderTarget = null ) {
  44654. return this._fromTexture( equirectangular, renderTarget );
  44655. }
  44656. /**
  44657. * Generates a PMREM from an cubemap texture, which can be either LDR
  44658. * or HDR. The ideal input cube size is 256 x 256,
  44659. * as this matches best with the 256 x 256 cubemap output.
  44660. *
  44661. * @param {Texture} cubemap - The cubemap texture to be converted.
  44662. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44663. * @return {WebGLRenderTarget} The resulting PMREM.
  44664. */
  44665. fromCubemap( cubemap, renderTarget = null ) {
  44666. return this._fromTexture( cubemap, renderTarget );
  44667. }
  44668. /**
  44669. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44670. * your texture's network fetch for increased concurrency.
  44671. */
  44672. compileCubemapShader() {
  44673. if ( this._cubemapMaterial === null ) {
  44674. this._cubemapMaterial = _getCubemapMaterial();
  44675. this._compileMaterial( this._cubemapMaterial );
  44676. }
  44677. }
  44678. /**
  44679. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44680. * your texture's network fetch for increased concurrency.
  44681. */
  44682. compileEquirectangularShader() {
  44683. if ( this._equirectMaterial === null ) {
  44684. this._equirectMaterial = _getEquirectMaterial();
  44685. this._compileMaterial( this._equirectMaterial );
  44686. }
  44687. }
  44688. /**
  44689. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44690. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44691. * one of them will cause any others to also become unusable.
  44692. */
  44693. dispose() {
  44694. this._dispose();
  44695. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44696. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44697. if ( this._backgroundBox !== null ) {
  44698. this._backgroundBox.geometry.dispose();
  44699. this._backgroundBox.material.dispose();
  44700. }
  44701. }
  44702. // private interface
  44703. _setSize( cubeSize ) {
  44704. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44705. this._cubeSize = Math.pow( 2, this._lodMax );
  44706. }
  44707. _dispose() {
  44708. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44709. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44710. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44711. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44712. this._lodMeshes[ i ].geometry.dispose();
  44713. }
  44714. }
  44715. _cleanup( outputTarget ) {
  44716. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44717. this._renderer.xr.enabled = _oldXrEnabled;
  44718. outputTarget.scissorTest = false;
  44719. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44720. }
  44721. _fromTexture( texture, renderTarget ) {
  44722. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44723. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44724. } else { // Equirectangular
  44725. this._setSize( texture.image.width / 4 );
  44726. }
  44727. _oldTarget = this._renderer.getRenderTarget();
  44728. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44729. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44730. _oldXrEnabled = this._renderer.xr.enabled;
  44731. this._renderer.xr.enabled = false;
  44732. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44733. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44734. this._applyPMREM( cubeUVRenderTarget );
  44735. this._cleanup( cubeUVRenderTarget );
  44736. return cubeUVRenderTarget;
  44737. }
  44738. _allocateTargets() {
  44739. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44740. const height = 4 * this._cubeSize;
  44741. const params = {
  44742. magFilter: LinearFilter,
  44743. minFilter: LinearFilter,
  44744. generateMipmaps: false,
  44745. type: HalfFloatType,
  44746. format: RGBAFormat,
  44747. colorSpace: LinearSRGBColorSpace,
  44748. depthBuffer: false
  44749. };
  44750. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44751. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44752. if ( this._pingPongRenderTarget !== null ) {
  44753. this._dispose();
  44754. }
  44755. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44756. const { _lodMax } = this;
  44757. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44758. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44759. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  44760. }
  44761. return cubeUVRenderTarget;
  44762. }
  44763. _compileMaterial( material ) {
  44764. const mesh = new Mesh( new BufferGeometry(), material );
  44765. this._renderer.compile( mesh, _flatCamera );
  44766. }
  44767. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44768. const fov = 90;
  44769. const aspect = 1;
  44770. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44771. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44772. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44773. const renderer = this._renderer;
  44774. const originalAutoClear = renderer.autoClear;
  44775. const toneMapping = renderer.toneMapping;
  44776. renderer.getClearColor( _clearColor );
  44777. renderer.toneMapping = NoToneMapping;
  44778. renderer.autoClear = false;
  44779. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44780. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44781. if ( reversedDepthBuffer ) {
  44782. renderer.setRenderTarget( cubeUVRenderTarget );
  44783. renderer.clearDepth();
  44784. renderer.setRenderTarget( null );
  44785. }
  44786. if ( this._backgroundBox === null ) {
  44787. this._backgroundBox = new Mesh(
  44788. new BoxGeometry(),
  44789. new MeshBasicMaterial( {
  44790. name: 'PMREM.Background',
  44791. side: BackSide,
  44792. depthWrite: false,
  44793. depthTest: false,
  44794. } )
  44795. );
  44796. }
  44797. const backgroundBox = this._backgroundBox;
  44798. const backgroundMaterial = backgroundBox.material;
  44799. let useSolidColor = false;
  44800. const background = scene.background;
  44801. if ( background ) {
  44802. if ( background.isColor ) {
  44803. backgroundMaterial.color.copy( background );
  44804. scene.background = null;
  44805. useSolidColor = true;
  44806. }
  44807. } else {
  44808. backgroundMaterial.color.copy( _clearColor );
  44809. useSolidColor = true;
  44810. }
  44811. for ( let i = 0; i < 6; i ++ ) {
  44812. const col = i % 3;
  44813. if ( col === 0 ) {
  44814. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44815. cubeCamera.position.set( position.x, position.y, position.z );
  44816. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44817. } else if ( col === 1 ) {
  44818. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44819. cubeCamera.position.set( position.x, position.y, position.z );
  44820. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44821. } else {
  44822. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44823. cubeCamera.position.set( position.x, position.y, position.z );
  44824. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44825. }
  44826. const size = this._cubeSize;
  44827. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44828. renderer.setRenderTarget( cubeUVRenderTarget );
  44829. if ( useSolidColor ) {
  44830. renderer.render( backgroundBox, cubeCamera );
  44831. }
  44832. renderer.render( scene, cubeCamera );
  44833. }
  44834. renderer.toneMapping = toneMapping;
  44835. renderer.autoClear = originalAutoClear;
  44836. scene.background = background;
  44837. }
  44838. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44839. const renderer = this._renderer;
  44840. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44841. if ( isCubeTexture ) {
  44842. if ( this._cubemapMaterial === null ) {
  44843. this._cubemapMaterial = _getCubemapMaterial();
  44844. }
  44845. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44846. } else {
  44847. if ( this._equirectMaterial === null ) {
  44848. this._equirectMaterial = _getEquirectMaterial();
  44849. }
  44850. }
  44851. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44852. const mesh = this._lodMeshes[ 0 ];
  44853. mesh.material = material;
  44854. const uniforms = material.uniforms;
  44855. uniforms[ 'envMap' ].value = texture;
  44856. const size = this._cubeSize;
  44857. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44858. renderer.setRenderTarget( cubeUVRenderTarget );
  44859. renderer.render( mesh, _flatCamera );
  44860. }
  44861. _applyPMREM( cubeUVRenderTarget ) {
  44862. const renderer = this._renderer;
  44863. const autoClear = renderer.autoClear;
  44864. renderer.autoClear = false;
  44865. const n = this._lodMeshes.length;
  44866. // Use GGX VNDF importance sampling
  44867. for ( let i = 1; i < n; i ++ ) {
  44868. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  44869. }
  44870. renderer.autoClear = autoClear;
  44871. }
  44872. /**
  44873. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  44874. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  44875. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  44876. * applies incremental roughness filtering to avoid over-blurring.
  44877. *
  44878. * @private
  44879. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44880. * @param {number} lodIn - Source LOD level to read from
  44881. * @param {number} lodOut - Target LOD level to write to
  44882. */
  44883. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  44884. const renderer = this._renderer;
  44885. const pingPongRenderTarget = this._pingPongRenderTarget;
  44886. const ggxMaterial = this._ggxMaterial;
  44887. const ggxMesh = this._lodMeshes[ lodOut ];
  44888. ggxMesh.material = ggxMaterial;
  44889. const ggxUniforms = ggxMaterial.uniforms;
  44890. // Calculate incremental roughness between LOD levels
  44891. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  44892. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  44893. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  44894. // Apply blur strength mapping for better quality across the roughness range
  44895. const blurStrength = 0.0 + targetRoughness * 1.25;
  44896. const adjustedRoughness = incrementalRoughness * blurStrength;
  44897. // Calculate viewport position based on output LOD level
  44898. const { _lodMax } = this;
  44899. const outputSize = this._sizeLods[ lodOut ];
  44900. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44901. const y = 4 * ( this._cubeSize - outputSize );
  44902. // Read from previous LOD with incremental roughness
  44903. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  44904. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  44905. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  44906. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44907. renderer.setRenderTarget( pingPongRenderTarget );
  44908. renderer.render( ggxMesh, _flatCamera );
  44909. // Copy from pingPong back to cubeUV (simple direct copy)
  44910. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  44911. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  44912. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  44913. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44914. renderer.setRenderTarget( cubeUVRenderTarget );
  44915. renderer.render( ggxMesh, _flatCamera );
  44916. }
  44917. /**
  44918. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44919. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44920. * the blur latitudinally (around the poles), and then longitudinally (towards
  44921. * the poles) to approximate the orthogonally-separable blur. It is least
  44922. * accurate at the poles, but still does a decent job.
  44923. *
  44924. * Used for initial scene blur in fromScene() method when sigma > 0.
  44925. *
  44926. * @private
  44927. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44928. * @param {number} lodIn
  44929. * @param {number} lodOut
  44930. * @param {number} sigma
  44931. * @param {Vector3} [poleAxis]
  44932. */
  44933. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44934. const pingPongRenderTarget = this._pingPongRenderTarget;
  44935. this._halfBlur(
  44936. cubeUVRenderTarget,
  44937. pingPongRenderTarget,
  44938. lodIn,
  44939. lodOut,
  44940. sigma,
  44941. 'latitudinal',
  44942. poleAxis );
  44943. this._halfBlur(
  44944. pingPongRenderTarget,
  44945. cubeUVRenderTarget,
  44946. lodOut,
  44947. lodOut,
  44948. sigma,
  44949. 'longitudinal',
  44950. poleAxis );
  44951. }
  44952. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44953. const renderer = this._renderer;
  44954. const blurMaterial = this._blurMaterial;
  44955. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44956. error(
  44957. 'blur direction must be either latitudinal or longitudinal!' );
  44958. }
  44959. // Number of standard deviations at which to cut off the discrete approximation.
  44960. const STANDARD_DEVIATIONS = 3;
  44961. const blurMesh = this._lodMeshes[ lodOut ];
  44962. blurMesh.material = blurMaterial;
  44963. const blurUniforms = blurMaterial.uniforms;
  44964. const pixels = this._sizeLods[ lodIn ] - 1;
  44965. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44966. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44967. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44968. if ( samples > MAX_SAMPLES ) {
  44969. warn( `sigmaRadians, ${
  44970. sigmaRadians}, is too large and will clip, as it requested ${
  44971. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44972. }
  44973. const weights = [];
  44974. let sum = 0;
  44975. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44976. const x = i / sigmaPixels;
  44977. const weight = Math.exp( - x * x / 2 );
  44978. weights.push( weight );
  44979. if ( i === 0 ) {
  44980. sum += weight;
  44981. } else if ( i < samples ) {
  44982. sum += 2 * weight;
  44983. }
  44984. }
  44985. for ( let i = 0; i < weights.length; i ++ ) {
  44986. weights[ i ] = weights[ i ] / sum;
  44987. }
  44988. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44989. blurUniforms[ 'samples' ].value = samples;
  44990. blurUniforms[ 'weights' ].value = weights;
  44991. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44992. if ( poleAxis ) {
  44993. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44994. }
  44995. const { _lodMax } = this;
  44996. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44997. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44998. const outputSize = this._sizeLods[ lodOut ];
  44999. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45000. const y = 4 * ( this._cubeSize - outputSize );
  45001. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  45002. renderer.setRenderTarget( targetOut );
  45003. renderer.render( blurMesh, _flatCamera );
  45004. }
  45005. }
  45006. function _createPlanes( lodMax ) {
  45007. const sizeLods = [];
  45008. const sigmas = [];
  45009. const lodMeshes = [];
  45010. let lod = lodMax;
  45011. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  45012. for ( let i = 0; i < totalLods; i ++ ) {
  45013. const sizeLod = Math.pow( 2, lod );
  45014. sizeLods.push( sizeLod );
  45015. let sigma = 1.0 / sizeLod;
  45016. if ( i > lodMax - LOD_MIN ) {
  45017. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  45018. } else if ( i === 0 ) {
  45019. sigma = 0;
  45020. }
  45021. sigmas.push( sigma );
  45022. const texelSize = 1.0 / ( sizeLod - 2 );
  45023. const min = - texelSize;
  45024. const max = 1 + texelSize;
  45025. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  45026. const cubeFaces = 6;
  45027. const vertices = 6;
  45028. const positionSize = 3;
  45029. const uvSize = 2;
  45030. const faceIndexSize = 1;
  45031. const position = new Float32Array( positionSize * vertices * cubeFaces );
  45032. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  45033. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  45034. for ( let face = 0; face < cubeFaces; face ++ ) {
  45035. const x = ( face % 3 ) * 2 / 3 - 1;
  45036. const y = face > 2 ? 0 : -1;
  45037. const coordinates = [
  45038. x, y, 0,
  45039. x + 2 / 3, y, 0,
  45040. x + 2 / 3, y + 1, 0,
  45041. x, y, 0,
  45042. x + 2 / 3, y + 1, 0,
  45043. x, y + 1, 0
  45044. ];
  45045. position.set( coordinates, positionSize * vertices * face );
  45046. uv.set( uv1, uvSize * vertices * face );
  45047. const fill = [ face, face, face, face, face, face ];
  45048. faceIndex.set( fill, faceIndexSize * vertices * face );
  45049. }
  45050. const planes = new BufferGeometry();
  45051. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  45052. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  45053. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  45054. lodMeshes.push( new Mesh( planes, null ) );
  45055. if ( lod > LOD_MIN ) {
  45056. lod --;
  45057. }
  45058. }
  45059. return { lodMeshes, sizeLods, sigmas };
  45060. }
  45061. function _createRenderTarget( width, height, params ) {
  45062. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  45063. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  45064. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  45065. cubeUVRenderTarget.scissorTest = true;
  45066. return cubeUVRenderTarget;
  45067. }
  45068. function _setViewport( target, x, y, width, height ) {
  45069. target.viewport.set( x, y, width, height );
  45070. target.scissor.set( x, y, width, height );
  45071. }
  45072. function _getGGXShader( lodMax, width, height ) {
  45073. const shaderMaterial = new ShaderMaterial( {
  45074. name: 'PMREMGGXConvolution',
  45075. defines: {
  45076. 'GGX_SAMPLES': GGX_SAMPLES,
  45077. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45078. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45079. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45080. },
  45081. uniforms: {
  45082. 'envMap': { value: null },
  45083. 'roughness': { value: 0.0 },
  45084. 'mipInt': { value: 0 }
  45085. },
  45086. vertexShader: _getCommonVertexShader(),
  45087. fragmentShader: /* glsl */`
  45088. precision highp float;
  45089. precision highp int;
  45090. varying vec3 vOutputDirection;
  45091. uniform sampler2D envMap;
  45092. uniform float roughness;
  45093. uniform float mipInt;
  45094. #define ENVMAP_TYPE_CUBE_UV
  45095. #include <cube_uv_reflection_fragment>
  45096. #define PI 3.14159265359
  45097. // Van der Corput radical inverse
  45098. float radicalInverse_VdC(uint bits) {
  45099. bits = (bits << 16u) | (bits >> 16u);
  45100. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  45101. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  45102. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  45103. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  45104. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  45105. }
  45106. // Hammersley sequence
  45107. vec2 hammersley(uint i, uint N) {
  45108. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  45109. }
  45110. // GGX VNDF importance sampling (Eric Heitz 2018)
  45111. // "Sampling the GGX Distribution of Visible Normals"
  45112. // https://jcgt.org/published/0007/04/01/
  45113. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  45114. float alpha = roughness * roughness;
  45115. // Section 4.1: Orthonormal basis
  45116. vec3 T1 = vec3(1.0, 0.0, 0.0);
  45117. vec3 T2 = cross(V, T1);
  45118. // Section 4.2: Parameterization of projected area
  45119. float r = sqrt(Xi.x);
  45120. float phi = 2.0 * PI * Xi.y;
  45121. float t1 = r * cos(phi);
  45122. float t2 = r * sin(phi);
  45123. float s = 0.5 * (1.0 + V.z);
  45124. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45125. // Section 4.3: Reprojection onto hemisphere
  45126. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;
  45127. // Section 3.4: Transform back to ellipsoid configuration
  45128. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45129. }
  45130. void main() {
  45131. vec3 N = normalize(vOutputDirection);
  45132. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45133. vec3 prefilteredColor = vec3(0.0);
  45134. float totalWeight = 0.0;
  45135. // For very low roughness, just sample the environment directly
  45136. if (roughness < 0.001) {
  45137. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45138. return;
  45139. }
  45140. // Tangent space basis for VNDF sampling
  45141. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45142. vec3 tangent = normalize(cross(up, N));
  45143. vec3 bitangent = cross(N, tangent);
  45144. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45145. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45146. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45147. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45148. // Transform H back to world space
  45149. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45150. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45151. float NdotL = max(dot(N, L), 0.0);
  45152. if(NdotL > 0.0) {
  45153. // Sample environment at fixed mip level
  45154. // VNDF importance sampling handles the distribution filtering
  45155. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45156. // Weight by NdotL for the split-sum approximation
  45157. // VNDF PDF naturally accounts for the visible microfacet distribution
  45158. prefilteredColor += sampleColor * NdotL;
  45159. totalWeight += NdotL;
  45160. }
  45161. }
  45162. if (totalWeight > 0.0) {
  45163. prefilteredColor = prefilteredColor / totalWeight;
  45164. }
  45165. gl_FragColor = vec4(prefilteredColor, 1.0);
  45166. }
  45167. `,
  45168. blending: NoBlending,
  45169. depthTest: false,
  45170. depthWrite: false
  45171. } );
  45172. return shaderMaterial;
  45173. }
  45174. function _getBlurShader( lodMax, width, height ) {
  45175. const weights = new Float32Array( MAX_SAMPLES );
  45176. const poleAxis = new Vector3( 0, 1, 0 );
  45177. const shaderMaterial = new ShaderMaterial( {
  45178. name: 'SphericalGaussianBlur',
  45179. defines: {
  45180. 'n': MAX_SAMPLES,
  45181. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45182. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45183. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45184. },
  45185. uniforms: {
  45186. 'envMap': { value: null },
  45187. 'samples': { value: 1 },
  45188. 'weights': { value: weights },
  45189. 'latitudinal': { value: false },
  45190. 'dTheta': { value: 0 },
  45191. 'mipInt': { value: 0 },
  45192. 'poleAxis': { value: poleAxis }
  45193. },
  45194. vertexShader: _getCommonVertexShader(),
  45195. fragmentShader: /* glsl */`
  45196. precision mediump float;
  45197. precision mediump int;
  45198. varying vec3 vOutputDirection;
  45199. uniform sampler2D envMap;
  45200. uniform int samples;
  45201. uniform float weights[ n ];
  45202. uniform bool latitudinal;
  45203. uniform float dTheta;
  45204. uniform float mipInt;
  45205. uniform vec3 poleAxis;
  45206. #define ENVMAP_TYPE_CUBE_UV
  45207. #include <cube_uv_reflection_fragment>
  45208. vec3 getSample( float theta, vec3 axis ) {
  45209. float cosTheta = cos( theta );
  45210. // Rodrigues' axis-angle rotation
  45211. vec3 sampleDirection = vOutputDirection * cosTheta
  45212. + cross( axis, vOutputDirection ) * sin( theta )
  45213. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45214. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45215. }
  45216. void main() {
  45217. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45218. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45219. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45220. }
  45221. axis = normalize( axis );
  45222. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45223. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45224. for ( int i = 1; i < n; i++ ) {
  45225. if ( i >= samples ) {
  45226. break;
  45227. }
  45228. float theta = dTheta * float( i );
  45229. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45230. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45231. }
  45232. }
  45233. `,
  45234. blending: NoBlending,
  45235. depthTest: false,
  45236. depthWrite: false
  45237. } );
  45238. return shaderMaterial;
  45239. }
  45240. function _getEquirectMaterial() {
  45241. return new ShaderMaterial( {
  45242. name: 'EquirectangularToCubeUV',
  45243. uniforms: {
  45244. 'envMap': { value: null }
  45245. },
  45246. vertexShader: _getCommonVertexShader(),
  45247. fragmentShader: /* glsl */`
  45248. precision mediump float;
  45249. precision mediump int;
  45250. varying vec3 vOutputDirection;
  45251. uniform sampler2D envMap;
  45252. #include <common>
  45253. void main() {
  45254. vec3 outputDirection = normalize( vOutputDirection );
  45255. vec2 uv = equirectUv( outputDirection );
  45256. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45257. }
  45258. `,
  45259. blending: NoBlending,
  45260. depthTest: false,
  45261. depthWrite: false
  45262. } );
  45263. }
  45264. function _getCubemapMaterial() {
  45265. return new ShaderMaterial( {
  45266. name: 'CubemapToCubeUV',
  45267. uniforms: {
  45268. 'envMap': { value: null },
  45269. 'flipEnvMap': { value: -1 }
  45270. },
  45271. vertexShader: _getCommonVertexShader(),
  45272. fragmentShader: /* glsl */`
  45273. precision mediump float;
  45274. precision mediump int;
  45275. uniform float flipEnvMap;
  45276. varying vec3 vOutputDirection;
  45277. uniform samplerCube envMap;
  45278. void main() {
  45279. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45280. }
  45281. `,
  45282. blending: NoBlending,
  45283. depthTest: false,
  45284. depthWrite: false
  45285. } );
  45286. }
  45287. function _getCommonVertexShader() {
  45288. return /* glsl */`
  45289. precision mediump float;
  45290. precision mediump int;
  45291. attribute float faceIndex;
  45292. varying vec3 vOutputDirection;
  45293. // RH coordinate system; PMREM face-indexing convention
  45294. vec3 getDirection( vec2 uv, float face ) {
  45295. uv = 2.0 * uv - 1.0;
  45296. vec3 direction = vec3( uv, 1.0 );
  45297. if ( face == 0.0 ) {
  45298. direction = direction.zyx; // ( 1, v, u ) pos x
  45299. } else if ( face == 1.0 ) {
  45300. direction = direction.xzy;
  45301. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45302. } else if ( face == 2.0 ) {
  45303. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45304. } else if ( face == 3.0 ) {
  45305. direction = direction.zyx;
  45306. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45307. } else if ( face == 4.0 ) {
  45308. direction = direction.xzy;
  45309. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45310. } else if ( face == 5.0 ) {
  45311. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45312. }
  45313. return direction;
  45314. }
  45315. void main() {
  45316. vOutputDirection = getDirection( uv, faceIndex );
  45317. gl_Position = vec4( position, 1.0 );
  45318. }
  45319. `;
  45320. }
  45321. function WebGLCubeUVMaps( renderer ) {
  45322. let cubeUVmaps = new WeakMap();
  45323. let pmremGenerator = null;
  45324. function get( texture ) {
  45325. if ( texture && texture.isTexture ) {
  45326. const mapping = texture.mapping;
  45327. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45328. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45329. // equirect/cube map to cubeUV conversion
  45330. if ( isEquirectMap || isCubeMap ) {
  45331. let renderTarget = cubeUVmaps.get( texture );
  45332. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45333. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45334. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45335. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45336. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45337. cubeUVmaps.set( texture, renderTarget );
  45338. return renderTarget.texture;
  45339. } else {
  45340. if ( renderTarget !== undefined ) {
  45341. return renderTarget.texture;
  45342. } else {
  45343. const image = texture.image;
  45344. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45345. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45346. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45347. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45348. cubeUVmaps.set( texture, renderTarget );
  45349. texture.addEventListener( 'dispose', onTextureDispose );
  45350. return renderTarget.texture;
  45351. } else {
  45352. // image not yet ready. try the conversion next frame
  45353. return null;
  45354. }
  45355. }
  45356. }
  45357. }
  45358. }
  45359. return texture;
  45360. }
  45361. function isCubeTextureComplete( image ) {
  45362. let count = 0;
  45363. const length = 6;
  45364. for ( let i = 0; i < length; i ++ ) {
  45365. if ( image[ i ] !== undefined ) count ++;
  45366. }
  45367. return count === length;
  45368. }
  45369. function onTextureDispose( event ) {
  45370. const texture = event.target;
  45371. texture.removeEventListener( 'dispose', onTextureDispose );
  45372. const cubemapUV = cubeUVmaps.get( texture );
  45373. if ( cubemapUV !== undefined ) {
  45374. cubeUVmaps.delete( texture );
  45375. cubemapUV.dispose();
  45376. }
  45377. }
  45378. function dispose() {
  45379. cubeUVmaps = new WeakMap();
  45380. if ( pmremGenerator !== null ) {
  45381. pmremGenerator.dispose();
  45382. pmremGenerator = null;
  45383. }
  45384. }
  45385. return {
  45386. get: get,
  45387. dispose: dispose
  45388. };
  45389. }
  45390. function WebGLExtensions( gl ) {
  45391. const extensions = {};
  45392. function getExtension( name ) {
  45393. if ( extensions[ name ] !== undefined ) {
  45394. return extensions[ name ];
  45395. }
  45396. const extension = gl.getExtension( name );
  45397. extensions[ name ] = extension;
  45398. return extension;
  45399. }
  45400. return {
  45401. has: function ( name ) {
  45402. return getExtension( name ) !== null;
  45403. },
  45404. init: function () {
  45405. getExtension( 'EXT_color_buffer_float' );
  45406. getExtension( 'WEBGL_clip_cull_distance' );
  45407. getExtension( 'OES_texture_float_linear' );
  45408. getExtension( 'EXT_color_buffer_half_float' );
  45409. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45410. getExtension( 'WEBGL_render_shared_exponent' );
  45411. },
  45412. get: function ( name ) {
  45413. const extension = getExtension( name );
  45414. if ( extension === null ) {
  45415. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45416. }
  45417. return extension;
  45418. }
  45419. };
  45420. }
  45421. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45422. const geometries = {};
  45423. const wireframeAttributes = new WeakMap();
  45424. function onGeometryDispose( event ) {
  45425. const geometry = event.target;
  45426. if ( geometry.index !== null ) {
  45427. attributes.remove( geometry.index );
  45428. }
  45429. for ( const name in geometry.attributes ) {
  45430. attributes.remove( geometry.attributes[ name ] );
  45431. }
  45432. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45433. delete geometries[ geometry.id ];
  45434. const attribute = wireframeAttributes.get( geometry );
  45435. if ( attribute ) {
  45436. attributes.remove( attribute );
  45437. wireframeAttributes.delete( geometry );
  45438. }
  45439. bindingStates.releaseStatesOfGeometry( geometry );
  45440. if ( geometry.isInstancedBufferGeometry === true ) {
  45441. delete geometry._maxInstanceCount;
  45442. }
  45443. //
  45444. info.memory.geometries --;
  45445. }
  45446. function get( object, geometry ) {
  45447. if ( geometries[ geometry.id ] === true ) return geometry;
  45448. geometry.addEventListener( 'dispose', onGeometryDispose );
  45449. geometries[ geometry.id ] = true;
  45450. info.memory.geometries ++;
  45451. return geometry;
  45452. }
  45453. function update( geometry ) {
  45454. const geometryAttributes = geometry.attributes;
  45455. // Updating index buffer in VAO now. See WebGLBindingStates.
  45456. for ( const name in geometryAttributes ) {
  45457. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45458. }
  45459. }
  45460. function updateWireframeAttribute( geometry ) {
  45461. const indices = [];
  45462. const geometryIndex = geometry.index;
  45463. const geometryPosition = geometry.attributes.position;
  45464. let version = 0;
  45465. if ( geometryIndex !== null ) {
  45466. const array = geometryIndex.array;
  45467. version = geometryIndex.version;
  45468. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45469. const a = array[ i + 0 ];
  45470. const b = array[ i + 1 ];
  45471. const c = array[ i + 2 ];
  45472. indices.push( a, b, b, c, c, a );
  45473. }
  45474. } else if ( geometryPosition !== undefined ) {
  45475. const array = geometryPosition.array;
  45476. version = geometryPosition.version;
  45477. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45478. const a = i + 0;
  45479. const b = i + 1;
  45480. const c = i + 2;
  45481. indices.push( a, b, b, c, c, a );
  45482. }
  45483. } else {
  45484. return;
  45485. }
  45486. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45487. attribute.version = version;
  45488. // Updating index buffer in VAO now. See WebGLBindingStates
  45489. //
  45490. const previousAttribute = wireframeAttributes.get( geometry );
  45491. if ( previousAttribute ) attributes.remove( previousAttribute );
  45492. //
  45493. wireframeAttributes.set( geometry, attribute );
  45494. }
  45495. function getWireframeAttribute( geometry ) {
  45496. const currentAttribute = wireframeAttributes.get( geometry );
  45497. if ( currentAttribute ) {
  45498. const geometryIndex = geometry.index;
  45499. if ( geometryIndex !== null ) {
  45500. // if the attribute is obsolete, create a new one
  45501. if ( currentAttribute.version < geometryIndex.version ) {
  45502. updateWireframeAttribute( geometry );
  45503. }
  45504. }
  45505. } else {
  45506. updateWireframeAttribute( geometry );
  45507. }
  45508. return wireframeAttributes.get( geometry );
  45509. }
  45510. return {
  45511. get: get,
  45512. update: update,
  45513. getWireframeAttribute: getWireframeAttribute
  45514. };
  45515. }
  45516. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45517. let mode;
  45518. function setMode( value ) {
  45519. mode = value;
  45520. }
  45521. let type, bytesPerElement;
  45522. function setIndex( value ) {
  45523. type = value.type;
  45524. bytesPerElement = value.bytesPerElement;
  45525. }
  45526. function render( start, count ) {
  45527. gl.drawElements( mode, count, type, start * bytesPerElement );
  45528. info.update( count, mode, 1 );
  45529. }
  45530. function renderInstances( start, count, primcount ) {
  45531. if ( primcount === 0 ) return;
  45532. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45533. info.update( count, mode, primcount );
  45534. }
  45535. function renderMultiDraw( starts, counts, drawCount ) {
  45536. if ( drawCount === 0 ) return;
  45537. const extension = extensions.get( 'WEBGL_multi_draw' );
  45538. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45539. let elementCount = 0;
  45540. for ( let i = 0; i < drawCount; i ++ ) {
  45541. elementCount += counts[ i ];
  45542. }
  45543. info.update( elementCount, mode, 1 );
  45544. }
  45545. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45546. if ( drawCount === 0 ) return;
  45547. const extension = extensions.get( 'WEBGL_multi_draw' );
  45548. if ( extension === null ) {
  45549. for ( let i = 0; i < starts.length; i ++ ) {
  45550. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45551. }
  45552. } else {
  45553. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45554. let elementCount = 0;
  45555. for ( let i = 0; i < drawCount; i ++ ) {
  45556. elementCount += counts[ i ] * primcount[ i ];
  45557. }
  45558. info.update( elementCount, mode, 1 );
  45559. }
  45560. }
  45561. //
  45562. this.setMode = setMode;
  45563. this.setIndex = setIndex;
  45564. this.render = render;
  45565. this.renderInstances = renderInstances;
  45566. this.renderMultiDraw = renderMultiDraw;
  45567. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45568. }
  45569. function WebGLInfo( gl ) {
  45570. const memory = {
  45571. geometries: 0,
  45572. textures: 0
  45573. };
  45574. const render = {
  45575. frame: 0,
  45576. calls: 0,
  45577. triangles: 0,
  45578. points: 0,
  45579. lines: 0
  45580. };
  45581. function update( count, mode, instanceCount ) {
  45582. render.calls ++;
  45583. switch ( mode ) {
  45584. case gl.TRIANGLES:
  45585. render.triangles += instanceCount * ( count / 3 );
  45586. break;
  45587. case gl.LINES:
  45588. render.lines += instanceCount * ( count / 2 );
  45589. break;
  45590. case gl.LINE_STRIP:
  45591. render.lines += instanceCount * ( count - 1 );
  45592. break;
  45593. case gl.LINE_LOOP:
  45594. render.lines += instanceCount * count;
  45595. break;
  45596. case gl.POINTS:
  45597. render.points += instanceCount * count;
  45598. break;
  45599. default:
  45600. error( 'WebGLInfo: Unknown draw mode:', mode );
  45601. break;
  45602. }
  45603. }
  45604. function reset() {
  45605. render.calls = 0;
  45606. render.triangles = 0;
  45607. render.points = 0;
  45608. render.lines = 0;
  45609. }
  45610. return {
  45611. memory: memory,
  45612. render: render,
  45613. programs: null,
  45614. autoReset: true,
  45615. reset: reset,
  45616. update: update
  45617. };
  45618. }
  45619. function WebGLMorphtargets( gl, capabilities, textures ) {
  45620. const morphTextures = new WeakMap();
  45621. const morph = new Vector4();
  45622. function update( object, geometry, program ) {
  45623. const objectInfluences = object.morphTargetInfluences;
  45624. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45625. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45626. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45627. let entry = morphTextures.get( geometry );
  45628. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45629. if ( entry !== undefined ) entry.texture.dispose();
  45630. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45631. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45632. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45633. const morphTargets = geometry.morphAttributes.position || [];
  45634. const morphNormals = geometry.morphAttributes.normal || [];
  45635. const morphColors = geometry.morphAttributes.color || [];
  45636. let vertexDataCount = 0;
  45637. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45638. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45639. if ( hasMorphColors === true ) vertexDataCount = 3;
  45640. let width = geometry.attributes.position.count * vertexDataCount;
  45641. let height = 1;
  45642. if ( width > capabilities.maxTextureSize ) {
  45643. height = Math.ceil( width / capabilities.maxTextureSize );
  45644. width = capabilities.maxTextureSize;
  45645. }
  45646. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45647. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45648. texture.type = FloatType;
  45649. texture.needsUpdate = true;
  45650. // fill buffer
  45651. const vertexDataStride = vertexDataCount * 4;
  45652. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45653. const morphTarget = morphTargets[ i ];
  45654. const morphNormal = morphNormals[ i ];
  45655. const morphColor = morphColors[ i ];
  45656. const offset = width * height * 4 * i;
  45657. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45658. const stride = j * vertexDataStride;
  45659. if ( hasMorphPosition === true ) {
  45660. morph.fromBufferAttribute( morphTarget, j );
  45661. buffer[ offset + stride + 0 ] = morph.x;
  45662. buffer[ offset + stride + 1 ] = morph.y;
  45663. buffer[ offset + stride + 2 ] = morph.z;
  45664. buffer[ offset + stride + 3 ] = 0;
  45665. }
  45666. if ( hasMorphNormals === true ) {
  45667. morph.fromBufferAttribute( morphNormal, j );
  45668. buffer[ offset + stride + 4 ] = morph.x;
  45669. buffer[ offset + stride + 5 ] = morph.y;
  45670. buffer[ offset + stride + 6 ] = morph.z;
  45671. buffer[ offset + stride + 7 ] = 0;
  45672. }
  45673. if ( hasMorphColors === true ) {
  45674. morph.fromBufferAttribute( morphColor, j );
  45675. buffer[ offset + stride + 8 ] = morph.x;
  45676. buffer[ offset + stride + 9 ] = morph.y;
  45677. buffer[ offset + stride + 10 ] = morph.z;
  45678. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45679. }
  45680. }
  45681. }
  45682. entry = {
  45683. count: morphTargetsCount,
  45684. texture: texture,
  45685. size: new Vector2( width, height )
  45686. };
  45687. morphTextures.set( geometry, entry );
  45688. function disposeTexture() {
  45689. texture.dispose();
  45690. morphTextures.delete( geometry );
  45691. geometry.removeEventListener( 'dispose', disposeTexture );
  45692. }
  45693. geometry.addEventListener( 'dispose', disposeTexture );
  45694. }
  45695. //
  45696. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45697. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45698. } else {
  45699. let morphInfluencesSum = 0;
  45700. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45701. morphInfluencesSum += objectInfluences[ i ];
  45702. }
  45703. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45704. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45705. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45706. }
  45707. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45708. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45709. }
  45710. return {
  45711. update: update
  45712. };
  45713. }
  45714. function WebGLObjects( gl, geometries, attributes, bindingStates, info ) {
  45715. let updateMap = new WeakMap();
  45716. function update( object ) {
  45717. const frame = info.render.frame;
  45718. const geometry = object.geometry;
  45719. const buffergeometry = geometries.get( object, geometry );
  45720. // Update once per frame
  45721. if ( updateMap.get( buffergeometry ) !== frame ) {
  45722. geometries.update( buffergeometry );
  45723. updateMap.set( buffergeometry, frame );
  45724. }
  45725. if ( object.isInstancedMesh ) {
  45726. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45727. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45728. }
  45729. if ( updateMap.get( object ) !== frame ) {
  45730. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45731. if ( object.instanceColor !== null ) {
  45732. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45733. }
  45734. updateMap.set( object, frame );
  45735. }
  45736. }
  45737. if ( object.isSkinnedMesh ) {
  45738. const skeleton = object.skeleton;
  45739. if ( updateMap.get( skeleton ) !== frame ) {
  45740. skeleton.update();
  45741. updateMap.set( skeleton, frame );
  45742. }
  45743. }
  45744. return buffergeometry;
  45745. }
  45746. function dispose() {
  45747. updateMap = new WeakMap();
  45748. }
  45749. function onInstancedMeshDispose( event ) {
  45750. const instancedMesh = event.target;
  45751. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45752. bindingStates.releaseStatesOfObject( instancedMesh );
  45753. attributes.remove( instancedMesh.instanceMatrix );
  45754. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45755. }
  45756. return {
  45757. update: update,
  45758. dispose: dispose
  45759. };
  45760. }
  45761. const toneMappingMap = {
  45762. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  45763. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  45764. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  45765. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  45766. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  45767. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  45768. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  45769. };
  45770. function WebGLOutput( type, width, height, depth, stencil ) {
  45771. // render targets for scene and post-processing
  45772. const targetA = new WebGLRenderTarget( width, height, {
  45773. type: type,
  45774. depthBuffer: depth,
  45775. stencilBuffer: stencil
  45776. } );
  45777. const targetB = new WebGLRenderTarget( width, height, {
  45778. type: HalfFloatType,
  45779. depthBuffer: false,
  45780. stencilBuffer: false
  45781. } );
  45782. // create fullscreen triangle geometry
  45783. const geometry = new BufferGeometry();
  45784. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  45785. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  45786. // create output material with tone mapping support
  45787. const material = new RawShaderMaterial( {
  45788. uniforms: {
  45789. tDiffuse: { value: null }
  45790. },
  45791. vertexShader: /* glsl */`
  45792. precision highp float;
  45793. uniform mat4 modelViewMatrix;
  45794. uniform mat4 projectionMatrix;
  45795. attribute vec3 position;
  45796. attribute vec2 uv;
  45797. varying vec2 vUv;
  45798. void main() {
  45799. vUv = uv;
  45800. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  45801. }`,
  45802. fragmentShader: /* glsl */`
  45803. precision highp float;
  45804. uniform sampler2D tDiffuse;
  45805. varying vec2 vUv;
  45806. #include <tonemapping_pars_fragment>
  45807. #include <colorspace_pars_fragment>
  45808. void main() {
  45809. gl_FragColor = texture2D( tDiffuse, vUv );
  45810. #ifdef LINEAR_TONE_MAPPING
  45811. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  45812. #elif defined( REINHARD_TONE_MAPPING )
  45813. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  45814. #elif defined( CINEON_TONE_MAPPING )
  45815. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  45816. #elif defined( ACES_FILMIC_TONE_MAPPING )
  45817. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  45818. #elif defined( AGX_TONE_MAPPING )
  45819. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  45820. #elif defined( NEUTRAL_TONE_MAPPING )
  45821. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  45822. #elif defined( CUSTOM_TONE_MAPPING )
  45823. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  45824. #endif
  45825. #ifdef SRGB_TRANSFER
  45826. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  45827. #endif
  45828. }`,
  45829. depthTest: false,
  45830. depthWrite: false
  45831. } );
  45832. const mesh = new Mesh( geometry, material );
  45833. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  45834. let _outputColorSpace = null;
  45835. let _outputToneMapping = null;
  45836. let _isCompositing = false;
  45837. let _savedToneMapping;
  45838. let _savedRenderTarget = null;
  45839. let _effects = [];
  45840. let _hasRenderPass = false;
  45841. this.setSize = function ( width, height ) {
  45842. targetA.setSize( width, height );
  45843. targetB.setSize( width, height );
  45844. for ( let i = 0; i < _effects.length; i ++ ) {
  45845. const effect = _effects[ i ];
  45846. if ( effect.setSize ) effect.setSize( width, height );
  45847. }
  45848. };
  45849. this.setEffects = function ( effects ) {
  45850. _effects = effects;
  45851. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  45852. const width = targetA.width;
  45853. const height = targetA.height;
  45854. for ( let i = 0; i < _effects.length; i ++ ) {
  45855. const effect = _effects[ i ];
  45856. if ( effect.setSize ) effect.setSize( width, height );
  45857. }
  45858. };
  45859. this.begin = function ( renderer, renderTarget ) {
  45860. // Don't begin during compositing phase (post-processing effects call render())
  45861. if ( _isCompositing ) return false;
  45862. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  45863. _savedRenderTarget = renderTarget;
  45864. // resize internal buffers to match render target (e.g. XR resolution)
  45865. if ( renderTarget !== null ) {
  45866. const width = renderTarget.width;
  45867. const height = renderTarget.height;
  45868. if ( targetA.width !== width || targetA.height !== height ) {
  45869. this.setSize( width, height );
  45870. }
  45871. }
  45872. // if first effect is a RenderPass, it will set its own render target
  45873. if ( _hasRenderPass === false ) {
  45874. renderer.setRenderTarget( targetA );
  45875. }
  45876. // disable tone mapping during render - it will be applied in end()
  45877. _savedToneMapping = renderer.toneMapping;
  45878. renderer.toneMapping = NoToneMapping;
  45879. return true;
  45880. };
  45881. this.hasRenderPass = function () {
  45882. return _hasRenderPass;
  45883. };
  45884. this.end = function ( renderer, deltaTime ) {
  45885. // restore tone mapping
  45886. renderer.toneMapping = _savedToneMapping;
  45887. _isCompositing = true;
  45888. // run post-processing effects
  45889. let readBuffer = targetA;
  45890. let writeBuffer = targetB;
  45891. for ( let i = 0; i < _effects.length; i ++ ) {
  45892. const effect = _effects[ i ];
  45893. if ( effect.enabled === false ) continue;
  45894. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  45895. if ( effect.needsSwap !== false ) {
  45896. const temp = readBuffer;
  45897. readBuffer = writeBuffer;
  45898. writeBuffer = temp;
  45899. }
  45900. }
  45901. // update output material defines if settings changed
  45902. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  45903. _outputColorSpace = renderer.outputColorSpace;
  45904. _outputToneMapping = renderer.toneMapping;
  45905. material.defines = {};
  45906. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  45907. const toneMapping = toneMappingMap[ _outputToneMapping ];
  45908. if ( toneMapping ) material.defines[ toneMapping ] = '';
  45909. material.needsUpdate = true;
  45910. }
  45911. // final output to canvas (or XR render target)
  45912. material.uniforms.tDiffuse.value = readBuffer.texture;
  45913. renderer.setRenderTarget( _savedRenderTarget );
  45914. renderer.render( mesh, camera );
  45915. _savedRenderTarget = null;
  45916. _isCompositing = false;
  45917. };
  45918. this.isCompositing = function () {
  45919. return _isCompositing;
  45920. };
  45921. this.dispose = function () {
  45922. targetA.dispose();
  45923. targetB.dispose();
  45924. geometry.dispose();
  45925. material.dispose();
  45926. };
  45927. }
  45928. /**
  45929. * Uniforms of a program.
  45930. * Those form a tree structure with a special top-level container for the root,
  45931. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45932. *
  45933. *
  45934. * Properties of inner nodes including the top-level container:
  45935. *
  45936. * .seq - array of nested uniforms
  45937. * .map - nested uniforms by name
  45938. *
  45939. *
  45940. * Methods of all nodes except the top-level container:
  45941. *
  45942. * .setValue( gl, value, [textures] )
  45943. *
  45944. * uploads a uniform value(s)
  45945. * the 'textures' parameter is needed for sampler uniforms
  45946. *
  45947. *
  45948. * Static methods of the top-level container (textures factorizations):
  45949. *
  45950. * .upload( gl, seq, values, textures )
  45951. *
  45952. * sets uniforms in 'seq' to 'values[id].value'
  45953. *
  45954. * .seqWithValue( seq, values ) : filteredSeq
  45955. *
  45956. * filters 'seq' entries with corresponding entry in values
  45957. *
  45958. *
  45959. * Methods of the top-level container (textures factorizations):
  45960. *
  45961. * .setValue( gl, name, value, textures )
  45962. *
  45963. * sets uniform with name 'name' to 'value'
  45964. *
  45965. * .setOptional( gl, obj, prop )
  45966. *
  45967. * like .set for an optional property of the object
  45968. *
  45969. */
  45970. const emptyTexture = /*@__PURE__*/ new Texture();
  45971. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45972. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45973. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45974. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45975. // --- Utilities ---
  45976. // Array Caches (provide typed arrays for temporary by size)
  45977. const arrayCacheF32 = [];
  45978. const arrayCacheI32 = [];
  45979. // Float32Array caches used for uploading Matrix uniforms
  45980. const mat4array = new Float32Array( 16 );
  45981. const mat3array = new Float32Array( 9 );
  45982. const mat2array = new Float32Array( 4 );
  45983. // Flattening for arrays of vectors and matrices
  45984. function flatten( array, nBlocks, blockSize ) {
  45985. const firstElem = array[ 0 ];
  45986. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45987. // unoptimized: ! isNaN( firstElem )
  45988. // see http://jacksondunstan.com/articles/983
  45989. const n = nBlocks * blockSize;
  45990. let r = arrayCacheF32[ n ];
  45991. if ( r === undefined ) {
  45992. r = new Float32Array( n );
  45993. arrayCacheF32[ n ] = r;
  45994. }
  45995. if ( nBlocks !== 0 ) {
  45996. firstElem.toArray( r, 0 );
  45997. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45998. offset += blockSize;
  45999. array[ i ].toArray( r, offset );
  46000. }
  46001. }
  46002. return r;
  46003. }
  46004. function arraysEqual( a, b ) {
  46005. if ( a.length !== b.length ) return false;
  46006. for ( let i = 0, l = a.length; i < l; i ++ ) {
  46007. if ( a[ i ] !== b[ i ] ) return false;
  46008. }
  46009. return true;
  46010. }
  46011. function copyArray( a, b ) {
  46012. for ( let i = 0, l = b.length; i < l; i ++ ) {
  46013. a[ i ] = b[ i ];
  46014. }
  46015. }
  46016. // Texture unit allocation
  46017. function allocTexUnits( textures, n ) {
  46018. let r = arrayCacheI32[ n ];
  46019. if ( r === undefined ) {
  46020. r = new Int32Array( n );
  46021. arrayCacheI32[ n ] = r;
  46022. }
  46023. for ( let i = 0; i !== n; ++ i ) {
  46024. r[ i ] = textures.allocateTextureUnit();
  46025. }
  46026. return r;
  46027. }
  46028. // --- Setters ---
  46029. // Note: Defining these methods externally, because they come in a bunch
  46030. // and this way their names minify.
  46031. // Single scalar
  46032. function setValueV1f( gl, v ) {
  46033. const cache = this.cache;
  46034. if ( cache[ 0 ] === v ) return;
  46035. gl.uniform1f( this.addr, v );
  46036. cache[ 0 ] = v;
  46037. }
  46038. // Single float vector (from flat array or THREE.VectorN)
  46039. function setValueV2f( gl, v ) {
  46040. const cache = this.cache;
  46041. if ( v.x !== undefined ) {
  46042. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46043. gl.uniform2f( this.addr, v.x, v.y );
  46044. cache[ 0 ] = v.x;
  46045. cache[ 1 ] = v.y;
  46046. }
  46047. } else {
  46048. if ( arraysEqual( cache, v ) ) return;
  46049. gl.uniform2fv( this.addr, v );
  46050. copyArray( cache, v );
  46051. }
  46052. }
  46053. function setValueV3f( gl, v ) {
  46054. const cache = this.cache;
  46055. if ( v.x !== undefined ) {
  46056. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46057. gl.uniform3f( this.addr, v.x, v.y, v.z );
  46058. cache[ 0 ] = v.x;
  46059. cache[ 1 ] = v.y;
  46060. cache[ 2 ] = v.z;
  46061. }
  46062. } else if ( v.r !== undefined ) {
  46063. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  46064. gl.uniform3f( this.addr, v.r, v.g, v.b );
  46065. cache[ 0 ] = v.r;
  46066. cache[ 1 ] = v.g;
  46067. cache[ 2 ] = v.b;
  46068. }
  46069. } else {
  46070. if ( arraysEqual( cache, v ) ) return;
  46071. gl.uniform3fv( this.addr, v );
  46072. copyArray( cache, v );
  46073. }
  46074. }
  46075. function setValueV4f( gl, v ) {
  46076. const cache = this.cache;
  46077. if ( v.x !== undefined ) {
  46078. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46079. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  46080. cache[ 0 ] = v.x;
  46081. cache[ 1 ] = v.y;
  46082. cache[ 2 ] = v.z;
  46083. cache[ 3 ] = v.w;
  46084. }
  46085. } else {
  46086. if ( arraysEqual( cache, v ) ) return;
  46087. gl.uniform4fv( this.addr, v );
  46088. copyArray( cache, v );
  46089. }
  46090. }
  46091. // Single matrix (from flat array or THREE.MatrixN)
  46092. function setValueM2( gl, v ) {
  46093. const cache = this.cache;
  46094. const elements = v.elements;
  46095. if ( elements === undefined ) {
  46096. if ( arraysEqual( cache, v ) ) return;
  46097. gl.uniformMatrix2fv( this.addr, false, v );
  46098. copyArray( cache, v );
  46099. } else {
  46100. if ( arraysEqual( cache, elements ) ) return;
  46101. mat2array.set( elements );
  46102. gl.uniformMatrix2fv( this.addr, false, mat2array );
  46103. copyArray( cache, elements );
  46104. }
  46105. }
  46106. function setValueM3( gl, v ) {
  46107. const cache = this.cache;
  46108. const elements = v.elements;
  46109. if ( elements === undefined ) {
  46110. if ( arraysEqual( cache, v ) ) return;
  46111. gl.uniformMatrix3fv( this.addr, false, v );
  46112. copyArray( cache, v );
  46113. } else {
  46114. if ( arraysEqual( cache, elements ) ) return;
  46115. mat3array.set( elements );
  46116. gl.uniformMatrix3fv( this.addr, false, mat3array );
  46117. copyArray( cache, elements );
  46118. }
  46119. }
  46120. function setValueM4( gl, v ) {
  46121. const cache = this.cache;
  46122. const elements = v.elements;
  46123. if ( elements === undefined ) {
  46124. if ( arraysEqual( cache, v ) ) return;
  46125. gl.uniformMatrix4fv( this.addr, false, v );
  46126. copyArray( cache, v );
  46127. } else {
  46128. if ( arraysEqual( cache, elements ) ) return;
  46129. mat4array.set( elements );
  46130. gl.uniformMatrix4fv( this.addr, false, mat4array );
  46131. copyArray( cache, elements );
  46132. }
  46133. }
  46134. // Single integer / boolean
  46135. function setValueV1i( gl, v ) {
  46136. const cache = this.cache;
  46137. if ( cache[ 0 ] === v ) return;
  46138. gl.uniform1i( this.addr, v );
  46139. cache[ 0 ] = v;
  46140. }
  46141. // Single integer / boolean vector (from flat array or THREE.VectorN)
  46142. function setValueV2i( gl, v ) {
  46143. const cache = this.cache;
  46144. if ( v.x !== undefined ) {
  46145. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46146. gl.uniform2i( this.addr, v.x, v.y );
  46147. cache[ 0 ] = v.x;
  46148. cache[ 1 ] = v.y;
  46149. }
  46150. } else {
  46151. if ( arraysEqual( cache, v ) ) return;
  46152. gl.uniform2iv( this.addr, v );
  46153. copyArray( cache, v );
  46154. }
  46155. }
  46156. function setValueV3i( gl, v ) {
  46157. const cache = this.cache;
  46158. if ( v.x !== undefined ) {
  46159. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46160. gl.uniform3i( this.addr, v.x, v.y, v.z );
  46161. cache[ 0 ] = v.x;
  46162. cache[ 1 ] = v.y;
  46163. cache[ 2 ] = v.z;
  46164. }
  46165. } else {
  46166. if ( arraysEqual( cache, v ) ) return;
  46167. gl.uniform3iv( this.addr, v );
  46168. copyArray( cache, v );
  46169. }
  46170. }
  46171. function setValueV4i( gl, v ) {
  46172. const cache = this.cache;
  46173. if ( v.x !== undefined ) {
  46174. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46175. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  46176. cache[ 0 ] = v.x;
  46177. cache[ 1 ] = v.y;
  46178. cache[ 2 ] = v.z;
  46179. cache[ 3 ] = v.w;
  46180. }
  46181. } else {
  46182. if ( arraysEqual( cache, v ) ) return;
  46183. gl.uniform4iv( this.addr, v );
  46184. copyArray( cache, v );
  46185. }
  46186. }
  46187. // Single unsigned integer
  46188. function setValueV1ui( gl, v ) {
  46189. const cache = this.cache;
  46190. if ( cache[ 0 ] === v ) return;
  46191. gl.uniform1ui( this.addr, v );
  46192. cache[ 0 ] = v;
  46193. }
  46194. // Single unsigned integer vector (from flat array or THREE.VectorN)
  46195. function setValueV2ui( gl, v ) {
  46196. const cache = this.cache;
  46197. if ( v.x !== undefined ) {
  46198. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46199. gl.uniform2ui( this.addr, v.x, v.y );
  46200. cache[ 0 ] = v.x;
  46201. cache[ 1 ] = v.y;
  46202. }
  46203. } else {
  46204. if ( arraysEqual( cache, v ) ) return;
  46205. gl.uniform2uiv( this.addr, v );
  46206. copyArray( cache, v );
  46207. }
  46208. }
  46209. function setValueV3ui( gl, v ) {
  46210. const cache = this.cache;
  46211. if ( v.x !== undefined ) {
  46212. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46213. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  46214. cache[ 0 ] = v.x;
  46215. cache[ 1 ] = v.y;
  46216. cache[ 2 ] = v.z;
  46217. }
  46218. } else {
  46219. if ( arraysEqual( cache, v ) ) return;
  46220. gl.uniform3uiv( this.addr, v );
  46221. copyArray( cache, v );
  46222. }
  46223. }
  46224. function setValueV4ui( gl, v ) {
  46225. const cache = this.cache;
  46226. if ( v.x !== undefined ) {
  46227. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46228. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  46229. cache[ 0 ] = v.x;
  46230. cache[ 1 ] = v.y;
  46231. cache[ 2 ] = v.z;
  46232. cache[ 3 ] = v.w;
  46233. }
  46234. } else {
  46235. if ( arraysEqual( cache, v ) ) return;
  46236. gl.uniform4uiv( this.addr, v );
  46237. copyArray( cache, v );
  46238. }
  46239. }
  46240. // Single texture (2D / Cube)
  46241. function setValueT1( gl, v, textures ) {
  46242. const cache = this.cache;
  46243. const unit = textures.allocateTextureUnit();
  46244. if ( cache[ 0 ] !== unit ) {
  46245. gl.uniform1i( this.addr, unit );
  46246. cache[ 0 ] = unit;
  46247. }
  46248. let emptyTexture2D;
  46249. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46250. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  46251. emptyTexture2D = emptyShadowTexture;
  46252. } else {
  46253. emptyTexture2D = emptyTexture;
  46254. }
  46255. textures.setTexture2D( v || emptyTexture2D, unit );
  46256. }
  46257. function setValueT3D1( gl, v, textures ) {
  46258. const cache = this.cache;
  46259. const unit = textures.allocateTextureUnit();
  46260. if ( cache[ 0 ] !== unit ) {
  46261. gl.uniform1i( this.addr, unit );
  46262. cache[ 0 ] = unit;
  46263. }
  46264. textures.setTexture3D( v || empty3dTexture, unit );
  46265. }
  46266. function setValueT6( gl, v, textures ) {
  46267. const cache = this.cache;
  46268. const unit = textures.allocateTextureUnit();
  46269. if ( cache[ 0 ] !== unit ) {
  46270. gl.uniform1i( this.addr, unit );
  46271. cache[ 0 ] = unit;
  46272. }
  46273. textures.setTextureCube( v || emptyCubeTexture, unit );
  46274. }
  46275. function setValueT2DArray1( gl, v, textures ) {
  46276. const cache = this.cache;
  46277. const unit = textures.allocateTextureUnit();
  46278. if ( cache[ 0 ] !== unit ) {
  46279. gl.uniform1i( this.addr, unit );
  46280. cache[ 0 ] = unit;
  46281. }
  46282. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46283. }
  46284. // Helper to pick the right setter for the singular case
  46285. function getSingularSetter( type ) {
  46286. switch ( type ) {
  46287. case 0x1406: return setValueV1f; // FLOAT
  46288. case 0x8b50: return setValueV2f; // _VEC2
  46289. case 0x8b51: return setValueV3f; // _VEC3
  46290. case 0x8b52: return setValueV4f; // _VEC4
  46291. case 0x8b5a: return setValueM2; // _MAT2
  46292. case 0x8b5b: return setValueM3; // _MAT3
  46293. case 0x8b5c: return setValueM4; // _MAT4
  46294. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46295. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46296. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46297. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46298. case 0x1405: return setValueV1ui; // UINT
  46299. case 0x8dc6: return setValueV2ui; // _VEC2
  46300. case 0x8dc7: return setValueV3ui; // _VEC3
  46301. case 0x8dc8: return setValueV4ui; // _VEC4
  46302. case 0x8b5e: // SAMPLER_2D
  46303. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46304. case 0x8dca: // INT_SAMPLER_2D
  46305. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46306. case 0x8b62: // SAMPLER_2D_SHADOW
  46307. return setValueT1;
  46308. case 0x8b5f: // SAMPLER_3D
  46309. case 0x8dcb: // INT_SAMPLER_3D
  46310. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46311. return setValueT3D1;
  46312. case 0x8b60: // SAMPLER_CUBE
  46313. case 0x8dcc: // INT_SAMPLER_CUBE
  46314. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46315. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46316. return setValueT6;
  46317. case 0x8dc1: // SAMPLER_2D_ARRAY
  46318. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46319. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46320. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46321. return setValueT2DArray1;
  46322. }
  46323. }
  46324. // Array of scalars
  46325. function setValueV1fArray( gl, v ) {
  46326. gl.uniform1fv( this.addr, v );
  46327. }
  46328. // Array of vectors (from flat array or array of THREE.VectorN)
  46329. function setValueV2fArray( gl, v ) {
  46330. const data = flatten( v, this.size, 2 );
  46331. gl.uniform2fv( this.addr, data );
  46332. }
  46333. function setValueV3fArray( gl, v ) {
  46334. const data = flatten( v, this.size, 3 );
  46335. gl.uniform3fv( this.addr, data );
  46336. }
  46337. function setValueV4fArray( gl, v ) {
  46338. const data = flatten( v, this.size, 4 );
  46339. gl.uniform4fv( this.addr, data );
  46340. }
  46341. // Array of matrices (from flat array or array of THREE.MatrixN)
  46342. function setValueM2Array( gl, v ) {
  46343. const data = flatten( v, this.size, 4 );
  46344. gl.uniformMatrix2fv( this.addr, false, data );
  46345. }
  46346. function setValueM3Array( gl, v ) {
  46347. const data = flatten( v, this.size, 9 );
  46348. gl.uniformMatrix3fv( this.addr, false, data );
  46349. }
  46350. function setValueM4Array( gl, v ) {
  46351. const data = flatten( v, this.size, 16 );
  46352. gl.uniformMatrix4fv( this.addr, false, data );
  46353. }
  46354. // Array of integer / boolean
  46355. function setValueV1iArray( gl, v ) {
  46356. gl.uniform1iv( this.addr, v );
  46357. }
  46358. // Array of integer / boolean vectors (from flat array)
  46359. function setValueV2iArray( gl, v ) {
  46360. gl.uniform2iv( this.addr, v );
  46361. }
  46362. function setValueV3iArray( gl, v ) {
  46363. gl.uniform3iv( this.addr, v );
  46364. }
  46365. function setValueV4iArray( gl, v ) {
  46366. gl.uniform4iv( this.addr, v );
  46367. }
  46368. // Array of unsigned integer
  46369. function setValueV1uiArray( gl, v ) {
  46370. gl.uniform1uiv( this.addr, v );
  46371. }
  46372. // Array of unsigned integer vectors (from flat array)
  46373. function setValueV2uiArray( gl, v ) {
  46374. gl.uniform2uiv( this.addr, v );
  46375. }
  46376. function setValueV3uiArray( gl, v ) {
  46377. gl.uniform3uiv( this.addr, v );
  46378. }
  46379. function setValueV4uiArray( gl, v ) {
  46380. gl.uniform4uiv( this.addr, v );
  46381. }
  46382. // Array of textures (2D / 3D / Cube / 2DArray)
  46383. function setValueT1Array( gl, v, textures ) {
  46384. const cache = this.cache;
  46385. const n = v.length;
  46386. const units = allocTexUnits( textures, n );
  46387. if ( ! arraysEqual( cache, units ) ) {
  46388. gl.uniform1iv( this.addr, units );
  46389. copyArray( cache, units );
  46390. }
  46391. let emptyTexture2D;
  46392. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46393. emptyTexture2D = emptyShadowTexture;
  46394. } else {
  46395. emptyTexture2D = emptyTexture;
  46396. }
  46397. for ( let i = 0; i !== n; ++ i ) {
  46398. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46399. }
  46400. }
  46401. function setValueT3DArray( gl, v, textures ) {
  46402. const cache = this.cache;
  46403. const n = v.length;
  46404. const units = allocTexUnits( textures, n );
  46405. if ( ! arraysEqual( cache, units ) ) {
  46406. gl.uniform1iv( this.addr, units );
  46407. copyArray( cache, units );
  46408. }
  46409. for ( let i = 0; i !== n; ++ i ) {
  46410. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46411. }
  46412. }
  46413. function setValueT6Array( gl, v, textures ) {
  46414. const cache = this.cache;
  46415. const n = v.length;
  46416. const units = allocTexUnits( textures, n );
  46417. if ( ! arraysEqual( cache, units ) ) {
  46418. gl.uniform1iv( this.addr, units );
  46419. copyArray( cache, units );
  46420. }
  46421. for ( let i = 0; i !== n; ++ i ) {
  46422. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46423. }
  46424. }
  46425. function setValueT2DArrayArray( gl, v, textures ) {
  46426. const cache = this.cache;
  46427. const n = v.length;
  46428. const units = allocTexUnits( textures, n );
  46429. if ( ! arraysEqual( cache, units ) ) {
  46430. gl.uniform1iv( this.addr, units );
  46431. copyArray( cache, units );
  46432. }
  46433. for ( let i = 0; i !== n; ++ i ) {
  46434. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46435. }
  46436. }
  46437. // Helper to pick the right setter for a pure (bottom-level) array
  46438. function getPureArraySetter( type ) {
  46439. switch ( type ) {
  46440. case 0x1406: return setValueV1fArray; // FLOAT
  46441. case 0x8b50: return setValueV2fArray; // _VEC2
  46442. case 0x8b51: return setValueV3fArray; // _VEC3
  46443. case 0x8b52: return setValueV4fArray; // _VEC4
  46444. case 0x8b5a: return setValueM2Array; // _MAT2
  46445. case 0x8b5b: return setValueM3Array; // _MAT3
  46446. case 0x8b5c: return setValueM4Array; // _MAT4
  46447. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46448. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46449. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46450. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46451. case 0x1405: return setValueV1uiArray; // UINT
  46452. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46453. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46454. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46455. case 0x8b5e: // SAMPLER_2D
  46456. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46457. case 0x8dca: // INT_SAMPLER_2D
  46458. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46459. case 0x8b62: // SAMPLER_2D_SHADOW
  46460. return setValueT1Array;
  46461. case 0x8b5f: // SAMPLER_3D
  46462. case 0x8dcb: // INT_SAMPLER_3D
  46463. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46464. return setValueT3DArray;
  46465. case 0x8b60: // SAMPLER_CUBE
  46466. case 0x8dcc: // INT_SAMPLER_CUBE
  46467. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46468. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46469. return setValueT6Array;
  46470. case 0x8dc1: // SAMPLER_2D_ARRAY
  46471. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46472. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46473. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46474. return setValueT2DArrayArray;
  46475. }
  46476. }
  46477. // --- Uniform Classes ---
  46478. class SingleUniform {
  46479. constructor( id, activeInfo, addr ) {
  46480. this.id = id;
  46481. this.addr = addr;
  46482. this.cache = [];
  46483. this.type = activeInfo.type;
  46484. this.setValue = getSingularSetter( activeInfo.type );
  46485. // this.path = activeInfo.name; // DEBUG
  46486. }
  46487. }
  46488. class PureArrayUniform {
  46489. constructor( id, activeInfo, addr ) {
  46490. this.id = id;
  46491. this.addr = addr;
  46492. this.cache = [];
  46493. this.type = activeInfo.type;
  46494. this.size = activeInfo.size;
  46495. this.setValue = getPureArraySetter( activeInfo.type );
  46496. // this.path = activeInfo.name; // DEBUG
  46497. }
  46498. }
  46499. class StructuredUniform {
  46500. constructor( id ) {
  46501. this.id = id;
  46502. this.seq = [];
  46503. this.map = {};
  46504. }
  46505. setValue( gl, value, textures ) {
  46506. const seq = this.seq;
  46507. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46508. const u = seq[ i ];
  46509. u.setValue( gl, value[ u.id ], textures );
  46510. }
  46511. }
  46512. }
  46513. // --- Top-level ---
  46514. // Parser - builds up the property tree from the path strings
  46515. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46516. // extracts
  46517. // - the identifier (member name or array index)
  46518. // - followed by an optional right bracket (found when array index)
  46519. // - followed by an optional left bracket or dot (type of subscript)
  46520. //
  46521. // Note: These portions can be read in a non-overlapping fashion and
  46522. // allow straightforward parsing of the hierarchy that WebGL encodes
  46523. // in the uniform names.
  46524. function addUniform( container, uniformObject ) {
  46525. container.seq.push( uniformObject );
  46526. container.map[ uniformObject.id ] = uniformObject;
  46527. }
  46528. function parseUniform( activeInfo, addr, container ) {
  46529. const path = activeInfo.name,
  46530. pathLength = path.length;
  46531. // reset RegExp object, because of the early exit of a previous run
  46532. RePathPart.lastIndex = 0;
  46533. while ( true ) {
  46534. const match = RePathPart.exec( path ),
  46535. matchEnd = RePathPart.lastIndex;
  46536. let id = match[ 1 ];
  46537. const idIsIndex = match[ 2 ] === ']',
  46538. subscript = match[ 3 ];
  46539. if ( idIsIndex ) id = id | 0; // convert to integer
  46540. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46541. // bare name or "pure" bottom-level array "[0]" suffix
  46542. addUniform( container, subscript === undefined ?
  46543. new SingleUniform( id, activeInfo, addr ) :
  46544. new PureArrayUniform( id, activeInfo, addr ) );
  46545. break;
  46546. } else {
  46547. // step into inner node / create it in case it doesn't exist
  46548. const map = container.map;
  46549. let next = map[ id ];
  46550. if ( next === undefined ) {
  46551. next = new StructuredUniform( id );
  46552. addUniform( container, next );
  46553. }
  46554. container = next;
  46555. }
  46556. }
  46557. }
  46558. // Root Container
  46559. class WebGLUniforms {
  46560. constructor( gl, program ) {
  46561. this.seq = [];
  46562. this.map = {};
  46563. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46564. for ( let i = 0; i < n; ++ i ) {
  46565. const info = gl.getActiveUniform( program, i ),
  46566. addr = gl.getUniformLocation( program, info.name );
  46567. parseUniform( info, addr, this );
  46568. }
  46569. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46570. const shadowSamplers = [];
  46571. const otherUniforms = [];
  46572. for ( const u of this.seq ) {
  46573. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46574. shadowSamplers.push( u );
  46575. } else {
  46576. otherUniforms.push( u );
  46577. }
  46578. }
  46579. if ( shadowSamplers.length > 0 ) {
  46580. this.seq = shadowSamplers.concat( otherUniforms );
  46581. }
  46582. }
  46583. setValue( gl, name, value, textures ) {
  46584. const u = this.map[ name ];
  46585. if ( u !== undefined ) u.setValue( gl, value, textures );
  46586. }
  46587. setOptional( gl, object, name ) {
  46588. const v = object[ name ];
  46589. if ( v !== undefined ) this.setValue( gl, name, v );
  46590. }
  46591. static upload( gl, seq, values, textures ) {
  46592. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46593. const u = seq[ i ],
  46594. v = values[ u.id ];
  46595. if ( v.needsUpdate !== false ) {
  46596. // note: always updating when .needsUpdate is undefined
  46597. u.setValue( gl, v.value, textures );
  46598. }
  46599. }
  46600. }
  46601. static seqWithValue( seq, values ) {
  46602. const r = [];
  46603. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46604. const u = seq[ i ];
  46605. if ( u.id in values ) r.push( u );
  46606. }
  46607. return r;
  46608. }
  46609. }
  46610. function WebGLShader( gl, type, string ) {
  46611. const shader = gl.createShader( type );
  46612. gl.shaderSource( shader, string );
  46613. gl.compileShader( shader );
  46614. return shader;
  46615. }
  46616. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46617. const COMPLETION_STATUS_KHR = 0x91B1;
  46618. let programIdCount = 0;
  46619. function handleSource( string, errorLine ) {
  46620. const lines = string.split( '\n' );
  46621. const lines2 = [];
  46622. const from = Math.max( errorLine - 6, 0 );
  46623. const to = Math.min( errorLine + 6, lines.length );
  46624. for ( let i = from; i < to; i ++ ) {
  46625. const line = i + 1;
  46626. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46627. }
  46628. return lines2.join( '\n' );
  46629. }
  46630. const _m0 = /*@__PURE__*/ new Matrix3();
  46631. function getEncodingComponents( colorSpace ) {
  46632. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46633. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46634. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46635. case LinearTransfer:
  46636. return [ encodingMatrix, 'LinearTransferOETF' ];
  46637. case SRGBTransfer:
  46638. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46639. default:
  46640. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46641. return [ encodingMatrix, 'LinearTransferOETF' ];
  46642. }
  46643. }
  46644. function getShaderErrors( gl, shader, type ) {
  46645. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46646. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46647. const errors = shaderInfoLog.trim();
  46648. if ( status && errors === '' ) return '';
  46649. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46650. if ( errorMatches ) {
  46651. // --enable-privileged-webgl-extension
  46652. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46653. const errorLine = parseInt( errorMatches[ 1 ] );
  46654. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46655. } else {
  46656. return errors;
  46657. }
  46658. }
  46659. function getTexelEncodingFunction( functionName, colorSpace ) {
  46660. const components = getEncodingComponents( colorSpace );
  46661. return [
  46662. `vec4 ${functionName}( vec4 value ) {`,
  46663. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46664. '}',
  46665. ].join( '\n' );
  46666. }
  46667. const toneMappingFunctions = {
  46668. [ LinearToneMapping ]: 'Linear',
  46669. [ ReinhardToneMapping ]: 'Reinhard',
  46670. [ CineonToneMapping ]: 'Cineon',
  46671. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  46672. [ AgXToneMapping ]: 'AgX',
  46673. [ NeutralToneMapping ]: 'Neutral',
  46674. [ CustomToneMapping ]: 'Custom'
  46675. };
  46676. function getToneMappingFunction( functionName, toneMapping ) {
  46677. const toneMappingName = toneMappingFunctions[ toneMapping ];
  46678. if ( toneMappingName === undefined ) {
  46679. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46680. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  46681. }
  46682. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46683. }
  46684. const _v0 = /*@__PURE__*/ new Vector3();
  46685. function getLuminanceFunction() {
  46686. ColorManagement.getLuminanceCoefficients( _v0 );
  46687. const r = _v0.x.toFixed( 4 );
  46688. const g = _v0.y.toFixed( 4 );
  46689. const b = _v0.z.toFixed( 4 );
  46690. return [
  46691. 'float luminance( const in vec3 rgb ) {',
  46692. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46693. ' return dot( weights, rgb );',
  46694. '}'
  46695. ].join( '\n' );
  46696. }
  46697. function generateVertexExtensions( parameters ) {
  46698. const chunks = [
  46699. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46700. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46701. ];
  46702. return chunks.filter( filterEmptyLine ).join( '\n' );
  46703. }
  46704. function generateDefines( defines ) {
  46705. const chunks = [];
  46706. for ( const name in defines ) {
  46707. const value = defines[ name ];
  46708. if ( value === false ) continue;
  46709. chunks.push( '#define ' + name + ' ' + value );
  46710. }
  46711. return chunks.join( '\n' );
  46712. }
  46713. function fetchAttributeLocations( gl, program ) {
  46714. const attributes = {};
  46715. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46716. for ( let i = 0; i < n; i ++ ) {
  46717. const info = gl.getActiveAttrib( program, i );
  46718. const name = info.name;
  46719. let locationSize = 1;
  46720. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46721. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46722. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46723. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46724. attributes[ name ] = {
  46725. type: info.type,
  46726. location: gl.getAttribLocation( program, name ),
  46727. locationSize: locationSize
  46728. };
  46729. }
  46730. return attributes;
  46731. }
  46732. function filterEmptyLine( string ) {
  46733. return string !== '';
  46734. }
  46735. function replaceLightNums( string, parameters ) {
  46736. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46737. return string
  46738. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46739. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46740. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46741. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46742. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46743. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46744. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46745. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46746. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46747. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46748. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46749. }
  46750. function replaceClippingPlaneNums( string, parameters ) {
  46751. return string
  46752. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46753. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46754. }
  46755. // Resolve Includes
  46756. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46757. function resolveIncludes( string ) {
  46758. return string.replace( includePattern, includeReplacer );
  46759. }
  46760. const shaderChunkMap = new Map();
  46761. function includeReplacer( match, include ) {
  46762. let string = ShaderChunk[ include ];
  46763. if ( string === undefined ) {
  46764. const newInclude = shaderChunkMap.get( include );
  46765. if ( newInclude !== undefined ) {
  46766. string = ShaderChunk[ newInclude ];
  46767. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46768. } else {
  46769. throw new Error( 'Can not resolve #include <' + include + '>' );
  46770. }
  46771. }
  46772. return resolveIncludes( string );
  46773. }
  46774. // Unroll Loops
  46775. 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;
  46776. function unrollLoops( string ) {
  46777. return string.replace( unrollLoopPattern, loopReplacer );
  46778. }
  46779. function loopReplacer( match, start, end, snippet ) {
  46780. let string = '';
  46781. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46782. string += snippet
  46783. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46784. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46785. }
  46786. return string;
  46787. }
  46788. //
  46789. function generatePrecision( parameters ) {
  46790. let precisionstring = `precision ${parameters.precision} float;
  46791. precision ${parameters.precision} int;
  46792. precision ${parameters.precision} sampler2D;
  46793. precision ${parameters.precision} samplerCube;
  46794. precision ${parameters.precision} sampler3D;
  46795. precision ${parameters.precision} sampler2DArray;
  46796. precision ${parameters.precision} sampler2DShadow;
  46797. precision ${parameters.precision} samplerCubeShadow;
  46798. precision ${parameters.precision} sampler2DArrayShadow;
  46799. precision ${parameters.precision} isampler2D;
  46800. precision ${parameters.precision} isampler3D;
  46801. precision ${parameters.precision} isamplerCube;
  46802. precision ${parameters.precision} isampler2DArray;
  46803. precision ${parameters.precision} usampler2D;
  46804. precision ${parameters.precision} usampler3D;
  46805. precision ${parameters.precision} usamplerCube;
  46806. precision ${parameters.precision} usampler2DArray;
  46807. `;
  46808. if ( parameters.precision === 'highp' ) {
  46809. precisionstring += '\n#define HIGH_PRECISION';
  46810. } else if ( parameters.precision === 'mediump' ) {
  46811. precisionstring += '\n#define MEDIUM_PRECISION';
  46812. } else if ( parameters.precision === 'lowp' ) {
  46813. precisionstring += '\n#define LOW_PRECISION';
  46814. }
  46815. return precisionstring;
  46816. }
  46817. const shadowMapTypeDefines = {
  46818. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  46819. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  46820. };
  46821. function generateShadowMapTypeDefine( parameters ) {
  46822. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  46823. }
  46824. const envMapTypeDefines = {
  46825. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  46826. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  46827. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  46828. };
  46829. function generateEnvMapTypeDefine( parameters ) {
  46830. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  46831. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  46832. }
  46833. const envMapModeDefines = {
  46834. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  46835. };
  46836. function generateEnvMapModeDefine( parameters ) {
  46837. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  46838. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  46839. }
  46840. const envMapBlendingDefines = {
  46841. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  46842. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  46843. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  46844. };
  46845. function generateEnvMapBlendingDefine( parameters ) {
  46846. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  46847. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  46848. }
  46849. function generateCubeUVSize( parameters ) {
  46850. const imageHeight = parameters.envMapCubeUVHeight;
  46851. if ( imageHeight === null ) return null;
  46852. const maxMip = Math.log2( imageHeight ) - 2;
  46853. const texelHeight = 1.0 / imageHeight;
  46854. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46855. return { texelWidth, texelHeight, maxMip };
  46856. }
  46857. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46858. // TODO Send this event to Three.js DevTools
  46859. // log( 'WebGLProgram', cacheKey );
  46860. const gl = renderer.getContext();
  46861. const defines = parameters.defines;
  46862. let vertexShader = parameters.vertexShader;
  46863. let fragmentShader = parameters.fragmentShader;
  46864. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46865. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46866. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46867. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46868. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46869. const customVertexExtensions = generateVertexExtensions( parameters );
  46870. const customDefines = generateDefines( defines );
  46871. const program = gl.createProgram();
  46872. let prefixVertex, prefixFragment;
  46873. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46874. if ( parameters.isRawShaderMaterial ) {
  46875. prefixVertex = [
  46876. '#define SHADER_TYPE ' + parameters.shaderType,
  46877. '#define SHADER_NAME ' + parameters.shaderName,
  46878. customDefines
  46879. ].filter( filterEmptyLine ).join( '\n' );
  46880. if ( prefixVertex.length > 0 ) {
  46881. prefixVertex += '\n';
  46882. }
  46883. prefixFragment = [
  46884. '#define SHADER_TYPE ' + parameters.shaderType,
  46885. '#define SHADER_NAME ' + parameters.shaderName,
  46886. customDefines
  46887. ].filter( filterEmptyLine ).join( '\n' );
  46888. if ( prefixFragment.length > 0 ) {
  46889. prefixFragment += '\n';
  46890. }
  46891. } else {
  46892. prefixVertex = [
  46893. generatePrecision( parameters ),
  46894. '#define SHADER_TYPE ' + parameters.shaderType,
  46895. '#define SHADER_NAME ' + parameters.shaderName,
  46896. customDefines,
  46897. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46898. parameters.batching ? '#define USE_BATCHING' : '',
  46899. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46900. parameters.instancing ? '#define USE_INSTANCING' : '',
  46901. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46902. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46903. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46904. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46905. parameters.map ? '#define USE_MAP' : '',
  46906. parameters.envMap ? '#define USE_ENVMAP' : '',
  46907. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46908. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46909. parameters.aoMap ? '#define USE_AOMAP' : '',
  46910. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46911. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46912. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46913. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46914. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46915. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46916. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46917. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46918. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46919. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46920. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46921. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46922. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46923. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46924. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46925. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46926. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46927. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46928. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46929. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46930. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46931. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46932. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46933. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46934. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46935. //
  46936. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46937. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46938. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46939. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46940. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46941. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46942. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46943. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46944. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46945. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46946. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46947. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46948. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46949. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46950. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46951. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46952. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46953. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46954. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46955. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46956. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46957. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46958. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46959. //
  46960. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46961. parameters.vertexColors ? '#define USE_COLOR' : '',
  46962. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46963. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46964. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46965. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46966. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46967. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46968. parameters.skinning ? '#define USE_SKINNING' : '',
  46969. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46970. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46971. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46972. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46973. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46974. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46975. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46976. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46977. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46978. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46979. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46980. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46981. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46982. 'uniform mat4 modelMatrix;',
  46983. 'uniform mat4 modelViewMatrix;',
  46984. 'uniform mat4 projectionMatrix;',
  46985. 'uniform mat4 viewMatrix;',
  46986. 'uniform mat3 normalMatrix;',
  46987. 'uniform vec3 cameraPosition;',
  46988. 'uniform bool isOrthographic;',
  46989. '#ifdef USE_INSTANCING',
  46990. ' attribute mat4 instanceMatrix;',
  46991. '#endif',
  46992. '#ifdef USE_INSTANCING_COLOR',
  46993. ' attribute vec3 instanceColor;',
  46994. '#endif',
  46995. '#ifdef USE_INSTANCING_MORPH',
  46996. ' uniform sampler2D morphTexture;',
  46997. '#endif',
  46998. 'attribute vec3 position;',
  46999. 'attribute vec3 normal;',
  47000. 'attribute vec2 uv;',
  47001. '#ifdef USE_UV1',
  47002. ' attribute vec2 uv1;',
  47003. '#endif',
  47004. '#ifdef USE_UV2',
  47005. ' attribute vec2 uv2;',
  47006. '#endif',
  47007. '#ifdef USE_UV3',
  47008. ' attribute vec2 uv3;',
  47009. '#endif',
  47010. '#ifdef USE_TANGENT',
  47011. ' attribute vec4 tangent;',
  47012. '#endif',
  47013. '#if defined( USE_COLOR_ALPHA )',
  47014. ' attribute vec4 color;',
  47015. '#elif defined( USE_COLOR )',
  47016. ' attribute vec3 color;',
  47017. '#endif',
  47018. '#ifdef USE_SKINNING',
  47019. ' attribute vec4 skinIndex;',
  47020. ' attribute vec4 skinWeight;',
  47021. '#endif',
  47022. '\n'
  47023. ].filter( filterEmptyLine ).join( '\n' );
  47024. prefixFragment = [
  47025. generatePrecision( parameters ),
  47026. '#define SHADER_TYPE ' + parameters.shaderType,
  47027. '#define SHADER_NAME ' + parameters.shaderName,
  47028. customDefines,
  47029. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47030. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47031. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  47032. parameters.map ? '#define USE_MAP' : '',
  47033. parameters.matcap ? '#define USE_MATCAP' : '',
  47034. parameters.envMap ? '#define USE_ENVMAP' : '',
  47035. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  47036. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47037. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  47038. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  47039. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  47040. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  47041. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47042. parameters.aoMap ? '#define USE_AOMAP' : '',
  47043. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47044. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47045. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47046. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47047. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47048. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47049. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47050. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  47051. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47052. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47053. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47054. parameters.dispersion ? '#define USE_DISPERSION' : '',
  47055. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  47056. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47057. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47058. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47059. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47060. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47061. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47062. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47063. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47064. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  47065. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47066. parameters.sheen ? '#define USE_SHEEN' : '',
  47067. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47068. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47069. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47070. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47071. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47072. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47073. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  47074. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  47075. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47076. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47077. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47078. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47079. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  47080. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47081. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47082. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47083. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47084. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47085. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  47086. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47087. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  47088. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  47089. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47090. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47091. 'uniform mat4 viewMatrix;',
  47092. 'uniform vec3 cameraPosition;',
  47093. 'uniform bool isOrthographic;',
  47094. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  47095. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  47096. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  47097. parameters.dithering ? '#define DITHERING' : '',
  47098. parameters.opaque ? '#define OPAQUE' : '',
  47099. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  47100. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  47101. getLuminanceFunction(),
  47102. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  47103. '\n'
  47104. ].filter( filterEmptyLine ).join( '\n' );
  47105. }
  47106. vertexShader = resolveIncludes( vertexShader );
  47107. vertexShader = replaceLightNums( vertexShader, parameters );
  47108. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  47109. fragmentShader = resolveIncludes( fragmentShader );
  47110. fragmentShader = replaceLightNums( fragmentShader, parameters );
  47111. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  47112. vertexShader = unrollLoops( vertexShader );
  47113. fragmentShader = unrollLoops( fragmentShader );
  47114. if ( parameters.isRawShaderMaterial !== true ) {
  47115. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  47116. versionString = '#version 300 es\n';
  47117. prefixVertex = [
  47118. customVertexExtensions,
  47119. '#define attribute in',
  47120. '#define varying out',
  47121. '#define texture2D texture'
  47122. ].join( '\n' ) + '\n' + prefixVertex;
  47123. prefixFragment = [
  47124. '#define varying in',
  47125. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  47126. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  47127. '#define gl_FragDepthEXT gl_FragDepth',
  47128. '#define texture2D texture',
  47129. '#define textureCube texture',
  47130. '#define texture2DProj textureProj',
  47131. '#define texture2DLodEXT textureLod',
  47132. '#define texture2DProjLodEXT textureProjLod',
  47133. '#define textureCubeLodEXT textureLod',
  47134. '#define texture2DGradEXT textureGrad',
  47135. '#define texture2DProjGradEXT textureProjGrad',
  47136. '#define textureCubeGradEXT textureGrad'
  47137. ].join( '\n' ) + '\n' + prefixFragment;
  47138. }
  47139. const vertexGlsl = versionString + prefixVertex + vertexShader;
  47140. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  47141. // log( '*VERTEX*', vertexGlsl );
  47142. // log( '*FRAGMENT*', fragmentGlsl );
  47143. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  47144. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  47145. gl.attachShader( program, glVertexShader );
  47146. gl.attachShader( program, glFragmentShader );
  47147. // Force a particular attribute to index 0.
  47148. if ( parameters.index0AttributeName !== undefined ) {
  47149. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  47150. } else if ( parameters.morphTargets === true ) {
  47151. // programs with morphTargets displace position out of attribute 0
  47152. gl.bindAttribLocation( program, 0, 'position' );
  47153. }
  47154. gl.linkProgram( program );
  47155. function onFirstUse( self ) {
  47156. // check for link errors
  47157. if ( renderer.debug.checkShaderErrors ) {
  47158. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  47159. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  47160. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  47161. const programLog = programInfoLog.trim();
  47162. const vertexLog = vertexShaderInfoLog.trim();
  47163. const fragmentLog = fragmentShaderInfoLog.trim();
  47164. let runnable = true;
  47165. let haveDiagnostics = true;
  47166. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  47167. runnable = false;
  47168. if ( typeof renderer.debug.onShaderError === 'function' ) {
  47169. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  47170. } else {
  47171. // default error reporting
  47172. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  47173. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  47174. error(
  47175. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47176. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  47177. 'Material Name: ' + self.name + '\n' +
  47178. 'Material Type: ' + self.type + '\n\n' +
  47179. 'Program Info Log: ' + programLog + '\n' +
  47180. vertexErrors + '\n' +
  47181. fragmentErrors
  47182. );
  47183. }
  47184. } else if ( programLog !== '' ) {
  47185. warn( 'WebGLProgram: Program Info Log:', programLog );
  47186. } else if ( vertexLog === '' || fragmentLog === '' ) {
  47187. haveDiagnostics = false;
  47188. }
  47189. if ( haveDiagnostics ) {
  47190. self.diagnostics = {
  47191. runnable: runnable,
  47192. programLog: programLog,
  47193. vertexShader: {
  47194. log: vertexLog,
  47195. prefix: prefixVertex
  47196. },
  47197. fragmentShader: {
  47198. log: fragmentLog,
  47199. prefix: prefixFragment
  47200. }
  47201. };
  47202. }
  47203. }
  47204. // Clean up
  47205. // Crashes in iOS9 and iOS10. #18402
  47206. // gl.detachShader( program, glVertexShader );
  47207. // gl.detachShader( program, glFragmentShader );
  47208. gl.deleteShader( glVertexShader );
  47209. gl.deleteShader( glFragmentShader );
  47210. cachedUniforms = new WebGLUniforms( gl, program );
  47211. cachedAttributes = fetchAttributeLocations( gl, program );
  47212. }
  47213. // set up caching for uniform locations
  47214. let cachedUniforms;
  47215. this.getUniforms = function () {
  47216. if ( cachedUniforms === undefined ) {
  47217. // Populates cachedUniforms and cachedAttributes
  47218. onFirstUse( this );
  47219. }
  47220. return cachedUniforms;
  47221. };
  47222. // set up caching for attribute locations
  47223. let cachedAttributes;
  47224. this.getAttributes = function () {
  47225. if ( cachedAttributes === undefined ) {
  47226. // Populates cachedAttributes and cachedUniforms
  47227. onFirstUse( this );
  47228. }
  47229. return cachedAttributes;
  47230. };
  47231. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  47232. // flag the program as ready immediately. It may cause a stall when it's first used.
  47233. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  47234. this.isReady = function () {
  47235. if ( programReady === false ) {
  47236. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  47237. }
  47238. return programReady;
  47239. };
  47240. // free resource
  47241. this.destroy = function () {
  47242. bindingStates.releaseStatesOfProgram( this );
  47243. gl.deleteProgram( program );
  47244. this.program = undefined;
  47245. };
  47246. //
  47247. this.type = parameters.shaderType;
  47248. this.name = parameters.shaderName;
  47249. this.id = programIdCount ++;
  47250. this.cacheKey = cacheKey;
  47251. this.usedTimes = 1;
  47252. this.program = program;
  47253. this.vertexShader = glVertexShader;
  47254. this.fragmentShader = glFragmentShader;
  47255. return this;
  47256. }
  47257. let _id = 0;
  47258. class WebGLShaderCache {
  47259. constructor() {
  47260. this.shaderCache = new Map();
  47261. this.materialCache = new Map();
  47262. }
  47263. update( material ) {
  47264. const vertexShader = material.vertexShader;
  47265. const fragmentShader = material.fragmentShader;
  47266. const vertexShaderStage = this._getShaderStage( vertexShader );
  47267. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47268. const materialShaders = this._getShaderCacheForMaterial( material );
  47269. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47270. materialShaders.add( vertexShaderStage );
  47271. vertexShaderStage.usedTimes ++;
  47272. }
  47273. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47274. materialShaders.add( fragmentShaderStage );
  47275. fragmentShaderStage.usedTimes ++;
  47276. }
  47277. return this;
  47278. }
  47279. remove( material ) {
  47280. const materialShaders = this.materialCache.get( material );
  47281. for ( const shaderStage of materialShaders ) {
  47282. shaderStage.usedTimes --;
  47283. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47284. }
  47285. this.materialCache.delete( material );
  47286. return this;
  47287. }
  47288. getVertexShaderID( material ) {
  47289. return this._getShaderStage( material.vertexShader ).id;
  47290. }
  47291. getFragmentShaderID( material ) {
  47292. return this._getShaderStage( material.fragmentShader ).id;
  47293. }
  47294. dispose() {
  47295. this.shaderCache.clear();
  47296. this.materialCache.clear();
  47297. }
  47298. _getShaderCacheForMaterial( material ) {
  47299. const cache = this.materialCache;
  47300. let set = cache.get( material );
  47301. if ( set === undefined ) {
  47302. set = new Set();
  47303. cache.set( material, set );
  47304. }
  47305. return set;
  47306. }
  47307. _getShaderStage( code ) {
  47308. const cache = this.shaderCache;
  47309. let stage = cache.get( code );
  47310. if ( stage === undefined ) {
  47311. stage = new WebGLShaderStage( code );
  47312. cache.set( code, stage );
  47313. }
  47314. return stage;
  47315. }
  47316. }
  47317. class WebGLShaderStage {
  47318. constructor( code ) {
  47319. this.id = _id ++;
  47320. this.code = code;
  47321. this.usedTimes = 0;
  47322. }
  47323. }
  47324. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  47325. const _programLayers = new Layers();
  47326. const _customShaders = new WebGLShaderCache();
  47327. const _activeChannels = new Set();
  47328. const programs = [];
  47329. const programsMap = new Map();
  47330. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47331. let precision = capabilities.precision;
  47332. const shaderIDs = {
  47333. MeshDepthMaterial: 'depth',
  47334. MeshDistanceMaterial: 'distance',
  47335. MeshNormalMaterial: 'normal',
  47336. MeshBasicMaterial: 'basic',
  47337. MeshLambertMaterial: 'lambert',
  47338. MeshPhongMaterial: 'phong',
  47339. MeshToonMaterial: 'toon',
  47340. MeshStandardMaterial: 'physical',
  47341. MeshPhysicalMaterial: 'physical',
  47342. MeshMatcapMaterial: 'matcap',
  47343. LineBasicMaterial: 'basic',
  47344. LineDashedMaterial: 'dashed',
  47345. PointsMaterial: 'points',
  47346. ShadowMaterial: 'shadow',
  47347. SpriteMaterial: 'sprite'
  47348. };
  47349. function getChannel( value ) {
  47350. _activeChannels.add( value );
  47351. if ( value === 0 ) return 'uv';
  47352. return `uv${ value }`;
  47353. }
  47354. function getParameters( material, lights, shadows, scene, object ) {
  47355. const fog = scene.fog;
  47356. const geometry = object.geometry;
  47357. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  47358. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  47359. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47360. const shaderID = shaderIDs[ material.type ];
  47361. // heuristics to create shader parameters according to lights in the scene
  47362. // (not to blow over maxLights budget)
  47363. if ( material.precision !== null ) {
  47364. precision = capabilities.getMaxPrecision( material.precision );
  47365. if ( precision !== material.precision ) {
  47366. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47367. }
  47368. }
  47369. //
  47370. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47371. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47372. let morphTextureStride = 0;
  47373. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47374. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47375. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47376. //
  47377. let vertexShader, fragmentShader;
  47378. let customVertexShaderID, customFragmentShaderID;
  47379. if ( shaderID ) {
  47380. const shader = ShaderLib[ shaderID ];
  47381. vertexShader = shader.vertexShader;
  47382. fragmentShader = shader.fragmentShader;
  47383. } else {
  47384. vertexShader = material.vertexShader;
  47385. fragmentShader = material.fragmentShader;
  47386. _customShaders.update( material );
  47387. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47388. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47389. }
  47390. const currentRenderTarget = renderer.getRenderTarget();
  47391. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47392. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47393. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47394. const HAS_MAP = !! material.map;
  47395. const HAS_MATCAP = !! material.matcap;
  47396. const HAS_ENVMAP = !! envMap;
  47397. const HAS_AOMAP = !! material.aoMap;
  47398. const HAS_LIGHTMAP = !! material.lightMap;
  47399. const HAS_BUMPMAP = !! material.bumpMap;
  47400. const HAS_NORMALMAP = !! material.normalMap;
  47401. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47402. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47403. const HAS_METALNESSMAP = !! material.metalnessMap;
  47404. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47405. const HAS_ANISOTROPY = material.anisotropy > 0;
  47406. const HAS_CLEARCOAT = material.clearcoat > 0;
  47407. const HAS_DISPERSION = material.dispersion > 0;
  47408. const HAS_IRIDESCENCE = material.iridescence > 0;
  47409. const HAS_SHEEN = material.sheen > 0;
  47410. const HAS_TRANSMISSION = material.transmission > 0;
  47411. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47412. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47413. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47414. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47415. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47416. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47417. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47418. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47419. const HAS_SPECULARMAP = !! material.specularMap;
  47420. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47421. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47422. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47423. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47424. const HAS_GRADIENTMAP = !! material.gradientMap;
  47425. const HAS_ALPHAMAP = !! material.alphaMap;
  47426. const HAS_ALPHATEST = material.alphaTest > 0;
  47427. const HAS_ALPHAHASH = !! material.alphaHash;
  47428. const HAS_EXTENSIONS = !! material.extensions;
  47429. let toneMapping = NoToneMapping;
  47430. if ( material.toneMapped ) {
  47431. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47432. toneMapping = renderer.toneMapping;
  47433. }
  47434. }
  47435. const parameters = {
  47436. shaderID: shaderID,
  47437. shaderType: material.type,
  47438. shaderName: material.name,
  47439. vertexShader: vertexShader,
  47440. fragmentShader: fragmentShader,
  47441. defines: material.defines,
  47442. customVertexShaderID: customVertexShaderID,
  47443. customFragmentShaderID: customFragmentShaderID,
  47444. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47445. glslVersion: material.glslVersion,
  47446. precision: precision,
  47447. batching: IS_BATCHEDMESH,
  47448. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47449. instancing: IS_INSTANCEDMESH,
  47450. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47451. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47452. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47453. alphaToCoverage: !! material.alphaToCoverage,
  47454. map: HAS_MAP,
  47455. matcap: HAS_MATCAP,
  47456. envMap: HAS_ENVMAP,
  47457. envMapMode: HAS_ENVMAP && envMap.mapping,
  47458. envMapCubeUVHeight: envMapCubeUVHeight,
  47459. aoMap: HAS_AOMAP,
  47460. lightMap: HAS_LIGHTMAP,
  47461. bumpMap: HAS_BUMPMAP,
  47462. normalMap: HAS_NORMALMAP,
  47463. displacementMap: HAS_DISPLACEMENTMAP,
  47464. emissiveMap: HAS_EMISSIVEMAP,
  47465. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47466. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47467. metalnessMap: HAS_METALNESSMAP,
  47468. roughnessMap: HAS_ROUGHNESSMAP,
  47469. anisotropy: HAS_ANISOTROPY,
  47470. anisotropyMap: HAS_ANISOTROPYMAP,
  47471. clearcoat: HAS_CLEARCOAT,
  47472. clearcoatMap: HAS_CLEARCOATMAP,
  47473. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47474. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47475. dispersion: HAS_DISPERSION,
  47476. iridescence: HAS_IRIDESCENCE,
  47477. iridescenceMap: HAS_IRIDESCENCEMAP,
  47478. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47479. sheen: HAS_SHEEN,
  47480. sheenColorMap: HAS_SHEEN_COLORMAP,
  47481. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47482. specularMap: HAS_SPECULARMAP,
  47483. specularColorMap: HAS_SPECULAR_COLORMAP,
  47484. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47485. transmission: HAS_TRANSMISSION,
  47486. transmissionMap: HAS_TRANSMISSIONMAP,
  47487. thicknessMap: HAS_THICKNESSMAP,
  47488. gradientMap: HAS_GRADIENTMAP,
  47489. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47490. alphaMap: HAS_ALPHAMAP,
  47491. alphaTest: HAS_ALPHATEST,
  47492. alphaHash: HAS_ALPHAHASH,
  47493. combine: material.combine,
  47494. //
  47495. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47496. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47497. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47498. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47499. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47500. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47501. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47502. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47503. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47504. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47505. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47506. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47507. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47508. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47509. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47510. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47511. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47512. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47513. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47514. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47515. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47516. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47517. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47518. //
  47519. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47520. vertexColors: material.vertexColors,
  47521. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47522. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47523. fog: !! fog,
  47524. useFog: material.fog === true,
  47525. fogExp2: ( !! fog && fog.isFogExp2 ),
  47526. flatShading: ( material.flatShading === true && material.wireframe === false ),
  47527. sizeAttenuation: material.sizeAttenuation === true,
  47528. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47529. reversedDepthBuffer: reversedDepthBuffer,
  47530. skinning: object.isSkinnedMesh === true,
  47531. morphTargets: geometry.morphAttributes.position !== undefined,
  47532. morphNormals: geometry.morphAttributes.normal !== undefined,
  47533. morphColors: geometry.morphAttributes.color !== undefined,
  47534. morphTargetsCount: morphTargetsCount,
  47535. morphTextureStride: morphTextureStride,
  47536. numDirLights: lights.directional.length,
  47537. numPointLights: lights.point.length,
  47538. numSpotLights: lights.spot.length,
  47539. numSpotLightMaps: lights.spotLightMap.length,
  47540. numRectAreaLights: lights.rectArea.length,
  47541. numHemiLights: lights.hemi.length,
  47542. numDirLightShadows: lights.directionalShadowMap.length,
  47543. numPointLightShadows: lights.pointShadowMap.length,
  47544. numSpotLightShadows: lights.spotShadowMap.length,
  47545. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47546. numLightProbes: lights.numLightProbes,
  47547. numClippingPlanes: clipping.numPlanes,
  47548. numClipIntersection: clipping.numIntersection,
  47549. dithering: material.dithering,
  47550. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47551. shadowMapType: renderer.shadowMap.type,
  47552. toneMapping: toneMapping,
  47553. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47554. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47555. premultipliedAlpha: material.premultipliedAlpha,
  47556. doubleSided: material.side === DoubleSide,
  47557. flipSided: material.side === BackSide,
  47558. useDepthPacking: material.depthPacking >= 0,
  47559. depthPacking: material.depthPacking || 0,
  47560. index0AttributeName: material.index0AttributeName,
  47561. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47562. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47563. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47564. customProgramCacheKey: material.customProgramCacheKey()
  47565. };
  47566. // the usage of getChannel() determines the active texture channels for this shader
  47567. parameters.vertexUv1s = _activeChannels.has( 1 );
  47568. parameters.vertexUv2s = _activeChannels.has( 2 );
  47569. parameters.vertexUv3s = _activeChannels.has( 3 );
  47570. _activeChannels.clear();
  47571. return parameters;
  47572. }
  47573. function getProgramCacheKey( parameters ) {
  47574. const array = [];
  47575. if ( parameters.shaderID ) {
  47576. array.push( parameters.shaderID );
  47577. } else {
  47578. array.push( parameters.customVertexShaderID );
  47579. array.push( parameters.customFragmentShaderID );
  47580. }
  47581. if ( parameters.defines !== undefined ) {
  47582. for ( const name in parameters.defines ) {
  47583. array.push( name );
  47584. array.push( parameters.defines[ name ] );
  47585. }
  47586. }
  47587. if ( parameters.isRawShaderMaterial === false ) {
  47588. getProgramCacheKeyParameters( array, parameters );
  47589. getProgramCacheKeyBooleans( array, parameters );
  47590. array.push( renderer.outputColorSpace );
  47591. }
  47592. array.push( parameters.customProgramCacheKey );
  47593. return array.join();
  47594. }
  47595. function getProgramCacheKeyParameters( array, parameters ) {
  47596. array.push( parameters.precision );
  47597. array.push( parameters.outputColorSpace );
  47598. array.push( parameters.envMapMode );
  47599. array.push( parameters.envMapCubeUVHeight );
  47600. array.push( parameters.mapUv );
  47601. array.push( parameters.alphaMapUv );
  47602. array.push( parameters.lightMapUv );
  47603. array.push( parameters.aoMapUv );
  47604. array.push( parameters.bumpMapUv );
  47605. array.push( parameters.normalMapUv );
  47606. array.push( parameters.displacementMapUv );
  47607. array.push( parameters.emissiveMapUv );
  47608. array.push( parameters.metalnessMapUv );
  47609. array.push( parameters.roughnessMapUv );
  47610. array.push( parameters.anisotropyMapUv );
  47611. array.push( parameters.clearcoatMapUv );
  47612. array.push( parameters.clearcoatNormalMapUv );
  47613. array.push( parameters.clearcoatRoughnessMapUv );
  47614. array.push( parameters.iridescenceMapUv );
  47615. array.push( parameters.iridescenceThicknessMapUv );
  47616. array.push( parameters.sheenColorMapUv );
  47617. array.push( parameters.sheenRoughnessMapUv );
  47618. array.push( parameters.specularMapUv );
  47619. array.push( parameters.specularColorMapUv );
  47620. array.push( parameters.specularIntensityMapUv );
  47621. array.push( parameters.transmissionMapUv );
  47622. array.push( parameters.thicknessMapUv );
  47623. array.push( parameters.combine );
  47624. array.push( parameters.fogExp2 );
  47625. array.push( parameters.sizeAttenuation );
  47626. array.push( parameters.morphTargetsCount );
  47627. array.push( parameters.morphAttributeCount );
  47628. array.push( parameters.numDirLights );
  47629. array.push( parameters.numPointLights );
  47630. array.push( parameters.numSpotLights );
  47631. array.push( parameters.numSpotLightMaps );
  47632. array.push( parameters.numHemiLights );
  47633. array.push( parameters.numRectAreaLights );
  47634. array.push( parameters.numDirLightShadows );
  47635. array.push( parameters.numPointLightShadows );
  47636. array.push( parameters.numSpotLightShadows );
  47637. array.push( parameters.numSpotLightShadowsWithMaps );
  47638. array.push( parameters.numLightProbes );
  47639. array.push( parameters.shadowMapType );
  47640. array.push( parameters.toneMapping );
  47641. array.push( parameters.numClippingPlanes );
  47642. array.push( parameters.numClipIntersection );
  47643. array.push( parameters.depthPacking );
  47644. }
  47645. function getProgramCacheKeyBooleans( array, parameters ) {
  47646. _programLayers.disableAll();
  47647. if ( parameters.instancing )
  47648. _programLayers.enable( 0 );
  47649. if ( parameters.instancingColor )
  47650. _programLayers.enable( 1 );
  47651. if ( parameters.instancingMorph )
  47652. _programLayers.enable( 2 );
  47653. if ( parameters.matcap )
  47654. _programLayers.enable( 3 );
  47655. if ( parameters.envMap )
  47656. _programLayers.enable( 4 );
  47657. if ( parameters.normalMapObjectSpace )
  47658. _programLayers.enable( 5 );
  47659. if ( parameters.normalMapTangentSpace )
  47660. _programLayers.enable( 6 );
  47661. if ( parameters.clearcoat )
  47662. _programLayers.enable( 7 );
  47663. if ( parameters.iridescence )
  47664. _programLayers.enable( 8 );
  47665. if ( parameters.alphaTest )
  47666. _programLayers.enable( 9 );
  47667. if ( parameters.vertexColors )
  47668. _programLayers.enable( 10 );
  47669. if ( parameters.vertexAlphas )
  47670. _programLayers.enable( 11 );
  47671. if ( parameters.vertexUv1s )
  47672. _programLayers.enable( 12 );
  47673. if ( parameters.vertexUv2s )
  47674. _programLayers.enable( 13 );
  47675. if ( parameters.vertexUv3s )
  47676. _programLayers.enable( 14 );
  47677. if ( parameters.vertexTangents )
  47678. _programLayers.enable( 15 );
  47679. if ( parameters.anisotropy )
  47680. _programLayers.enable( 16 );
  47681. if ( parameters.alphaHash )
  47682. _programLayers.enable( 17 );
  47683. if ( parameters.batching )
  47684. _programLayers.enable( 18 );
  47685. if ( parameters.dispersion )
  47686. _programLayers.enable( 19 );
  47687. if ( parameters.batchingColor )
  47688. _programLayers.enable( 20 );
  47689. if ( parameters.gradientMap )
  47690. _programLayers.enable( 21 );
  47691. array.push( _programLayers.mask );
  47692. _programLayers.disableAll();
  47693. if ( parameters.fog )
  47694. _programLayers.enable( 0 );
  47695. if ( parameters.useFog )
  47696. _programLayers.enable( 1 );
  47697. if ( parameters.flatShading )
  47698. _programLayers.enable( 2 );
  47699. if ( parameters.logarithmicDepthBuffer )
  47700. _programLayers.enable( 3 );
  47701. if ( parameters.reversedDepthBuffer )
  47702. _programLayers.enable( 4 );
  47703. if ( parameters.skinning )
  47704. _programLayers.enable( 5 );
  47705. if ( parameters.morphTargets )
  47706. _programLayers.enable( 6 );
  47707. if ( parameters.morphNormals )
  47708. _programLayers.enable( 7 );
  47709. if ( parameters.morphColors )
  47710. _programLayers.enable( 8 );
  47711. if ( parameters.premultipliedAlpha )
  47712. _programLayers.enable( 9 );
  47713. if ( parameters.shadowMapEnabled )
  47714. _programLayers.enable( 10 );
  47715. if ( parameters.doubleSided )
  47716. _programLayers.enable( 11 );
  47717. if ( parameters.flipSided )
  47718. _programLayers.enable( 12 );
  47719. if ( parameters.useDepthPacking )
  47720. _programLayers.enable( 13 );
  47721. if ( parameters.dithering )
  47722. _programLayers.enable( 14 );
  47723. if ( parameters.transmission )
  47724. _programLayers.enable( 15 );
  47725. if ( parameters.sheen )
  47726. _programLayers.enable( 16 );
  47727. if ( parameters.opaque )
  47728. _programLayers.enable( 17 );
  47729. if ( parameters.pointsUvs )
  47730. _programLayers.enable( 18 );
  47731. if ( parameters.decodeVideoTexture )
  47732. _programLayers.enable( 19 );
  47733. if ( parameters.decodeVideoTextureEmissive )
  47734. _programLayers.enable( 20 );
  47735. if ( parameters.alphaToCoverage )
  47736. _programLayers.enable( 21 );
  47737. array.push( _programLayers.mask );
  47738. }
  47739. function getUniforms( material ) {
  47740. const shaderID = shaderIDs[ material.type ];
  47741. let uniforms;
  47742. if ( shaderID ) {
  47743. const shader = ShaderLib[ shaderID ];
  47744. uniforms = UniformsUtils.clone( shader.uniforms );
  47745. } else {
  47746. uniforms = material.uniforms;
  47747. }
  47748. return uniforms;
  47749. }
  47750. function acquireProgram( parameters, cacheKey ) {
  47751. let program = programsMap.get( cacheKey );
  47752. if ( program !== undefined ) {
  47753. ++ program.usedTimes;
  47754. } else {
  47755. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47756. programs.push( program );
  47757. programsMap.set( cacheKey, program );
  47758. }
  47759. return program;
  47760. }
  47761. function releaseProgram( program ) {
  47762. if ( -- program.usedTimes === 0 ) {
  47763. // Remove from unordered set
  47764. const i = programs.indexOf( program );
  47765. programs[ i ] = programs[ programs.length - 1 ];
  47766. programs.pop();
  47767. // Remove from map
  47768. programsMap.delete( program.cacheKey );
  47769. // Free WebGL resources
  47770. program.destroy();
  47771. }
  47772. }
  47773. function releaseShaderCache( material ) {
  47774. _customShaders.remove( material );
  47775. }
  47776. function dispose() {
  47777. _customShaders.dispose();
  47778. }
  47779. return {
  47780. getParameters: getParameters,
  47781. getProgramCacheKey: getProgramCacheKey,
  47782. getUniforms: getUniforms,
  47783. acquireProgram: acquireProgram,
  47784. releaseProgram: releaseProgram,
  47785. releaseShaderCache: releaseShaderCache,
  47786. // Exposed for resource monitoring & error feedback via renderer.info:
  47787. programs: programs,
  47788. dispose: dispose
  47789. };
  47790. }
  47791. function WebGLProperties() {
  47792. let properties = new WeakMap();
  47793. function has( object ) {
  47794. return properties.has( object );
  47795. }
  47796. function get( object ) {
  47797. let map = properties.get( object );
  47798. if ( map === undefined ) {
  47799. map = {};
  47800. properties.set( object, map );
  47801. }
  47802. return map;
  47803. }
  47804. function remove( object ) {
  47805. properties.delete( object );
  47806. }
  47807. function update( object, key, value ) {
  47808. properties.get( object )[ key ] = value;
  47809. }
  47810. function dispose() {
  47811. properties = new WeakMap();
  47812. }
  47813. return {
  47814. has: has,
  47815. get: get,
  47816. remove: remove,
  47817. update: update,
  47818. dispose: dispose
  47819. };
  47820. }
  47821. function painterSortStable( a, b ) {
  47822. if ( a.groupOrder !== b.groupOrder ) {
  47823. return a.groupOrder - b.groupOrder;
  47824. } else if ( a.renderOrder !== b.renderOrder ) {
  47825. return a.renderOrder - b.renderOrder;
  47826. } else if ( a.material.id !== b.material.id ) {
  47827. return a.material.id - b.material.id;
  47828. } else if ( a.materialVariant !== b.materialVariant ) {
  47829. return a.materialVariant - b.materialVariant;
  47830. } else if ( a.z !== b.z ) {
  47831. return a.z - b.z;
  47832. } else {
  47833. return a.id - b.id;
  47834. }
  47835. }
  47836. function reversePainterSortStable( a, b ) {
  47837. if ( a.groupOrder !== b.groupOrder ) {
  47838. return a.groupOrder - b.groupOrder;
  47839. } else if ( a.renderOrder !== b.renderOrder ) {
  47840. return a.renderOrder - b.renderOrder;
  47841. } else if ( a.z !== b.z ) {
  47842. return b.z - a.z;
  47843. } else {
  47844. return a.id - b.id;
  47845. }
  47846. }
  47847. function WebGLRenderList() {
  47848. const renderItems = [];
  47849. let renderItemsIndex = 0;
  47850. const opaque = [];
  47851. const transmissive = [];
  47852. const transparent = [];
  47853. function init() {
  47854. renderItemsIndex = 0;
  47855. opaque.length = 0;
  47856. transmissive.length = 0;
  47857. transparent.length = 0;
  47858. }
  47859. function materialVariant( object ) {
  47860. let variant = 0;
  47861. if ( object.isInstancedMesh ) variant += 2;
  47862. if ( object.isSkinnedMesh ) variant += 1;
  47863. return variant;
  47864. }
  47865. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47866. let renderItem = renderItems[ renderItemsIndex ];
  47867. if ( renderItem === undefined ) {
  47868. renderItem = {
  47869. id: object.id,
  47870. object: object,
  47871. geometry: geometry,
  47872. material: material,
  47873. materialVariant: materialVariant( object ),
  47874. groupOrder: groupOrder,
  47875. renderOrder: object.renderOrder,
  47876. z: z,
  47877. group: group
  47878. };
  47879. renderItems[ renderItemsIndex ] = renderItem;
  47880. } else {
  47881. renderItem.id = object.id;
  47882. renderItem.object = object;
  47883. renderItem.geometry = geometry;
  47884. renderItem.material = material;
  47885. renderItem.materialVariant = materialVariant( object );
  47886. renderItem.groupOrder = groupOrder;
  47887. renderItem.renderOrder = object.renderOrder;
  47888. renderItem.z = z;
  47889. renderItem.group = group;
  47890. }
  47891. renderItemsIndex ++;
  47892. return renderItem;
  47893. }
  47894. function push( object, geometry, material, groupOrder, z, group ) {
  47895. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47896. if ( material.transmission > 0.0 ) {
  47897. transmissive.push( renderItem );
  47898. } else if ( material.transparent === true ) {
  47899. transparent.push( renderItem );
  47900. } else {
  47901. opaque.push( renderItem );
  47902. }
  47903. }
  47904. function unshift( object, geometry, material, groupOrder, z, group ) {
  47905. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47906. if ( material.transmission > 0.0 ) {
  47907. transmissive.unshift( renderItem );
  47908. } else if ( material.transparent === true ) {
  47909. transparent.unshift( renderItem );
  47910. } else {
  47911. opaque.unshift( renderItem );
  47912. }
  47913. }
  47914. function sort( customOpaqueSort, customTransparentSort ) {
  47915. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47916. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47917. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47918. }
  47919. function finish() {
  47920. // Clear references from inactive renderItems in the list
  47921. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47922. const renderItem = renderItems[ i ];
  47923. if ( renderItem.id === null ) break;
  47924. renderItem.id = null;
  47925. renderItem.object = null;
  47926. renderItem.geometry = null;
  47927. renderItem.material = null;
  47928. renderItem.group = null;
  47929. }
  47930. }
  47931. return {
  47932. opaque: opaque,
  47933. transmissive: transmissive,
  47934. transparent: transparent,
  47935. init: init,
  47936. push: push,
  47937. unshift: unshift,
  47938. finish: finish,
  47939. sort: sort
  47940. };
  47941. }
  47942. function WebGLRenderLists() {
  47943. let lists = new WeakMap();
  47944. function get( scene, renderCallDepth ) {
  47945. const listArray = lists.get( scene );
  47946. let list;
  47947. if ( listArray === undefined ) {
  47948. list = new WebGLRenderList();
  47949. lists.set( scene, [ list ] );
  47950. } else {
  47951. if ( renderCallDepth >= listArray.length ) {
  47952. list = new WebGLRenderList();
  47953. listArray.push( list );
  47954. } else {
  47955. list = listArray[ renderCallDepth ];
  47956. }
  47957. }
  47958. return list;
  47959. }
  47960. function dispose() {
  47961. lists = new WeakMap();
  47962. }
  47963. return {
  47964. get: get,
  47965. dispose: dispose
  47966. };
  47967. }
  47968. function UniformsCache() {
  47969. const lights = {};
  47970. return {
  47971. get: function ( light ) {
  47972. if ( lights[ light.id ] !== undefined ) {
  47973. return lights[ light.id ];
  47974. }
  47975. let uniforms;
  47976. switch ( light.type ) {
  47977. case 'DirectionalLight':
  47978. uniforms = {
  47979. direction: new Vector3(),
  47980. color: new Color()
  47981. };
  47982. break;
  47983. case 'SpotLight':
  47984. uniforms = {
  47985. position: new Vector3(),
  47986. direction: new Vector3(),
  47987. color: new Color(),
  47988. distance: 0,
  47989. coneCos: 0,
  47990. penumbraCos: 0,
  47991. decay: 0
  47992. };
  47993. break;
  47994. case 'PointLight':
  47995. uniforms = {
  47996. position: new Vector3(),
  47997. color: new Color(),
  47998. distance: 0,
  47999. decay: 0
  48000. };
  48001. break;
  48002. case 'HemisphereLight':
  48003. uniforms = {
  48004. direction: new Vector3(),
  48005. skyColor: new Color(),
  48006. groundColor: new Color()
  48007. };
  48008. break;
  48009. case 'RectAreaLight':
  48010. uniforms = {
  48011. color: new Color(),
  48012. position: new Vector3(),
  48013. halfWidth: new Vector3(),
  48014. halfHeight: new Vector3()
  48015. };
  48016. break;
  48017. }
  48018. lights[ light.id ] = uniforms;
  48019. return uniforms;
  48020. }
  48021. };
  48022. }
  48023. function ShadowUniformsCache() {
  48024. const lights = {};
  48025. return {
  48026. get: function ( light ) {
  48027. if ( lights[ light.id ] !== undefined ) {
  48028. return lights[ light.id ];
  48029. }
  48030. let uniforms;
  48031. switch ( light.type ) {
  48032. case 'DirectionalLight':
  48033. uniforms = {
  48034. shadowIntensity: 1,
  48035. shadowBias: 0,
  48036. shadowNormalBias: 0,
  48037. shadowRadius: 1,
  48038. shadowMapSize: new Vector2()
  48039. };
  48040. break;
  48041. case 'SpotLight':
  48042. uniforms = {
  48043. shadowIntensity: 1,
  48044. shadowBias: 0,
  48045. shadowNormalBias: 0,
  48046. shadowRadius: 1,
  48047. shadowMapSize: new Vector2()
  48048. };
  48049. break;
  48050. case 'PointLight':
  48051. uniforms = {
  48052. shadowIntensity: 1,
  48053. shadowBias: 0,
  48054. shadowNormalBias: 0,
  48055. shadowRadius: 1,
  48056. shadowMapSize: new Vector2(),
  48057. shadowCameraNear: 1,
  48058. shadowCameraFar: 1000
  48059. };
  48060. break;
  48061. // TODO (abelnation): set RectAreaLight shadow uniforms
  48062. }
  48063. lights[ light.id ] = uniforms;
  48064. return uniforms;
  48065. }
  48066. };
  48067. }
  48068. let nextVersion = 0;
  48069. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  48070. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  48071. }
  48072. function WebGLLights( extensions ) {
  48073. const cache = new UniformsCache();
  48074. const shadowCache = ShadowUniformsCache();
  48075. const state = {
  48076. version: 0,
  48077. hash: {
  48078. directionalLength: -1,
  48079. pointLength: -1,
  48080. spotLength: -1,
  48081. rectAreaLength: -1,
  48082. hemiLength: -1,
  48083. numDirectionalShadows: -1,
  48084. numPointShadows: -1,
  48085. numSpotShadows: -1,
  48086. numSpotMaps: -1,
  48087. numLightProbes: -1
  48088. },
  48089. ambient: [ 0, 0, 0 ],
  48090. probe: [],
  48091. directional: [],
  48092. directionalShadow: [],
  48093. directionalShadowMap: [],
  48094. directionalShadowMatrix: [],
  48095. spot: [],
  48096. spotLightMap: [],
  48097. spotShadow: [],
  48098. spotShadowMap: [],
  48099. spotLightMatrix: [],
  48100. rectArea: [],
  48101. rectAreaLTC1: null,
  48102. rectAreaLTC2: null,
  48103. point: [],
  48104. pointShadow: [],
  48105. pointShadowMap: [],
  48106. pointShadowMatrix: [],
  48107. hemi: [],
  48108. numSpotLightShadowsWithMaps: 0,
  48109. numLightProbes: 0
  48110. };
  48111. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  48112. const vector3 = new Vector3();
  48113. const matrix4 = new Matrix4();
  48114. const matrix42 = new Matrix4();
  48115. function setup( lights ) {
  48116. let r = 0, g = 0, b = 0;
  48117. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  48118. let directionalLength = 0;
  48119. let pointLength = 0;
  48120. let spotLength = 0;
  48121. let rectAreaLength = 0;
  48122. let hemiLength = 0;
  48123. let numDirectionalShadows = 0;
  48124. let numPointShadows = 0;
  48125. let numSpotShadows = 0;
  48126. let numSpotMaps = 0;
  48127. let numSpotShadowsWithMaps = 0;
  48128. let numLightProbes = 0;
  48129. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  48130. lights.sort( shadowCastingAndTexturingLightsFirst );
  48131. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48132. const light = lights[ i ];
  48133. const color = light.color;
  48134. const intensity = light.intensity;
  48135. const distance = light.distance;
  48136. let shadowMap = null;
  48137. if ( light.shadow && light.shadow.map ) {
  48138. if ( light.shadow.map.texture.format === RGFormat ) {
  48139. // VSM uses color texture with blurred mean/std_dev
  48140. shadowMap = light.shadow.map.texture;
  48141. } else {
  48142. // Other types use depth texture
  48143. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  48144. }
  48145. }
  48146. if ( light.isAmbientLight ) {
  48147. r += color.r * intensity;
  48148. g += color.g * intensity;
  48149. b += color.b * intensity;
  48150. } else if ( light.isLightProbe ) {
  48151. for ( let j = 0; j < 9; j ++ ) {
  48152. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  48153. }
  48154. numLightProbes ++;
  48155. } else if ( light.isDirectionalLight ) {
  48156. const uniforms = cache.get( light );
  48157. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48158. if ( light.castShadow ) {
  48159. const shadow = light.shadow;
  48160. const shadowUniforms = shadowCache.get( light );
  48161. shadowUniforms.shadowIntensity = shadow.intensity;
  48162. shadowUniforms.shadowBias = shadow.bias;
  48163. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48164. shadowUniforms.shadowRadius = shadow.radius;
  48165. shadowUniforms.shadowMapSize = shadow.mapSize;
  48166. state.directionalShadow[ directionalLength ] = shadowUniforms;
  48167. state.directionalShadowMap[ directionalLength ] = shadowMap;
  48168. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  48169. numDirectionalShadows ++;
  48170. }
  48171. state.directional[ directionalLength ] = uniforms;
  48172. directionalLength ++;
  48173. } else if ( light.isSpotLight ) {
  48174. const uniforms = cache.get( light );
  48175. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48176. uniforms.color.copy( color ).multiplyScalar( intensity );
  48177. uniforms.distance = distance;
  48178. uniforms.coneCos = Math.cos( light.angle );
  48179. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  48180. uniforms.decay = light.decay;
  48181. state.spot[ spotLength ] = uniforms;
  48182. const shadow = light.shadow;
  48183. if ( light.map ) {
  48184. state.spotLightMap[ numSpotMaps ] = light.map;
  48185. numSpotMaps ++;
  48186. // make sure the lightMatrix is up to date
  48187. // TODO : do it if required only
  48188. shadow.updateMatrices( light );
  48189. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  48190. }
  48191. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  48192. if ( light.castShadow ) {
  48193. const shadowUniforms = shadowCache.get( light );
  48194. shadowUniforms.shadowIntensity = shadow.intensity;
  48195. shadowUniforms.shadowBias = shadow.bias;
  48196. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48197. shadowUniforms.shadowRadius = shadow.radius;
  48198. shadowUniforms.shadowMapSize = shadow.mapSize;
  48199. state.spotShadow[ spotLength ] = shadowUniforms;
  48200. state.spotShadowMap[ spotLength ] = shadowMap;
  48201. numSpotShadows ++;
  48202. }
  48203. spotLength ++;
  48204. } else if ( light.isRectAreaLight ) {
  48205. const uniforms = cache.get( light );
  48206. uniforms.color.copy( color ).multiplyScalar( intensity );
  48207. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48208. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48209. state.rectArea[ rectAreaLength ] = uniforms;
  48210. rectAreaLength ++;
  48211. } else if ( light.isPointLight ) {
  48212. const uniforms = cache.get( light );
  48213. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48214. uniforms.distance = light.distance;
  48215. uniforms.decay = light.decay;
  48216. if ( light.castShadow ) {
  48217. const shadow = light.shadow;
  48218. const shadowUniforms = shadowCache.get( light );
  48219. shadowUniforms.shadowIntensity = shadow.intensity;
  48220. shadowUniforms.shadowBias = shadow.bias;
  48221. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48222. shadowUniforms.shadowRadius = shadow.radius;
  48223. shadowUniforms.shadowMapSize = shadow.mapSize;
  48224. shadowUniforms.shadowCameraNear = shadow.camera.near;
  48225. shadowUniforms.shadowCameraFar = shadow.camera.far;
  48226. state.pointShadow[ pointLength ] = shadowUniforms;
  48227. state.pointShadowMap[ pointLength ] = shadowMap;
  48228. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  48229. numPointShadows ++;
  48230. }
  48231. state.point[ pointLength ] = uniforms;
  48232. pointLength ++;
  48233. } else if ( light.isHemisphereLight ) {
  48234. const uniforms = cache.get( light );
  48235. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  48236. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  48237. state.hemi[ hemiLength ] = uniforms;
  48238. hemiLength ++;
  48239. }
  48240. }
  48241. if ( rectAreaLength > 0 ) {
  48242. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  48243. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  48244. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  48245. } else {
  48246. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  48247. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  48248. }
  48249. }
  48250. state.ambient[ 0 ] = r;
  48251. state.ambient[ 1 ] = g;
  48252. state.ambient[ 2 ] = b;
  48253. const hash = state.hash;
  48254. if ( hash.directionalLength !== directionalLength ||
  48255. hash.pointLength !== pointLength ||
  48256. hash.spotLength !== spotLength ||
  48257. hash.rectAreaLength !== rectAreaLength ||
  48258. hash.hemiLength !== hemiLength ||
  48259. hash.numDirectionalShadows !== numDirectionalShadows ||
  48260. hash.numPointShadows !== numPointShadows ||
  48261. hash.numSpotShadows !== numSpotShadows ||
  48262. hash.numSpotMaps !== numSpotMaps ||
  48263. hash.numLightProbes !== numLightProbes ) {
  48264. state.directional.length = directionalLength;
  48265. state.spot.length = spotLength;
  48266. state.rectArea.length = rectAreaLength;
  48267. state.point.length = pointLength;
  48268. state.hemi.length = hemiLength;
  48269. state.directionalShadow.length = numDirectionalShadows;
  48270. state.directionalShadowMap.length = numDirectionalShadows;
  48271. state.pointShadow.length = numPointShadows;
  48272. state.pointShadowMap.length = numPointShadows;
  48273. state.spotShadow.length = numSpotShadows;
  48274. state.spotShadowMap.length = numSpotShadows;
  48275. state.directionalShadowMatrix.length = numDirectionalShadows;
  48276. state.pointShadowMatrix.length = numPointShadows;
  48277. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48278. state.spotLightMap.length = numSpotMaps;
  48279. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48280. state.numLightProbes = numLightProbes;
  48281. hash.directionalLength = directionalLength;
  48282. hash.pointLength = pointLength;
  48283. hash.spotLength = spotLength;
  48284. hash.rectAreaLength = rectAreaLength;
  48285. hash.hemiLength = hemiLength;
  48286. hash.numDirectionalShadows = numDirectionalShadows;
  48287. hash.numPointShadows = numPointShadows;
  48288. hash.numSpotShadows = numSpotShadows;
  48289. hash.numSpotMaps = numSpotMaps;
  48290. hash.numLightProbes = numLightProbes;
  48291. state.version = nextVersion ++;
  48292. }
  48293. }
  48294. function setupView( lights, camera ) {
  48295. let directionalLength = 0;
  48296. let pointLength = 0;
  48297. let spotLength = 0;
  48298. let rectAreaLength = 0;
  48299. let hemiLength = 0;
  48300. const viewMatrix = camera.matrixWorldInverse;
  48301. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48302. const light = lights[ i ];
  48303. if ( light.isDirectionalLight ) {
  48304. const uniforms = state.directional[ directionalLength ];
  48305. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48306. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48307. uniforms.direction.sub( vector3 );
  48308. uniforms.direction.transformDirection( viewMatrix );
  48309. directionalLength ++;
  48310. } else if ( light.isSpotLight ) {
  48311. const uniforms = state.spot[ spotLength ];
  48312. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48313. uniforms.position.applyMatrix4( viewMatrix );
  48314. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48315. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48316. uniforms.direction.sub( vector3 );
  48317. uniforms.direction.transformDirection( viewMatrix );
  48318. spotLength ++;
  48319. } else if ( light.isRectAreaLight ) {
  48320. const uniforms = state.rectArea[ rectAreaLength ];
  48321. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48322. uniforms.position.applyMatrix4( viewMatrix );
  48323. // extract local rotation of light to derive width/height half vectors
  48324. matrix42.identity();
  48325. matrix4.copy( light.matrixWorld );
  48326. matrix4.premultiply( viewMatrix );
  48327. matrix42.extractRotation( matrix4 );
  48328. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48329. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48330. uniforms.halfWidth.applyMatrix4( matrix42 );
  48331. uniforms.halfHeight.applyMatrix4( matrix42 );
  48332. rectAreaLength ++;
  48333. } else if ( light.isPointLight ) {
  48334. const uniforms = state.point[ pointLength ];
  48335. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48336. uniforms.position.applyMatrix4( viewMatrix );
  48337. pointLength ++;
  48338. } else if ( light.isHemisphereLight ) {
  48339. const uniforms = state.hemi[ hemiLength ];
  48340. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48341. uniforms.direction.transformDirection( viewMatrix );
  48342. hemiLength ++;
  48343. }
  48344. }
  48345. }
  48346. return {
  48347. setup: setup,
  48348. setupView: setupView,
  48349. state: state
  48350. };
  48351. }
  48352. function WebGLRenderState( extensions ) {
  48353. const lights = new WebGLLights( extensions );
  48354. const lightsArray = [];
  48355. const shadowsArray = [];
  48356. function init( camera ) {
  48357. state.camera = camera;
  48358. lightsArray.length = 0;
  48359. shadowsArray.length = 0;
  48360. }
  48361. function pushLight( light ) {
  48362. lightsArray.push( light );
  48363. }
  48364. function pushShadow( shadowLight ) {
  48365. shadowsArray.push( shadowLight );
  48366. }
  48367. function setupLights() {
  48368. lights.setup( lightsArray );
  48369. }
  48370. function setupLightsView( camera ) {
  48371. lights.setupView( lightsArray, camera );
  48372. }
  48373. const state = {
  48374. lightsArray: lightsArray,
  48375. shadowsArray: shadowsArray,
  48376. camera: null,
  48377. lights: lights,
  48378. transmissionRenderTarget: {}
  48379. };
  48380. return {
  48381. init: init,
  48382. state: state,
  48383. setupLights: setupLights,
  48384. setupLightsView: setupLightsView,
  48385. pushLight: pushLight,
  48386. pushShadow: pushShadow
  48387. };
  48388. }
  48389. function WebGLRenderStates( extensions ) {
  48390. let renderStates = new WeakMap();
  48391. function get( scene, renderCallDepth = 0 ) {
  48392. const renderStateArray = renderStates.get( scene );
  48393. let renderState;
  48394. if ( renderStateArray === undefined ) {
  48395. renderState = new WebGLRenderState( extensions );
  48396. renderStates.set( scene, [ renderState ] );
  48397. } else {
  48398. if ( renderCallDepth >= renderStateArray.length ) {
  48399. renderState = new WebGLRenderState( extensions );
  48400. renderStateArray.push( renderState );
  48401. } else {
  48402. renderState = renderStateArray[ renderCallDepth ];
  48403. }
  48404. }
  48405. return renderState;
  48406. }
  48407. function dispose() {
  48408. renderStates = new WeakMap();
  48409. }
  48410. return {
  48411. get: get,
  48412. dispose: dispose
  48413. };
  48414. }
  48415. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48416. 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}";
  48417. const _cubeDirections = [
  48418. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  48419. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  48420. ];
  48421. const _cubeUps = [
  48422. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  48423. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  48424. ];
  48425. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  48426. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  48427. const _lookTarget = /*@__PURE__*/ new Vector3();
  48428. function WebGLShadowMap( renderer, objects, capabilities ) {
  48429. let _frustum = new Frustum();
  48430. const _shadowMapSize = new Vector2(),
  48431. _viewportSize = new Vector2(),
  48432. _viewport = new Vector4(),
  48433. _depthMaterial = new MeshDepthMaterial(),
  48434. _distanceMaterial = new MeshDistanceMaterial(),
  48435. _materialCache = {},
  48436. _maxTextureSize = capabilities.maxTextureSize;
  48437. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48438. const shadowMaterialVertical = new ShaderMaterial( {
  48439. defines: {
  48440. VSM_SAMPLES: 8
  48441. },
  48442. uniforms: {
  48443. shadow_pass: { value: null },
  48444. resolution: { value: new Vector2() },
  48445. radius: { value: 4.0 }
  48446. },
  48447. vertexShader: vertex,
  48448. fragmentShader: fragment
  48449. } );
  48450. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48451. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48452. const fullScreenTri = new BufferGeometry();
  48453. fullScreenTri.setAttribute(
  48454. 'position',
  48455. new BufferAttribute(
  48456. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48457. 3
  48458. )
  48459. );
  48460. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48461. const scope = this;
  48462. this.enabled = false;
  48463. this.autoUpdate = true;
  48464. this.needsUpdate = false;
  48465. this.type = PCFShadowMap;
  48466. let _previousType = this.type;
  48467. this.render = function ( lights, scene, camera ) {
  48468. if ( scope.enabled === false ) return;
  48469. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48470. if ( lights.length === 0 ) return;
  48471. if ( this.type === PCFSoftShadowMap ) {
  48472. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48473. this.type = PCFShadowMap;
  48474. }
  48475. const currentRenderTarget = renderer.getRenderTarget();
  48476. const activeCubeFace = renderer.getActiveCubeFace();
  48477. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48478. const _state = renderer.state;
  48479. // Set GL state for depth map.
  48480. _state.setBlending( NoBlending );
  48481. if ( _state.buffers.depth.getReversed() === true ) {
  48482. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48483. } else {
  48484. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48485. }
  48486. _state.buffers.depth.setTest( true );
  48487. _state.setScissorTest( false );
  48488. // check for shadow map type changes
  48489. const typeChanged = _previousType !== this.type;
  48490. // When shadow map type changes, materials need recompilation because sampler types change
  48491. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48492. if ( typeChanged ) {
  48493. scene.traverse( function ( object ) {
  48494. if ( object.material ) {
  48495. if ( Array.isArray( object.material ) ) {
  48496. object.material.forEach( mat => mat.needsUpdate = true );
  48497. } else {
  48498. object.material.needsUpdate = true;
  48499. }
  48500. }
  48501. } );
  48502. }
  48503. // render depth map
  48504. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48505. const light = lights[ i ];
  48506. const shadow = light.shadow;
  48507. if ( shadow === undefined ) {
  48508. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48509. continue;
  48510. }
  48511. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48512. _shadowMapSize.copy( shadow.mapSize );
  48513. const shadowFrameExtents = shadow.getFrameExtents();
  48514. _shadowMapSize.multiply( shadowFrameExtents );
  48515. _viewportSize.copy( shadow.mapSize );
  48516. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48517. if ( _shadowMapSize.x > _maxTextureSize ) {
  48518. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48519. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48520. shadow.mapSize.x = _viewportSize.x;
  48521. }
  48522. if ( _shadowMapSize.y > _maxTextureSize ) {
  48523. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48524. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48525. shadow.mapSize.y = _viewportSize.y;
  48526. }
  48527. }
  48528. if ( shadow.map === null || typeChanged === true ) {
  48529. if ( shadow.map !== null ) {
  48530. if ( shadow.map.depthTexture !== null ) {
  48531. shadow.map.depthTexture.dispose();
  48532. shadow.map.depthTexture = null;
  48533. }
  48534. shadow.map.dispose();
  48535. }
  48536. if ( this.type === VSMShadowMap ) {
  48537. if ( light.isPointLight ) {
  48538. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48539. continue;
  48540. }
  48541. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48542. format: RGFormat,
  48543. type: HalfFloatType,
  48544. minFilter: LinearFilter,
  48545. magFilter: LinearFilter,
  48546. generateMipmaps: false
  48547. } );
  48548. shadow.map.texture.name = light.name + '.shadowMap';
  48549. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  48550. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  48551. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  48552. shadow.map.depthTexture.format = DepthFormat;
  48553. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  48554. shadow.map.depthTexture.minFilter = NearestFilter;
  48555. shadow.map.depthTexture.magFilter = NearestFilter;
  48556. } else {
  48557. if ( light.isPointLight ) {
  48558. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48559. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48560. } else {
  48561. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48562. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48563. }
  48564. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48565. shadow.map.depthTexture.format = DepthFormat;
  48566. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48567. if ( this.type === PCFShadowMap ) {
  48568. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48569. shadow.map.depthTexture.minFilter = LinearFilter;
  48570. shadow.map.depthTexture.magFilter = LinearFilter;
  48571. } else {
  48572. shadow.map.depthTexture.compareFunction = null;
  48573. shadow.map.depthTexture.minFilter = NearestFilter;
  48574. shadow.map.depthTexture.magFilter = NearestFilter;
  48575. }
  48576. }
  48577. shadow.camera.updateProjectionMatrix();
  48578. }
  48579. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48580. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48581. for ( let face = 0; face < faceCount; face ++ ) {
  48582. // For cube render targets, render to each face separately
  48583. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48584. renderer.setRenderTarget( shadow.map, face );
  48585. renderer.clear();
  48586. } else {
  48587. // For 2D render targets, use viewports
  48588. if ( face === 0 ) {
  48589. renderer.setRenderTarget( shadow.map );
  48590. renderer.clear();
  48591. }
  48592. const viewport = shadow.getViewport( face );
  48593. _viewport.set(
  48594. _viewportSize.x * viewport.x,
  48595. _viewportSize.y * viewport.y,
  48596. _viewportSize.x * viewport.z,
  48597. _viewportSize.y * viewport.w
  48598. );
  48599. _state.viewport( _viewport );
  48600. }
  48601. if ( light.isPointLight ) {
  48602. const camera = shadow.camera;
  48603. const shadowMatrix = shadow.matrix;
  48604. const far = light.distance || camera.far;
  48605. if ( far !== camera.far ) {
  48606. camera.far = far;
  48607. camera.updateProjectionMatrix();
  48608. }
  48609. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  48610. camera.position.copy( _lightPositionWorld );
  48611. _lookTarget.copy( camera.position );
  48612. _lookTarget.add( _cubeDirections[ face ] );
  48613. camera.up.copy( _cubeUps[ face ] );
  48614. camera.lookAt( _lookTarget );
  48615. camera.updateMatrixWorld();
  48616. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  48617. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  48618. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  48619. } else {
  48620. shadow.updateMatrices( light );
  48621. }
  48622. _frustum = shadow.getFrustum();
  48623. renderObject( scene, camera, shadow.camera, light, this.type );
  48624. }
  48625. // do blur pass for VSM
  48626. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  48627. VSMPass( shadow, camera );
  48628. }
  48629. shadow.needsUpdate = false;
  48630. }
  48631. _previousType = this.type;
  48632. scope.needsUpdate = false;
  48633. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  48634. };
  48635. function VSMPass( shadow, camera ) {
  48636. const geometry = objects.update( fullScreenMesh );
  48637. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  48638. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  48639. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  48640. shadowMaterialVertical.needsUpdate = true;
  48641. shadowMaterialHorizontal.needsUpdate = true;
  48642. }
  48643. if ( shadow.mapPass === null ) {
  48644. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48645. format: RGFormat,
  48646. type: HalfFloatType
  48647. } );
  48648. }
  48649. // vertical pass - read from native depth texture
  48650. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  48651. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  48652. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  48653. renderer.setRenderTarget( shadow.mapPass );
  48654. renderer.clear();
  48655. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  48656. // horizontal pass
  48657. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  48658. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  48659. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  48660. renderer.setRenderTarget( shadow.map );
  48661. renderer.clear();
  48662. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  48663. }
  48664. function getDepthMaterial( object, material, light, type ) {
  48665. let result = null;
  48666. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  48667. if ( customMaterial !== undefined ) {
  48668. result = customMaterial;
  48669. } else {
  48670. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  48671. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  48672. ( material.displacementMap && material.displacementScale !== 0 ) ||
  48673. ( material.alphaMap && material.alphaTest > 0 ) ||
  48674. ( material.map && material.alphaTest > 0 ) ||
  48675. ( material.alphaToCoverage === true ) ) {
  48676. // in this case we need a unique material instance reflecting the
  48677. // appropriate state
  48678. const keyA = result.uuid, keyB = material.uuid;
  48679. let materialsForVariant = _materialCache[ keyA ];
  48680. if ( materialsForVariant === undefined ) {
  48681. materialsForVariant = {};
  48682. _materialCache[ keyA ] = materialsForVariant;
  48683. }
  48684. let cachedMaterial = materialsForVariant[ keyB ];
  48685. if ( cachedMaterial === undefined ) {
  48686. cachedMaterial = result.clone();
  48687. materialsForVariant[ keyB ] = cachedMaterial;
  48688. material.addEventListener( 'dispose', onMaterialDispose );
  48689. }
  48690. result = cachedMaterial;
  48691. }
  48692. }
  48693. result.visible = material.visible;
  48694. result.wireframe = material.wireframe;
  48695. if ( type === VSMShadowMap ) {
  48696. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  48697. } else {
  48698. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  48699. }
  48700. result.alphaMap = material.alphaMap;
  48701. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  48702. result.map = material.map;
  48703. result.clipShadows = material.clipShadows;
  48704. result.clippingPlanes = material.clippingPlanes;
  48705. result.clipIntersection = material.clipIntersection;
  48706. result.displacementMap = material.displacementMap;
  48707. result.displacementScale = material.displacementScale;
  48708. result.displacementBias = material.displacementBias;
  48709. result.wireframeLinewidth = material.wireframeLinewidth;
  48710. result.linewidth = material.linewidth;
  48711. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  48712. const materialProperties = renderer.properties.get( result );
  48713. materialProperties.light = light;
  48714. }
  48715. return result;
  48716. }
  48717. function renderObject( object, camera, shadowCamera, light, type ) {
  48718. if ( object.visible === false ) return;
  48719. const visible = object.layers.test( camera.layers );
  48720. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  48721. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  48722. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  48723. const geometry = objects.update( object );
  48724. const material = object.material;
  48725. if ( Array.isArray( material ) ) {
  48726. const groups = geometry.groups;
  48727. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48728. const group = groups[ k ];
  48729. const groupMaterial = material[ group.materialIndex ];
  48730. if ( groupMaterial && groupMaterial.visible ) {
  48731. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48732. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48733. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48734. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48735. }
  48736. }
  48737. } else if ( material.visible ) {
  48738. const depthMaterial = getDepthMaterial( object, material, light, type );
  48739. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48740. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48741. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48742. }
  48743. }
  48744. }
  48745. const children = object.children;
  48746. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48747. renderObject( children[ i ], camera, shadowCamera, light, type );
  48748. }
  48749. }
  48750. function onMaterialDispose( event ) {
  48751. const material = event.target;
  48752. material.removeEventListener( 'dispose', onMaterialDispose );
  48753. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48754. for ( const id in _materialCache ) {
  48755. const cache = _materialCache[ id ];
  48756. const uuid = event.target.uuid;
  48757. if ( uuid in cache ) {
  48758. const shadowMaterial = cache[ uuid ];
  48759. shadowMaterial.dispose();
  48760. delete cache[ uuid ];
  48761. }
  48762. }
  48763. }
  48764. }
  48765. const reversedFuncs = {
  48766. [ NeverDepth ]: AlwaysDepth,
  48767. [ LessDepth ]: GreaterDepth,
  48768. [ EqualDepth ]: NotEqualDepth,
  48769. [ LessEqualDepth ]: GreaterEqualDepth,
  48770. [ AlwaysDepth ]: NeverDepth,
  48771. [ GreaterDepth ]: LessDepth,
  48772. [ NotEqualDepth ]: EqualDepth,
  48773. [ GreaterEqualDepth ]: LessEqualDepth,
  48774. };
  48775. function WebGLState( gl, extensions ) {
  48776. function ColorBuffer() {
  48777. let locked = false;
  48778. const color = new Vector4();
  48779. let currentColorMask = null;
  48780. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48781. return {
  48782. setMask: function ( colorMask ) {
  48783. if ( currentColorMask !== colorMask && ! locked ) {
  48784. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48785. currentColorMask = colorMask;
  48786. }
  48787. },
  48788. setLocked: function ( lock ) {
  48789. locked = lock;
  48790. },
  48791. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48792. if ( premultipliedAlpha === true ) {
  48793. r *= a; g *= a; b *= a;
  48794. }
  48795. color.set( r, g, b, a );
  48796. if ( currentColorClear.equals( color ) === false ) {
  48797. gl.clearColor( r, g, b, a );
  48798. currentColorClear.copy( color );
  48799. }
  48800. },
  48801. reset: function () {
  48802. locked = false;
  48803. currentColorMask = null;
  48804. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48805. }
  48806. };
  48807. }
  48808. function DepthBuffer() {
  48809. let locked = false;
  48810. let currentReversed = false;
  48811. let currentDepthMask = null;
  48812. let currentDepthFunc = null;
  48813. let currentDepthClear = null;
  48814. return {
  48815. setReversed: function ( reversed ) {
  48816. if ( currentReversed !== reversed ) {
  48817. const ext = extensions.get( 'EXT_clip_control' );
  48818. if ( reversed ) {
  48819. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48820. } else {
  48821. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48822. }
  48823. currentReversed = reversed;
  48824. const oldDepth = currentDepthClear;
  48825. currentDepthClear = null;
  48826. this.setClear( oldDepth );
  48827. }
  48828. },
  48829. getReversed: function () {
  48830. return currentReversed;
  48831. },
  48832. setTest: function ( depthTest ) {
  48833. if ( depthTest ) {
  48834. enable( gl.DEPTH_TEST );
  48835. } else {
  48836. disable( gl.DEPTH_TEST );
  48837. }
  48838. },
  48839. setMask: function ( depthMask ) {
  48840. if ( currentDepthMask !== depthMask && ! locked ) {
  48841. gl.depthMask( depthMask );
  48842. currentDepthMask = depthMask;
  48843. }
  48844. },
  48845. setFunc: function ( depthFunc ) {
  48846. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48847. if ( currentDepthFunc !== depthFunc ) {
  48848. switch ( depthFunc ) {
  48849. case NeverDepth:
  48850. gl.depthFunc( gl.NEVER );
  48851. break;
  48852. case AlwaysDepth:
  48853. gl.depthFunc( gl.ALWAYS );
  48854. break;
  48855. case LessDepth:
  48856. gl.depthFunc( gl.LESS );
  48857. break;
  48858. case LessEqualDepth:
  48859. gl.depthFunc( gl.LEQUAL );
  48860. break;
  48861. case EqualDepth:
  48862. gl.depthFunc( gl.EQUAL );
  48863. break;
  48864. case GreaterEqualDepth:
  48865. gl.depthFunc( gl.GEQUAL );
  48866. break;
  48867. case GreaterDepth:
  48868. gl.depthFunc( gl.GREATER );
  48869. break;
  48870. case NotEqualDepth:
  48871. gl.depthFunc( gl.NOTEQUAL );
  48872. break;
  48873. default:
  48874. gl.depthFunc( gl.LEQUAL );
  48875. }
  48876. currentDepthFunc = depthFunc;
  48877. }
  48878. },
  48879. setLocked: function ( lock ) {
  48880. locked = lock;
  48881. },
  48882. setClear: function ( depth ) {
  48883. if ( currentDepthClear !== depth ) {
  48884. if ( currentReversed ) {
  48885. depth = 1 - depth;
  48886. }
  48887. gl.clearDepth( depth );
  48888. currentDepthClear = depth;
  48889. }
  48890. },
  48891. reset: function () {
  48892. locked = false;
  48893. currentDepthMask = null;
  48894. currentDepthFunc = null;
  48895. currentDepthClear = null;
  48896. currentReversed = false;
  48897. }
  48898. };
  48899. }
  48900. function StencilBuffer() {
  48901. let locked = false;
  48902. let currentStencilMask = null;
  48903. let currentStencilFunc = null;
  48904. let currentStencilRef = null;
  48905. let currentStencilFuncMask = null;
  48906. let currentStencilFail = null;
  48907. let currentStencilZFail = null;
  48908. let currentStencilZPass = null;
  48909. let currentStencilClear = null;
  48910. return {
  48911. setTest: function ( stencilTest ) {
  48912. if ( ! locked ) {
  48913. if ( stencilTest ) {
  48914. enable( gl.STENCIL_TEST );
  48915. } else {
  48916. disable( gl.STENCIL_TEST );
  48917. }
  48918. }
  48919. },
  48920. setMask: function ( stencilMask ) {
  48921. if ( currentStencilMask !== stencilMask && ! locked ) {
  48922. gl.stencilMask( stencilMask );
  48923. currentStencilMask = stencilMask;
  48924. }
  48925. },
  48926. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48927. if ( currentStencilFunc !== stencilFunc ||
  48928. currentStencilRef !== stencilRef ||
  48929. currentStencilFuncMask !== stencilMask ) {
  48930. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48931. currentStencilFunc = stencilFunc;
  48932. currentStencilRef = stencilRef;
  48933. currentStencilFuncMask = stencilMask;
  48934. }
  48935. },
  48936. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48937. if ( currentStencilFail !== stencilFail ||
  48938. currentStencilZFail !== stencilZFail ||
  48939. currentStencilZPass !== stencilZPass ) {
  48940. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48941. currentStencilFail = stencilFail;
  48942. currentStencilZFail = stencilZFail;
  48943. currentStencilZPass = stencilZPass;
  48944. }
  48945. },
  48946. setLocked: function ( lock ) {
  48947. locked = lock;
  48948. },
  48949. setClear: function ( stencil ) {
  48950. if ( currentStencilClear !== stencil ) {
  48951. gl.clearStencil( stencil );
  48952. currentStencilClear = stencil;
  48953. }
  48954. },
  48955. reset: function () {
  48956. locked = false;
  48957. currentStencilMask = null;
  48958. currentStencilFunc = null;
  48959. currentStencilRef = null;
  48960. currentStencilFuncMask = null;
  48961. currentStencilFail = null;
  48962. currentStencilZFail = null;
  48963. currentStencilZPass = null;
  48964. currentStencilClear = null;
  48965. }
  48966. };
  48967. }
  48968. //
  48969. const colorBuffer = new ColorBuffer();
  48970. const depthBuffer = new DepthBuffer();
  48971. const stencilBuffer = new StencilBuffer();
  48972. const uboBindings = new WeakMap();
  48973. const uboProgramMap = new WeakMap();
  48974. let enabledCapabilities = {};
  48975. let currentBoundFramebuffers = {};
  48976. let currentDrawbuffers = new WeakMap();
  48977. let defaultDrawbuffers = [];
  48978. let currentProgram = null;
  48979. let currentBlendingEnabled = false;
  48980. let currentBlending = null;
  48981. let currentBlendEquation = null;
  48982. let currentBlendSrc = null;
  48983. let currentBlendDst = null;
  48984. let currentBlendEquationAlpha = null;
  48985. let currentBlendSrcAlpha = null;
  48986. let currentBlendDstAlpha = null;
  48987. let currentBlendColor = new Color( 0, 0, 0 );
  48988. let currentBlendAlpha = 0;
  48989. let currentPremultipledAlpha = false;
  48990. let currentFlipSided = null;
  48991. let currentCullFace = null;
  48992. let currentLineWidth = null;
  48993. let currentPolygonOffsetFactor = null;
  48994. let currentPolygonOffsetUnits = null;
  48995. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48996. let lineWidthAvailable = false;
  48997. let version = 0;
  48998. const glVersion = gl.getParameter( gl.VERSION );
  48999. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  49000. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  49001. lineWidthAvailable = ( version >= 1.0 );
  49002. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  49003. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  49004. lineWidthAvailable = ( version >= 2.0 );
  49005. }
  49006. let currentTextureSlot = null;
  49007. let currentBoundTextures = {};
  49008. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  49009. const viewportParam = gl.getParameter( gl.VIEWPORT );
  49010. const currentScissor = new Vector4().fromArray( scissorParam );
  49011. const currentViewport = new Vector4().fromArray( viewportParam );
  49012. function createTexture( type, target, count, dimensions ) {
  49013. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  49014. const texture = gl.createTexture();
  49015. gl.bindTexture( type, texture );
  49016. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  49017. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  49018. for ( let i = 0; i < count; i ++ ) {
  49019. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  49020. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49021. } else {
  49022. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49023. }
  49024. }
  49025. return texture;
  49026. }
  49027. const emptyTextures = {};
  49028. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  49029. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  49030. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  49031. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  49032. // init
  49033. colorBuffer.setClear( 0, 0, 0, 1 );
  49034. depthBuffer.setClear( 1 );
  49035. stencilBuffer.setClear( 0 );
  49036. enable( gl.DEPTH_TEST );
  49037. depthBuffer.setFunc( LessEqualDepth );
  49038. setFlipSided( false );
  49039. setCullFace( CullFaceBack );
  49040. enable( gl.CULL_FACE );
  49041. setBlending( NoBlending );
  49042. //
  49043. function enable( id ) {
  49044. if ( enabledCapabilities[ id ] !== true ) {
  49045. gl.enable( id );
  49046. enabledCapabilities[ id ] = true;
  49047. }
  49048. }
  49049. function disable( id ) {
  49050. if ( enabledCapabilities[ id ] !== false ) {
  49051. gl.disable( id );
  49052. enabledCapabilities[ id ] = false;
  49053. }
  49054. }
  49055. function bindFramebuffer( target, framebuffer ) {
  49056. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  49057. gl.bindFramebuffer( target, framebuffer );
  49058. currentBoundFramebuffers[ target ] = framebuffer;
  49059. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  49060. if ( target === gl.DRAW_FRAMEBUFFER ) {
  49061. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  49062. }
  49063. if ( target === gl.FRAMEBUFFER ) {
  49064. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  49065. }
  49066. return true;
  49067. }
  49068. return false;
  49069. }
  49070. function drawBuffers( renderTarget, framebuffer ) {
  49071. let drawBuffers = defaultDrawbuffers;
  49072. let needsUpdate = false;
  49073. if ( renderTarget ) {
  49074. drawBuffers = currentDrawbuffers.get( framebuffer );
  49075. if ( drawBuffers === undefined ) {
  49076. drawBuffers = [];
  49077. currentDrawbuffers.set( framebuffer, drawBuffers );
  49078. }
  49079. const textures = renderTarget.textures;
  49080. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  49081. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49082. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  49083. }
  49084. drawBuffers.length = textures.length;
  49085. needsUpdate = true;
  49086. }
  49087. } else {
  49088. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  49089. drawBuffers[ 0 ] = gl.BACK;
  49090. needsUpdate = true;
  49091. }
  49092. }
  49093. if ( needsUpdate ) {
  49094. gl.drawBuffers( drawBuffers );
  49095. }
  49096. }
  49097. function useProgram( program ) {
  49098. if ( currentProgram !== program ) {
  49099. gl.useProgram( program );
  49100. currentProgram = program;
  49101. return true;
  49102. }
  49103. return false;
  49104. }
  49105. const equationToGL = {
  49106. [ AddEquation ]: gl.FUNC_ADD,
  49107. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  49108. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  49109. };
  49110. equationToGL[ MinEquation ] = gl.MIN;
  49111. equationToGL[ MaxEquation ] = gl.MAX;
  49112. const factorToGL = {
  49113. [ ZeroFactor ]: gl.ZERO,
  49114. [ OneFactor ]: gl.ONE,
  49115. [ SrcColorFactor ]: gl.SRC_COLOR,
  49116. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  49117. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  49118. [ DstColorFactor ]: gl.DST_COLOR,
  49119. [ DstAlphaFactor ]: gl.DST_ALPHA,
  49120. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  49121. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  49122. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  49123. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  49124. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  49125. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  49126. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  49127. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  49128. };
  49129. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  49130. if ( blending === NoBlending ) {
  49131. if ( currentBlendingEnabled === true ) {
  49132. disable( gl.BLEND );
  49133. currentBlendingEnabled = false;
  49134. }
  49135. return;
  49136. }
  49137. if ( currentBlendingEnabled === false ) {
  49138. enable( gl.BLEND );
  49139. currentBlendingEnabled = true;
  49140. }
  49141. if ( blending !== CustomBlending ) {
  49142. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  49143. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  49144. gl.blendEquation( gl.FUNC_ADD );
  49145. currentBlendEquation = AddEquation;
  49146. currentBlendEquationAlpha = AddEquation;
  49147. }
  49148. if ( premultipliedAlpha ) {
  49149. switch ( blending ) {
  49150. case NormalBlending:
  49151. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49152. break;
  49153. case AdditiveBlending:
  49154. gl.blendFunc( gl.ONE, gl.ONE );
  49155. break;
  49156. case SubtractiveBlending:
  49157. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  49158. break;
  49159. case MultiplyBlending:
  49160. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  49161. break;
  49162. default:
  49163. error( 'WebGLState: Invalid blending: ', blending );
  49164. break;
  49165. }
  49166. } else {
  49167. switch ( blending ) {
  49168. case NormalBlending:
  49169. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49170. break;
  49171. case AdditiveBlending:
  49172. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  49173. break;
  49174. case SubtractiveBlending:
  49175. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49176. break;
  49177. case MultiplyBlending:
  49178. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  49179. break;
  49180. default:
  49181. error( 'WebGLState: Invalid blending: ', blending );
  49182. break;
  49183. }
  49184. }
  49185. currentBlendSrc = null;
  49186. currentBlendDst = null;
  49187. currentBlendSrcAlpha = null;
  49188. currentBlendDstAlpha = null;
  49189. currentBlendColor.set( 0, 0, 0 );
  49190. currentBlendAlpha = 0;
  49191. currentBlending = blending;
  49192. currentPremultipledAlpha = premultipliedAlpha;
  49193. }
  49194. return;
  49195. }
  49196. // custom blending
  49197. blendEquationAlpha = blendEquationAlpha || blendEquation;
  49198. blendSrcAlpha = blendSrcAlpha || blendSrc;
  49199. blendDstAlpha = blendDstAlpha || blendDst;
  49200. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  49201. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  49202. currentBlendEquation = blendEquation;
  49203. currentBlendEquationAlpha = blendEquationAlpha;
  49204. }
  49205. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  49206. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  49207. currentBlendSrc = blendSrc;
  49208. currentBlendDst = blendDst;
  49209. currentBlendSrcAlpha = blendSrcAlpha;
  49210. currentBlendDstAlpha = blendDstAlpha;
  49211. }
  49212. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  49213. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  49214. currentBlendColor.copy( blendColor );
  49215. currentBlendAlpha = blendAlpha;
  49216. }
  49217. currentBlending = blending;
  49218. currentPremultipledAlpha = false;
  49219. }
  49220. function setMaterial( material, frontFaceCW ) {
  49221. material.side === DoubleSide
  49222. ? disable( gl.CULL_FACE )
  49223. : enable( gl.CULL_FACE );
  49224. let flipSided = ( material.side === BackSide );
  49225. if ( frontFaceCW ) flipSided = ! flipSided;
  49226. setFlipSided( flipSided );
  49227. ( material.blending === NormalBlending && material.transparent === false )
  49228. ? setBlending( NoBlending )
  49229. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  49230. depthBuffer.setFunc( material.depthFunc );
  49231. depthBuffer.setTest( material.depthTest );
  49232. depthBuffer.setMask( material.depthWrite );
  49233. colorBuffer.setMask( material.colorWrite );
  49234. const stencilWrite = material.stencilWrite;
  49235. stencilBuffer.setTest( stencilWrite );
  49236. if ( stencilWrite ) {
  49237. stencilBuffer.setMask( material.stencilWriteMask );
  49238. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  49239. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  49240. }
  49241. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  49242. material.alphaToCoverage === true
  49243. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  49244. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49245. }
  49246. //
  49247. function setFlipSided( flipSided ) {
  49248. if ( currentFlipSided !== flipSided ) {
  49249. if ( flipSided ) {
  49250. gl.frontFace( gl.CW );
  49251. } else {
  49252. gl.frontFace( gl.CCW );
  49253. }
  49254. currentFlipSided = flipSided;
  49255. }
  49256. }
  49257. function setCullFace( cullFace ) {
  49258. if ( cullFace !== CullFaceNone ) {
  49259. enable( gl.CULL_FACE );
  49260. if ( cullFace !== currentCullFace ) {
  49261. if ( cullFace === CullFaceBack ) {
  49262. gl.cullFace( gl.BACK );
  49263. } else if ( cullFace === CullFaceFront ) {
  49264. gl.cullFace( gl.FRONT );
  49265. } else {
  49266. gl.cullFace( gl.FRONT_AND_BACK );
  49267. }
  49268. }
  49269. } else {
  49270. disable( gl.CULL_FACE );
  49271. }
  49272. currentCullFace = cullFace;
  49273. }
  49274. function setLineWidth( width ) {
  49275. if ( width !== currentLineWidth ) {
  49276. if ( lineWidthAvailable ) gl.lineWidth( width );
  49277. currentLineWidth = width;
  49278. }
  49279. }
  49280. function setPolygonOffset( polygonOffset, factor, units ) {
  49281. if ( polygonOffset ) {
  49282. enable( gl.POLYGON_OFFSET_FILL );
  49283. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  49284. gl.polygonOffset( factor, units );
  49285. currentPolygonOffsetFactor = factor;
  49286. currentPolygonOffsetUnits = units;
  49287. }
  49288. } else {
  49289. disable( gl.POLYGON_OFFSET_FILL );
  49290. }
  49291. }
  49292. function setScissorTest( scissorTest ) {
  49293. if ( scissorTest ) {
  49294. enable( gl.SCISSOR_TEST );
  49295. } else {
  49296. disable( gl.SCISSOR_TEST );
  49297. }
  49298. }
  49299. // texture
  49300. function activeTexture( webglSlot ) {
  49301. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49302. if ( currentTextureSlot !== webglSlot ) {
  49303. gl.activeTexture( webglSlot );
  49304. currentTextureSlot = webglSlot;
  49305. }
  49306. }
  49307. function bindTexture( webglType, webglTexture, webglSlot ) {
  49308. if ( webglSlot === undefined ) {
  49309. if ( currentTextureSlot === null ) {
  49310. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49311. } else {
  49312. webglSlot = currentTextureSlot;
  49313. }
  49314. }
  49315. let boundTexture = currentBoundTextures[ webglSlot ];
  49316. if ( boundTexture === undefined ) {
  49317. boundTexture = { type: undefined, texture: undefined };
  49318. currentBoundTextures[ webglSlot ] = boundTexture;
  49319. }
  49320. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49321. if ( currentTextureSlot !== webglSlot ) {
  49322. gl.activeTexture( webglSlot );
  49323. currentTextureSlot = webglSlot;
  49324. }
  49325. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49326. boundTexture.type = webglType;
  49327. boundTexture.texture = webglTexture;
  49328. }
  49329. }
  49330. function unbindTexture() {
  49331. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49332. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49333. gl.bindTexture( boundTexture.type, null );
  49334. boundTexture.type = undefined;
  49335. boundTexture.texture = undefined;
  49336. }
  49337. }
  49338. function compressedTexImage2D() {
  49339. try {
  49340. gl.compressedTexImage2D( ...arguments );
  49341. } catch ( e ) {
  49342. error( 'WebGLState:', e );
  49343. }
  49344. }
  49345. function compressedTexImage3D() {
  49346. try {
  49347. gl.compressedTexImage3D( ...arguments );
  49348. } catch ( e ) {
  49349. error( 'WebGLState:', e );
  49350. }
  49351. }
  49352. function texSubImage2D() {
  49353. try {
  49354. gl.texSubImage2D( ...arguments );
  49355. } catch ( e ) {
  49356. error( 'WebGLState:', e );
  49357. }
  49358. }
  49359. function texSubImage3D() {
  49360. try {
  49361. gl.texSubImage3D( ...arguments );
  49362. } catch ( e ) {
  49363. error( 'WebGLState:', e );
  49364. }
  49365. }
  49366. function compressedTexSubImage2D() {
  49367. try {
  49368. gl.compressedTexSubImage2D( ...arguments );
  49369. } catch ( e ) {
  49370. error( 'WebGLState:', e );
  49371. }
  49372. }
  49373. function compressedTexSubImage3D() {
  49374. try {
  49375. gl.compressedTexSubImage3D( ...arguments );
  49376. } catch ( e ) {
  49377. error( 'WebGLState:', e );
  49378. }
  49379. }
  49380. function texStorage2D() {
  49381. try {
  49382. gl.texStorage2D( ...arguments );
  49383. } catch ( e ) {
  49384. error( 'WebGLState:', e );
  49385. }
  49386. }
  49387. function texStorage3D() {
  49388. try {
  49389. gl.texStorage3D( ...arguments );
  49390. } catch ( e ) {
  49391. error( 'WebGLState:', e );
  49392. }
  49393. }
  49394. function texImage2D() {
  49395. try {
  49396. gl.texImage2D( ...arguments );
  49397. } catch ( e ) {
  49398. error( 'WebGLState:', e );
  49399. }
  49400. }
  49401. function texImage3D() {
  49402. try {
  49403. gl.texImage3D( ...arguments );
  49404. } catch ( e ) {
  49405. error( 'WebGLState:', e );
  49406. }
  49407. }
  49408. //
  49409. function scissor( scissor ) {
  49410. if ( currentScissor.equals( scissor ) === false ) {
  49411. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49412. currentScissor.copy( scissor );
  49413. }
  49414. }
  49415. function viewport( viewport ) {
  49416. if ( currentViewport.equals( viewport ) === false ) {
  49417. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49418. currentViewport.copy( viewport );
  49419. }
  49420. }
  49421. function updateUBOMapping( uniformsGroup, program ) {
  49422. let mapping = uboProgramMap.get( program );
  49423. if ( mapping === undefined ) {
  49424. mapping = new WeakMap();
  49425. uboProgramMap.set( program, mapping );
  49426. }
  49427. let blockIndex = mapping.get( uniformsGroup );
  49428. if ( blockIndex === undefined ) {
  49429. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49430. mapping.set( uniformsGroup, blockIndex );
  49431. }
  49432. }
  49433. function uniformBlockBinding( uniformsGroup, program ) {
  49434. const mapping = uboProgramMap.get( program );
  49435. const blockIndex = mapping.get( uniformsGroup );
  49436. if ( uboBindings.get( program ) !== blockIndex ) {
  49437. // bind shader specific block index to global block point
  49438. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49439. uboBindings.set( program, blockIndex );
  49440. }
  49441. }
  49442. //
  49443. function reset() {
  49444. // reset state
  49445. gl.disable( gl.BLEND );
  49446. gl.disable( gl.CULL_FACE );
  49447. gl.disable( gl.DEPTH_TEST );
  49448. gl.disable( gl.POLYGON_OFFSET_FILL );
  49449. gl.disable( gl.SCISSOR_TEST );
  49450. gl.disable( gl.STENCIL_TEST );
  49451. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49452. gl.blendEquation( gl.FUNC_ADD );
  49453. gl.blendFunc( gl.ONE, gl.ZERO );
  49454. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49455. gl.blendColor( 0, 0, 0, 0 );
  49456. gl.colorMask( true, true, true, true );
  49457. gl.clearColor( 0, 0, 0, 0 );
  49458. gl.depthMask( true );
  49459. gl.depthFunc( gl.LESS );
  49460. depthBuffer.setReversed( false );
  49461. gl.clearDepth( 1 );
  49462. gl.stencilMask( 0xffffffff );
  49463. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49464. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49465. gl.clearStencil( 0 );
  49466. gl.cullFace( gl.BACK );
  49467. gl.frontFace( gl.CCW );
  49468. gl.polygonOffset( 0, 0 );
  49469. gl.activeTexture( gl.TEXTURE0 );
  49470. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49471. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49472. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49473. gl.useProgram( null );
  49474. gl.lineWidth( 1 );
  49475. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49476. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49477. // reset internals
  49478. enabledCapabilities = {};
  49479. currentTextureSlot = null;
  49480. currentBoundTextures = {};
  49481. currentBoundFramebuffers = {};
  49482. currentDrawbuffers = new WeakMap();
  49483. defaultDrawbuffers = [];
  49484. currentProgram = null;
  49485. currentBlendingEnabled = false;
  49486. currentBlending = null;
  49487. currentBlendEquation = null;
  49488. currentBlendSrc = null;
  49489. currentBlendDst = null;
  49490. currentBlendEquationAlpha = null;
  49491. currentBlendSrcAlpha = null;
  49492. currentBlendDstAlpha = null;
  49493. currentBlendColor = new Color( 0, 0, 0 );
  49494. currentBlendAlpha = 0;
  49495. currentPremultipledAlpha = false;
  49496. currentFlipSided = null;
  49497. currentCullFace = null;
  49498. currentLineWidth = null;
  49499. currentPolygonOffsetFactor = null;
  49500. currentPolygonOffsetUnits = null;
  49501. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49502. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49503. colorBuffer.reset();
  49504. depthBuffer.reset();
  49505. stencilBuffer.reset();
  49506. }
  49507. return {
  49508. buffers: {
  49509. color: colorBuffer,
  49510. depth: depthBuffer,
  49511. stencil: stencilBuffer
  49512. },
  49513. enable: enable,
  49514. disable: disable,
  49515. bindFramebuffer: bindFramebuffer,
  49516. drawBuffers: drawBuffers,
  49517. useProgram: useProgram,
  49518. setBlending: setBlending,
  49519. setMaterial: setMaterial,
  49520. setFlipSided: setFlipSided,
  49521. setCullFace: setCullFace,
  49522. setLineWidth: setLineWidth,
  49523. setPolygonOffset: setPolygonOffset,
  49524. setScissorTest: setScissorTest,
  49525. activeTexture: activeTexture,
  49526. bindTexture: bindTexture,
  49527. unbindTexture: unbindTexture,
  49528. compressedTexImage2D: compressedTexImage2D,
  49529. compressedTexImage3D: compressedTexImage3D,
  49530. texImage2D: texImage2D,
  49531. texImage3D: texImage3D,
  49532. updateUBOMapping: updateUBOMapping,
  49533. uniformBlockBinding: uniformBlockBinding,
  49534. texStorage2D: texStorage2D,
  49535. texStorage3D: texStorage3D,
  49536. texSubImage2D: texSubImage2D,
  49537. texSubImage3D: texSubImage3D,
  49538. compressedTexSubImage2D: compressedTexSubImage2D,
  49539. compressedTexSubImage3D: compressedTexSubImage3D,
  49540. scissor: scissor,
  49541. viewport: viewport,
  49542. reset: reset
  49543. };
  49544. }
  49545. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49546. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49547. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49548. const _imageDimensions = new Vector2();
  49549. const _videoTextures = new WeakMap();
  49550. let _canvas;
  49551. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49552. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49553. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49554. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49555. let useOffscreenCanvas = false;
  49556. try {
  49557. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49558. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49559. } catch ( err ) {
  49560. // Ignore any errors
  49561. }
  49562. function createCanvas( width, height ) {
  49563. // Use OffscreenCanvas when available. Specially needed in web workers
  49564. return useOffscreenCanvas ?
  49565. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49566. }
  49567. function resizeImage( image, needsNewCanvas, maxSize ) {
  49568. let scale = 1;
  49569. const dimensions = getDimensions( image );
  49570. // handle case if texture exceeds max size
  49571. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49572. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49573. }
  49574. // only perform resize if necessary
  49575. if ( scale < 1 ) {
  49576. // only perform resize for certain image types
  49577. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49578. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49579. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49580. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49581. const width = Math.floor( scale * dimensions.width );
  49582. const height = Math.floor( scale * dimensions.height );
  49583. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49584. // cube textures can't reuse the same canvas
  49585. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49586. canvas.width = width;
  49587. canvas.height = height;
  49588. const context = canvas.getContext( '2d' );
  49589. context.drawImage( image, 0, 0, width, height );
  49590. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49591. return canvas;
  49592. } else {
  49593. if ( 'data' in image ) {
  49594. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49595. }
  49596. return image;
  49597. }
  49598. }
  49599. return image;
  49600. }
  49601. function textureNeedsGenerateMipmaps( texture ) {
  49602. return texture.generateMipmaps;
  49603. }
  49604. function generateMipmap( target ) {
  49605. _gl.generateMipmap( target );
  49606. }
  49607. function getTargetType( texture ) {
  49608. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49609. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49610. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49611. return _gl.TEXTURE_2D;
  49612. }
  49613. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49614. if ( internalFormatName !== null ) {
  49615. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49616. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49617. }
  49618. let internalFormat = glFormat;
  49619. if ( glFormat === _gl.RED ) {
  49620. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49621. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49622. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49623. }
  49624. if ( glFormat === _gl.RED_INTEGER ) {
  49625. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49626. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  49627. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  49628. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  49629. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  49630. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  49631. }
  49632. if ( glFormat === _gl.RG ) {
  49633. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  49634. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  49635. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  49636. }
  49637. if ( glFormat === _gl.RG_INTEGER ) {
  49638. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  49639. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  49640. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  49641. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  49642. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  49643. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  49644. }
  49645. if ( glFormat === _gl.RGB_INTEGER ) {
  49646. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  49647. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  49648. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  49649. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  49650. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  49651. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  49652. }
  49653. if ( glFormat === _gl.RGBA_INTEGER ) {
  49654. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  49655. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  49656. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  49657. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  49658. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  49659. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  49660. }
  49661. if ( glFormat === _gl.RGB ) {
  49662. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  49663. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  49664. }
  49665. if ( glFormat === _gl.RGBA ) {
  49666. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49667. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  49668. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  49669. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  49670. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  49671. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  49672. }
  49673. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  49674. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  49675. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  49676. extensions.get( 'EXT_color_buffer_float' );
  49677. }
  49678. return internalFormat;
  49679. }
  49680. function getInternalDepthFormat( useStencil, depthType ) {
  49681. let glInternalFormat;
  49682. if ( useStencil ) {
  49683. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49684. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49685. } else if ( depthType === FloatType ) {
  49686. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  49687. } else if ( depthType === UnsignedShortType ) {
  49688. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49689. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49690. }
  49691. } else {
  49692. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49693. glInternalFormat = _gl.DEPTH_COMPONENT24;
  49694. } else if ( depthType === FloatType ) {
  49695. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  49696. } else if ( depthType === UnsignedShortType ) {
  49697. glInternalFormat = _gl.DEPTH_COMPONENT16;
  49698. }
  49699. }
  49700. return glInternalFormat;
  49701. }
  49702. function getMipLevels( texture, image ) {
  49703. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  49704. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  49705. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  49706. // user-defined mipmaps
  49707. return texture.mipmaps.length;
  49708. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  49709. return image.mipmaps.length;
  49710. } else {
  49711. // texture without mipmaps (only base level)
  49712. return 1;
  49713. }
  49714. }
  49715. //
  49716. function onTextureDispose( event ) {
  49717. const texture = event.target;
  49718. texture.removeEventListener( 'dispose', onTextureDispose );
  49719. deallocateTexture( texture );
  49720. if ( texture.isVideoTexture ) {
  49721. _videoTextures.delete( texture );
  49722. }
  49723. }
  49724. function onRenderTargetDispose( event ) {
  49725. const renderTarget = event.target;
  49726. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49727. deallocateRenderTarget( renderTarget );
  49728. }
  49729. //
  49730. function deallocateTexture( texture ) {
  49731. const textureProperties = properties.get( texture );
  49732. if ( textureProperties.__webglInit === undefined ) return;
  49733. // check if it's necessary to remove the WebGLTexture object
  49734. const source = texture.source;
  49735. const webglTextures = _sources.get( source );
  49736. if ( webglTextures ) {
  49737. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49738. webglTexture.usedTimes --;
  49739. // the WebGLTexture object is not used anymore, remove it
  49740. if ( webglTexture.usedTimes === 0 ) {
  49741. deleteTexture( texture );
  49742. }
  49743. // remove the weak map entry if no WebGLTexture uses the source anymore
  49744. if ( Object.keys( webglTextures ).length === 0 ) {
  49745. _sources.delete( source );
  49746. }
  49747. }
  49748. properties.remove( texture );
  49749. }
  49750. function deleteTexture( texture ) {
  49751. const textureProperties = properties.get( texture );
  49752. _gl.deleteTexture( textureProperties.__webglTexture );
  49753. const source = texture.source;
  49754. const webglTextures = _sources.get( source );
  49755. delete webglTextures[ textureProperties.__cacheKey ];
  49756. info.memory.textures --;
  49757. }
  49758. function deallocateRenderTarget( renderTarget ) {
  49759. const renderTargetProperties = properties.get( renderTarget );
  49760. if ( renderTarget.depthTexture ) {
  49761. renderTarget.depthTexture.dispose();
  49762. properties.remove( renderTarget.depthTexture );
  49763. }
  49764. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49765. for ( let i = 0; i < 6; i ++ ) {
  49766. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49767. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49768. } else {
  49769. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49770. }
  49771. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49772. }
  49773. } else {
  49774. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49775. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49776. } else {
  49777. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49778. }
  49779. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49780. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49781. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49782. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49783. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49784. }
  49785. }
  49786. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49787. }
  49788. const textures = renderTarget.textures;
  49789. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49790. const attachmentProperties = properties.get( textures[ i ] );
  49791. if ( attachmentProperties.__webglTexture ) {
  49792. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49793. info.memory.textures --;
  49794. }
  49795. properties.remove( textures[ i ] );
  49796. }
  49797. properties.remove( renderTarget );
  49798. }
  49799. //
  49800. let textureUnits = 0;
  49801. function resetTextureUnits() {
  49802. textureUnits = 0;
  49803. }
  49804. function allocateTextureUnit() {
  49805. const textureUnit = textureUnits;
  49806. if ( textureUnit >= capabilities.maxTextures ) {
  49807. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49808. }
  49809. textureUnits += 1;
  49810. return textureUnit;
  49811. }
  49812. function getTextureCacheKey( texture ) {
  49813. const array = [];
  49814. array.push( texture.wrapS );
  49815. array.push( texture.wrapT );
  49816. array.push( texture.wrapR || 0 );
  49817. array.push( texture.magFilter );
  49818. array.push( texture.minFilter );
  49819. array.push( texture.anisotropy );
  49820. array.push( texture.internalFormat );
  49821. array.push( texture.format );
  49822. array.push( texture.type );
  49823. array.push( texture.generateMipmaps );
  49824. array.push( texture.premultiplyAlpha );
  49825. array.push( texture.flipY );
  49826. array.push( texture.unpackAlignment );
  49827. array.push( texture.colorSpace );
  49828. return array.join();
  49829. }
  49830. //
  49831. function setTexture2D( texture, slot ) {
  49832. const textureProperties = properties.get( texture );
  49833. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49834. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49835. const image = texture.image;
  49836. if ( image === null ) {
  49837. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  49838. } else if ( image.complete === false ) {
  49839. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  49840. } else {
  49841. uploadTexture( textureProperties, texture, slot );
  49842. return;
  49843. }
  49844. } else if ( texture.isExternalTexture ) {
  49845. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49846. }
  49847. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49848. }
  49849. function setTexture2DArray( texture, slot ) {
  49850. const textureProperties = properties.get( texture );
  49851. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49852. uploadTexture( textureProperties, texture, slot );
  49853. return;
  49854. } else if ( texture.isExternalTexture ) {
  49855. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49856. }
  49857. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49858. }
  49859. function setTexture3D( texture, slot ) {
  49860. const textureProperties = properties.get( texture );
  49861. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49862. uploadTexture( textureProperties, texture, slot );
  49863. return;
  49864. }
  49865. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49866. }
  49867. function setTextureCube( texture, slot ) {
  49868. const textureProperties = properties.get( texture );
  49869. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49870. uploadCubeTexture( textureProperties, texture, slot );
  49871. return;
  49872. }
  49873. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49874. }
  49875. const wrappingToGL = {
  49876. [ RepeatWrapping ]: _gl.REPEAT,
  49877. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49878. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49879. };
  49880. const filterToGL = {
  49881. [ NearestFilter ]: _gl.NEAREST,
  49882. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49883. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49884. [ LinearFilter ]: _gl.LINEAR,
  49885. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49886. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49887. };
  49888. const compareToGL = {
  49889. [ NeverCompare ]: _gl.NEVER,
  49890. [ AlwaysCompare ]: _gl.ALWAYS,
  49891. [ LessCompare ]: _gl.LESS,
  49892. [ LessEqualCompare ]: _gl.LEQUAL,
  49893. [ EqualCompare ]: _gl.EQUAL,
  49894. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49895. [ GreaterCompare ]: _gl.GREATER,
  49896. [ NotEqualCompare ]: _gl.NOTEQUAL
  49897. };
  49898. function setTextureParameters( textureType, texture ) {
  49899. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49900. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49901. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49902. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49903. }
  49904. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49905. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49906. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49907. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49908. }
  49909. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49910. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49911. if ( texture.compareFunction ) {
  49912. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49913. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49914. }
  49915. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49916. if ( texture.magFilter === NearestFilter ) return;
  49917. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49918. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49919. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49920. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49921. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49922. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49923. }
  49924. }
  49925. }
  49926. function initTexture( textureProperties, texture ) {
  49927. let forceUpload = false;
  49928. if ( textureProperties.__webglInit === undefined ) {
  49929. textureProperties.__webglInit = true;
  49930. texture.addEventListener( 'dispose', onTextureDispose );
  49931. }
  49932. // create Source <-> WebGLTextures mapping if necessary
  49933. const source = texture.source;
  49934. let webglTextures = _sources.get( source );
  49935. if ( webglTextures === undefined ) {
  49936. webglTextures = {};
  49937. _sources.set( source, webglTextures );
  49938. }
  49939. // check if there is already a WebGLTexture object for the given texture parameters
  49940. const textureCacheKey = getTextureCacheKey( texture );
  49941. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49942. // if not, create a new instance of WebGLTexture
  49943. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49944. // create new entry
  49945. webglTextures[ textureCacheKey ] = {
  49946. texture: _gl.createTexture(),
  49947. usedTimes: 0
  49948. };
  49949. info.memory.textures ++;
  49950. // when a new instance of WebGLTexture was created, a texture upload is required
  49951. // even if the image contents are identical
  49952. forceUpload = true;
  49953. }
  49954. webglTextures[ textureCacheKey ].usedTimes ++;
  49955. // every time the texture cache key changes, it's necessary to check if an instance of
  49956. // WebGLTexture can be deleted in order to avoid a memory leak.
  49957. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49958. if ( webglTexture !== undefined ) {
  49959. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49960. if ( webglTexture.usedTimes === 0 ) {
  49961. deleteTexture( texture );
  49962. }
  49963. }
  49964. // store references to cache key and WebGLTexture object
  49965. textureProperties.__cacheKey = textureCacheKey;
  49966. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49967. }
  49968. return forceUpload;
  49969. }
  49970. function getRow( index, rowLength, componentStride ) {
  49971. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49972. }
  49973. function updateTexture( texture, image, glFormat, glType ) {
  49974. const componentStride = 4; // only RGBA supported
  49975. const updateRanges = texture.updateRanges;
  49976. if ( updateRanges.length === 0 ) {
  49977. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49978. } else {
  49979. // Before applying update ranges, we merge any adjacent / overlapping
  49980. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49981. // to performance improvements for applications which make heavy use of
  49982. // update ranges. Likely due to GPU command overhead.
  49983. //
  49984. // Note that to reduce garbage collection between frames, we merge the
  49985. // update ranges in-place. This is safe because this method will clear the
  49986. // update ranges once updated.
  49987. updateRanges.sort( ( a, b ) => a.start - b.start );
  49988. // To merge the update ranges in-place, we work from left to right in the
  49989. // existing updateRanges array, merging ranges. This may result in a final
  49990. // array which is smaller than the original. This index tracks the last
  49991. // index representing a merged range, any data after this index can be
  49992. // trimmed once the merge algorithm is completed.
  49993. let mergeIndex = 0;
  49994. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49995. const previousRange = updateRanges[ mergeIndex ];
  49996. const range = updateRanges[ i ];
  49997. // Only merge if in the same row and overlapping/adjacent
  49998. const previousEnd = previousRange.start + previousRange.count;
  49999. const currentRow = getRow( range.start, image.width, componentStride );
  50000. const previousRow = getRow( previousRange.start, image.width, componentStride );
  50001. // We add one here to merge adjacent ranges. This is safe because ranges
  50002. // operate over positive integers.
  50003. if (
  50004. range.start <= previousEnd + 1 &&
  50005. currentRow === previousRow &&
  50006. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  50007. ) {
  50008. previousRange.count = Math.max(
  50009. previousRange.count,
  50010. range.start + range.count - previousRange.start
  50011. );
  50012. } else {
  50013. ++ mergeIndex;
  50014. updateRanges[ mergeIndex ] = range;
  50015. }
  50016. }
  50017. // Trim the array to only contain the merged ranges.
  50018. updateRanges.length = mergeIndex + 1;
  50019. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  50020. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  50021. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  50022. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  50023. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50024. const range = updateRanges[ i ];
  50025. const pixelStart = Math.floor( range.start / componentStride );
  50026. const pixelCount = Math.ceil( range.count / componentStride );
  50027. const x = pixelStart % image.width;
  50028. const y = Math.floor( pixelStart / image.width );
  50029. // Assumes update ranges refer to contiguous memory
  50030. const width = pixelCount;
  50031. const height = 1;
  50032. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  50033. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  50034. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  50035. }
  50036. texture.clearUpdateRanges();
  50037. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  50038. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  50039. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  50040. }
  50041. }
  50042. function uploadTexture( textureProperties, texture, slot ) {
  50043. let textureType = _gl.TEXTURE_2D;
  50044. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  50045. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  50046. const forceUpload = initTexture( textureProperties, texture );
  50047. const source = texture.source;
  50048. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50049. const sourceProperties = properties.get( source );
  50050. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50051. state.activeTexture( _gl.TEXTURE0 + slot );
  50052. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50053. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50054. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50055. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50056. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50057. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50058. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50059. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  50060. image = verifyColorSpace( texture, image );
  50061. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50062. const glType = utils.convert( texture.type );
  50063. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  50064. setTextureParameters( textureType, texture );
  50065. let mipmap;
  50066. const mipmaps = texture.mipmaps;
  50067. const useTexStorage = ( texture.isVideoTexture !== true );
  50068. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50069. const dataReady = source.dataReady;
  50070. const levels = getMipLevels( texture, image );
  50071. if ( texture.isDepthTexture ) {
  50072. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  50073. //
  50074. if ( allocateMemory ) {
  50075. if ( useTexStorage ) {
  50076. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  50077. } else {
  50078. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  50079. }
  50080. }
  50081. } else if ( texture.isDataTexture ) {
  50082. // use manually created mipmaps if available
  50083. // if there are no manual mipmaps
  50084. // set 0 level mipmap and then use GL to generate other mipmap levels
  50085. if ( mipmaps.length > 0 ) {
  50086. if ( useTexStorage && allocateMemory ) {
  50087. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50088. }
  50089. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50090. mipmap = mipmaps[ i ];
  50091. if ( useTexStorage ) {
  50092. if ( dataReady ) {
  50093. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50094. }
  50095. } else {
  50096. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50097. }
  50098. }
  50099. texture.generateMipmaps = false;
  50100. } else {
  50101. if ( useTexStorage ) {
  50102. if ( allocateMemory ) {
  50103. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50104. }
  50105. if ( dataReady ) {
  50106. updateTexture( texture, image, glFormat, glType );
  50107. }
  50108. } else {
  50109. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  50110. }
  50111. }
  50112. } else if ( texture.isCompressedTexture ) {
  50113. if ( texture.isCompressedArrayTexture ) {
  50114. if ( useTexStorage && allocateMemory ) {
  50115. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  50116. }
  50117. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50118. mipmap = mipmaps[ i ];
  50119. if ( texture.format !== RGBAFormat ) {
  50120. if ( glFormat !== null ) {
  50121. if ( useTexStorage ) {
  50122. if ( dataReady ) {
  50123. if ( texture.layerUpdates.size > 0 ) {
  50124. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  50125. for ( const layerIndex of texture.layerUpdates ) {
  50126. const layerData = mipmap.data.subarray(
  50127. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  50128. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  50129. );
  50130. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  50131. }
  50132. texture.clearLayerUpdates();
  50133. } else {
  50134. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  50135. }
  50136. }
  50137. } else {
  50138. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  50139. }
  50140. } else {
  50141. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50142. }
  50143. } else {
  50144. if ( useTexStorage ) {
  50145. if ( dataReady ) {
  50146. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  50147. }
  50148. } else {
  50149. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  50150. }
  50151. }
  50152. }
  50153. } else {
  50154. if ( useTexStorage && allocateMemory ) {
  50155. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50156. }
  50157. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50158. mipmap = mipmaps[ i ];
  50159. if ( texture.format !== RGBAFormat ) {
  50160. if ( glFormat !== null ) {
  50161. if ( useTexStorage ) {
  50162. if ( dataReady ) {
  50163. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50164. }
  50165. } else {
  50166. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50167. }
  50168. } else {
  50169. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50170. }
  50171. } else {
  50172. if ( useTexStorage ) {
  50173. if ( dataReady ) {
  50174. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50175. }
  50176. } else {
  50177. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50178. }
  50179. }
  50180. }
  50181. }
  50182. } else if ( texture.isDataArrayTexture ) {
  50183. if ( useTexStorage ) {
  50184. if ( allocateMemory ) {
  50185. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  50186. }
  50187. if ( dataReady ) {
  50188. if ( texture.layerUpdates.size > 0 ) {
  50189. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  50190. for ( const layerIndex of texture.layerUpdates ) {
  50191. const layerData = image.data.subarray(
  50192. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  50193. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  50194. );
  50195. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  50196. }
  50197. texture.clearLayerUpdates();
  50198. } else {
  50199. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50200. }
  50201. }
  50202. } else {
  50203. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50204. }
  50205. } else if ( texture.isData3DTexture ) {
  50206. if ( useTexStorage ) {
  50207. if ( allocateMemory ) {
  50208. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  50209. }
  50210. if ( dataReady ) {
  50211. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50212. }
  50213. } else {
  50214. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50215. }
  50216. } else if ( texture.isFramebufferTexture ) {
  50217. if ( allocateMemory ) {
  50218. if ( useTexStorage ) {
  50219. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50220. } else {
  50221. let width = image.width, height = image.height;
  50222. for ( let i = 0; i < levels; i ++ ) {
  50223. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  50224. width >>= 1;
  50225. height >>= 1;
  50226. }
  50227. }
  50228. }
  50229. } else {
  50230. // regular Texture (image, video, canvas)
  50231. // use manually created mipmaps if available
  50232. // if there are no manual mipmaps
  50233. // set 0 level mipmap and then use GL to generate other mipmap levels
  50234. if ( mipmaps.length > 0 ) {
  50235. if ( useTexStorage && allocateMemory ) {
  50236. const dimensions = getDimensions( mipmaps[ 0 ] );
  50237. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50238. }
  50239. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50240. mipmap = mipmaps[ i ];
  50241. if ( useTexStorage ) {
  50242. if ( dataReady ) {
  50243. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  50244. }
  50245. } else {
  50246. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  50247. }
  50248. }
  50249. texture.generateMipmaps = false;
  50250. } else {
  50251. if ( useTexStorage ) {
  50252. if ( allocateMemory ) {
  50253. const dimensions = getDimensions( image );
  50254. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50255. }
  50256. if ( dataReady ) {
  50257. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  50258. }
  50259. } else {
  50260. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  50261. }
  50262. }
  50263. }
  50264. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50265. generateMipmap( textureType );
  50266. }
  50267. sourceProperties.__version = source.version;
  50268. if ( texture.onUpdate ) texture.onUpdate( texture );
  50269. }
  50270. textureProperties.__version = texture.version;
  50271. }
  50272. function uploadCubeTexture( textureProperties, texture, slot ) {
  50273. if ( texture.image.length !== 6 ) return;
  50274. const forceUpload = initTexture( textureProperties, texture );
  50275. const source = texture.source;
  50276. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50277. const sourceProperties = properties.get( source );
  50278. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50279. state.activeTexture( _gl.TEXTURE0 + slot );
  50280. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50281. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50282. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50283. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50284. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50285. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50286. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50287. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  50288. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  50289. const cubeImage = [];
  50290. for ( let i = 0; i < 6; i ++ ) {
  50291. if ( ! isCompressed && ! isDataTexture ) {
  50292. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50293. } else {
  50294. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50295. }
  50296. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50297. }
  50298. const image = cubeImage[ 0 ],
  50299. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50300. glType = utils.convert( texture.type ),
  50301. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50302. const useTexStorage = ( texture.isVideoTexture !== true );
  50303. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50304. const dataReady = source.dataReady;
  50305. let levels = getMipLevels( texture, image );
  50306. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50307. let mipmaps;
  50308. if ( isCompressed ) {
  50309. if ( useTexStorage && allocateMemory ) {
  50310. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50311. }
  50312. for ( let i = 0; i < 6; i ++ ) {
  50313. mipmaps = cubeImage[ i ].mipmaps;
  50314. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50315. const mipmap = mipmaps[ j ];
  50316. if ( texture.format !== RGBAFormat ) {
  50317. if ( glFormat !== null ) {
  50318. if ( useTexStorage ) {
  50319. if ( dataReady ) {
  50320. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50321. }
  50322. } else {
  50323. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50324. }
  50325. } else {
  50326. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50327. }
  50328. } else {
  50329. if ( useTexStorage ) {
  50330. if ( dataReady ) {
  50331. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50332. }
  50333. } else {
  50334. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50335. }
  50336. }
  50337. }
  50338. }
  50339. } else {
  50340. mipmaps = texture.mipmaps;
  50341. if ( useTexStorage && allocateMemory ) {
  50342. // TODO: Uniformly handle mipmap definitions
  50343. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50344. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50345. if ( mipmaps.length > 0 ) levels ++;
  50346. const dimensions = getDimensions( cubeImage[ 0 ] );
  50347. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50348. }
  50349. for ( let i = 0; i < 6; i ++ ) {
  50350. if ( isDataTexture ) {
  50351. if ( useTexStorage ) {
  50352. if ( dataReady ) {
  50353. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50354. }
  50355. } else {
  50356. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50357. }
  50358. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50359. const mipmap = mipmaps[ j ];
  50360. const mipmapImage = mipmap.image[ i ].image;
  50361. if ( useTexStorage ) {
  50362. if ( dataReady ) {
  50363. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50364. }
  50365. } else {
  50366. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50367. }
  50368. }
  50369. } else {
  50370. if ( useTexStorage ) {
  50371. if ( dataReady ) {
  50372. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50373. }
  50374. } else {
  50375. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50376. }
  50377. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50378. const mipmap = mipmaps[ j ];
  50379. if ( useTexStorage ) {
  50380. if ( dataReady ) {
  50381. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50382. }
  50383. } else {
  50384. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50385. }
  50386. }
  50387. }
  50388. }
  50389. }
  50390. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50391. // We assume images for cube map have the same size.
  50392. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50393. }
  50394. sourceProperties.__version = source.version;
  50395. if ( texture.onUpdate ) texture.onUpdate( texture );
  50396. }
  50397. textureProperties.__version = texture.version;
  50398. }
  50399. // Render targets
  50400. // Setup storage for target texture and bind it to correct framebuffer
  50401. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50402. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50403. const glType = utils.convert( texture.type );
  50404. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50405. const renderTargetProperties = properties.get( renderTarget );
  50406. const textureProperties = properties.get( texture );
  50407. textureProperties.__renderTarget = renderTarget;
  50408. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50409. const width = Math.max( 1, renderTarget.width >> level );
  50410. const height = Math.max( 1, renderTarget.height >> level );
  50411. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50412. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50413. } else {
  50414. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50415. }
  50416. }
  50417. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50418. if ( useMultisampledRTT( renderTarget ) ) {
  50419. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50420. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50421. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50422. }
  50423. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50424. }
  50425. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50426. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  50427. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50428. if ( renderTarget.depthBuffer ) {
  50429. // retrieve the depth attachment types
  50430. const depthTexture = renderTarget.depthTexture;
  50431. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50432. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50433. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50434. // set up the attachment
  50435. if ( useMultisampledRTT( renderTarget ) ) {
  50436. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50437. } else if ( useMultisample ) {
  50438. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50439. } else {
  50440. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50441. }
  50442. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50443. } else {
  50444. const textures = renderTarget.textures;
  50445. for ( let i = 0; i < textures.length; i ++ ) {
  50446. const texture = textures[ i ];
  50447. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50448. const glType = utils.convert( texture.type );
  50449. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50450. if ( useMultisampledRTT( renderTarget ) ) {
  50451. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50452. } else if ( useMultisample ) {
  50453. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50454. } else {
  50455. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50456. }
  50457. }
  50458. }
  50459. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50460. }
  50461. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50462. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50463. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50464. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50465. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50466. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50467. }
  50468. const textureProperties = properties.get( renderTarget.depthTexture );
  50469. textureProperties.__renderTarget = renderTarget;
  50470. // upload an empty depth texture with framebuffer size
  50471. if ( ! textureProperties.__webglTexture ||
  50472. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50473. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50474. renderTarget.depthTexture.image.width = renderTarget.width;
  50475. renderTarget.depthTexture.image.height = renderTarget.height;
  50476. renderTarget.depthTexture.needsUpdate = true;
  50477. }
  50478. if ( isCube ) {
  50479. // For cube depth textures, initialize and bind without uploading image data
  50480. if ( textureProperties.__webglInit === undefined ) {
  50481. textureProperties.__webglInit = true;
  50482. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50483. }
  50484. // Only create and allocate storage once
  50485. if ( textureProperties.__webglTexture === undefined ) {
  50486. textureProperties.__webglTexture = _gl.createTexture();
  50487. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50488. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50489. // Allocate storage for all 6 faces with correct depth texture format
  50490. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50491. const glType = utils.convert( renderTarget.depthTexture.type );
  50492. // Use proper internal format for depth textures
  50493. let glInternalFormat;
  50494. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50495. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50496. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50497. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50498. }
  50499. for ( let i = 0; i < 6; i ++ ) {
  50500. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50501. }
  50502. }
  50503. } else {
  50504. setTexture2D( renderTarget.depthTexture, 0 );
  50505. }
  50506. const webglDepthTexture = textureProperties.__webglTexture;
  50507. const samples = getRenderTargetSamples( renderTarget );
  50508. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50509. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50510. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50511. if ( useMultisampledRTT( renderTarget ) ) {
  50512. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50513. } else {
  50514. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50515. }
  50516. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50517. if ( useMultisampledRTT( renderTarget ) ) {
  50518. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50519. } else {
  50520. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50521. }
  50522. } else {
  50523. throw new Error( 'Unknown depthTexture format' );
  50524. }
  50525. }
  50526. // Setup GL resources for a non-texture depth buffer
  50527. function setupDepthRenderbuffer( renderTarget ) {
  50528. const renderTargetProperties = properties.get( renderTarget );
  50529. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50530. // if the bound depth texture has changed
  50531. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50532. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50533. const depthTexture = renderTarget.depthTexture;
  50534. if ( renderTargetProperties.__depthDisposeCallback ) {
  50535. renderTargetProperties.__depthDisposeCallback();
  50536. }
  50537. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50538. if ( depthTexture ) {
  50539. const disposeEvent = () => {
  50540. delete renderTargetProperties.__boundDepthTexture;
  50541. delete renderTargetProperties.__depthDisposeCallback;
  50542. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50543. };
  50544. depthTexture.addEventListener( 'dispose', disposeEvent );
  50545. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50546. }
  50547. renderTargetProperties.__boundDepthTexture = depthTexture;
  50548. }
  50549. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50550. if ( isCube ) {
  50551. // For cube render targets with depth texture, setup each face
  50552. for ( let i = 0; i < 6; i ++ ) {
  50553. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50554. }
  50555. } else {
  50556. const mipmaps = renderTarget.texture.mipmaps;
  50557. if ( mipmaps && mipmaps.length > 0 ) {
  50558. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50559. } else {
  50560. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50561. }
  50562. }
  50563. } else {
  50564. if ( isCube ) {
  50565. renderTargetProperties.__webglDepthbuffer = [];
  50566. for ( let i = 0; i < 6; i ++ ) {
  50567. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50568. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50569. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50570. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50571. } else {
  50572. // attach buffer if it's been created already
  50573. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50574. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50575. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50576. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50577. }
  50578. }
  50579. } else {
  50580. const mipmaps = renderTarget.texture.mipmaps;
  50581. if ( mipmaps && mipmaps.length > 0 ) {
  50582. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50583. } else {
  50584. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50585. }
  50586. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50587. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50588. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50589. } else {
  50590. // attach buffer if it's been created already
  50591. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50592. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50593. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50594. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50595. }
  50596. }
  50597. }
  50598. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50599. }
  50600. // rebind framebuffer with external textures
  50601. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50602. const renderTargetProperties = properties.get( renderTarget );
  50603. if ( colorTexture !== undefined ) {
  50604. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50605. }
  50606. if ( depthTexture !== undefined ) {
  50607. setupDepthRenderbuffer( renderTarget );
  50608. }
  50609. }
  50610. // Set up GL resources for the render target
  50611. function setupRenderTarget( renderTarget ) {
  50612. const texture = renderTarget.texture;
  50613. const renderTargetProperties = properties.get( renderTarget );
  50614. const textureProperties = properties.get( texture );
  50615. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50616. const textures = renderTarget.textures;
  50617. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50618. const isMultipleRenderTargets = ( textures.length > 1 );
  50619. if ( ! isMultipleRenderTargets ) {
  50620. if ( textureProperties.__webglTexture === undefined ) {
  50621. textureProperties.__webglTexture = _gl.createTexture();
  50622. }
  50623. textureProperties.__version = texture.version;
  50624. info.memory.textures ++;
  50625. }
  50626. // Setup framebuffer
  50627. if ( isCube ) {
  50628. renderTargetProperties.__webglFramebuffer = [];
  50629. for ( let i = 0; i < 6; i ++ ) {
  50630. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50631. renderTargetProperties.__webglFramebuffer[ i ] = [];
  50632. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50633. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  50634. }
  50635. } else {
  50636. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  50637. }
  50638. }
  50639. } else {
  50640. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50641. renderTargetProperties.__webglFramebuffer = [];
  50642. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50643. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  50644. }
  50645. } else {
  50646. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  50647. }
  50648. if ( isMultipleRenderTargets ) {
  50649. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50650. const attachmentProperties = properties.get( textures[ i ] );
  50651. if ( attachmentProperties.__webglTexture === undefined ) {
  50652. attachmentProperties.__webglTexture = _gl.createTexture();
  50653. info.memory.textures ++;
  50654. }
  50655. }
  50656. }
  50657. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  50658. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  50659. renderTargetProperties.__webglColorRenderbuffer = [];
  50660. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50661. for ( let i = 0; i < textures.length; i ++ ) {
  50662. const texture = textures[ i ];
  50663. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  50664. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50665. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50666. const glType = utils.convert( texture.type );
  50667. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  50668. const samples = getRenderTargetSamples( renderTarget );
  50669. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50670. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50671. }
  50672. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50673. if ( renderTarget.depthBuffer ) {
  50674. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  50675. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  50676. }
  50677. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50678. }
  50679. }
  50680. // Setup color buffer
  50681. if ( isCube ) {
  50682. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50683. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50684. for ( let i = 0; i < 6; i ++ ) {
  50685. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50686. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50687. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  50688. }
  50689. } else {
  50690. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  50691. }
  50692. }
  50693. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50694. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50695. }
  50696. state.unbindTexture();
  50697. } else if ( isMultipleRenderTargets ) {
  50698. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50699. const attachment = textures[ i ];
  50700. const attachmentProperties = properties.get( attachment );
  50701. let glTextureType = _gl.TEXTURE_2D;
  50702. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50703. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50704. }
  50705. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  50706. setTextureParameters( glTextureType, attachment );
  50707. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  50708. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  50709. generateMipmap( glTextureType );
  50710. }
  50711. }
  50712. state.unbindTexture();
  50713. } else {
  50714. let glTextureType = _gl.TEXTURE_2D;
  50715. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50716. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50717. }
  50718. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  50719. setTextureParameters( glTextureType, texture );
  50720. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50721. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50722. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  50723. }
  50724. } else {
  50725. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  50726. }
  50727. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50728. generateMipmap( glTextureType );
  50729. }
  50730. state.unbindTexture();
  50731. }
  50732. // Setup depth and stencil buffers
  50733. if ( renderTarget.depthBuffer ) {
  50734. setupDepthRenderbuffer( renderTarget );
  50735. }
  50736. }
  50737. function updateRenderTargetMipmap( renderTarget ) {
  50738. const textures = renderTarget.textures;
  50739. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50740. const texture = textures[ i ];
  50741. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50742. const targetType = getTargetType( renderTarget );
  50743. const webglTexture = properties.get( texture ).__webglTexture;
  50744. state.bindTexture( targetType, webglTexture );
  50745. generateMipmap( targetType );
  50746. state.unbindTexture();
  50747. }
  50748. }
  50749. }
  50750. const invalidationArrayRead = [];
  50751. const invalidationArrayDraw = [];
  50752. function updateMultisampleRenderTarget( renderTarget ) {
  50753. if ( renderTarget.samples > 0 ) {
  50754. if ( useMultisampledRTT( renderTarget ) === false ) {
  50755. const textures = renderTarget.textures;
  50756. const width = renderTarget.width;
  50757. const height = renderTarget.height;
  50758. let mask = _gl.COLOR_BUFFER_BIT;
  50759. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50760. const renderTargetProperties = properties.get( renderTarget );
  50761. const isMultipleRenderTargets = ( textures.length > 1 );
  50762. // If MRT we need to remove FBO attachments
  50763. if ( isMultipleRenderTargets ) {
  50764. for ( let i = 0; i < textures.length; i ++ ) {
  50765. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50766. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50767. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50768. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50769. }
  50770. }
  50771. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50772. const mipmaps = renderTarget.texture.mipmaps;
  50773. if ( mipmaps && mipmaps.length > 0 ) {
  50774. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50775. } else {
  50776. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50777. }
  50778. for ( let i = 0; i < textures.length; i ++ ) {
  50779. if ( renderTarget.resolveDepthBuffer ) {
  50780. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50781. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50782. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50783. }
  50784. if ( isMultipleRenderTargets ) {
  50785. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50786. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50787. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50788. }
  50789. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50790. if ( supportsInvalidateFramebuffer === true ) {
  50791. invalidationArrayRead.length = 0;
  50792. invalidationArrayDraw.length = 0;
  50793. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50794. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50795. invalidationArrayRead.push( depthStyle );
  50796. invalidationArrayDraw.push( depthStyle );
  50797. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50798. }
  50799. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50800. }
  50801. }
  50802. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50803. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50804. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50805. if ( isMultipleRenderTargets ) {
  50806. for ( let i = 0; i < textures.length; i ++ ) {
  50807. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50808. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50809. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50810. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50811. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50812. }
  50813. }
  50814. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50815. } else {
  50816. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50817. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50818. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50819. }
  50820. }
  50821. }
  50822. }
  50823. function getRenderTargetSamples( renderTarget ) {
  50824. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50825. }
  50826. function useMultisampledRTT( renderTarget ) {
  50827. const renderTargetProperties = properties.get( renderTarget );
  50828. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50829. }
  50830. function updateVideoTexture( texture ) {
  50831. const frame = info.render.frame;
  50832. // Check the last frame we updated the VideoTexture
  50833. if ( _videoTextures.get( texture ) !== frame ) {
  50834. _videoTextures.set( texture, frame );
  50835. texture.update();
  50836. }
  50837. }
  50838. function verifyColorSpace( texture, image ) {
  50839. const colorSpace = texture.colorSpace;
  50840. const format = texture.format;
  50841. const type = texture.type;
  50842. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50843. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50844. // sRGB
  50845. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50846. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50847. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50848. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50849. }
  50850. } else {
  50851. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  50852. }
  50853. }
  50854. return image;
  50855. }
  50856. function getDimensions( image ) {
  50857. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50858. // if intrinsic data are not available, fallback to width/height
  50859. _imageDimensions.width = image.naturalWidth || image.width;
  50860. _imageDimensions.height = image.naturalHeight || image.height;
  50861. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50862. _imageDimensions.width = image.displayWidth;
  50863. _imageDimensions.height = image.displayHeight;
  50864. } else {
  50865. _imageDimensions.width = image.width;
  50866. _imageDimensions.height = image.height;
  50867. }
  50868. return _imageDimensions;
  50869. }
  50870. //
  50871. this.allocateTextureUnit = allocateTextureUnit;
  50872. this.resetTextureUnits = resetTextureUnits;
  50873. this.setTexture2D = setTexture2D;
  50874. this.setTexture2DArray = setTexture2DArray;
  50875. this.setTexture3D = setTexture3D;
  50876. this.setTextureCube = setTextureCube;
  50877. this.rebindTextures = rebindTextures;
  50878. this.setupRenderTarget = setupRenderTarget;
  50879. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50880. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50881. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50882. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50883. this.useMultisampledRTT = useMultisampledRTT;
  50884. this.isReversedDepthBuffer = function () {
  50885. return state.buffers.depth.getReversed();
  50886. };
  50887. }
  50888. function WebGLUtils( gl, extensions ) {
  50889. function convert( p, colorSpace = NoColorSpace ) {
  50890. let extension;
  50891. const transfer = ColorManagement.getTransfer( colorSpace );
  50892. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50893. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50894. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50895. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50896. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  50897. if ( p === ByteType ) return gl.BYTE;
  50898. if ( p === ShortType ) return gl.SHORT;
  50899. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50900. if ( p === IntType ) return gl.INT;
  50901. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50902. if ( p === FloatType ) return gl.FLOAT;
  50903. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50904. if ( p === AlphaFormat ) return gl.ALPHA;
  50905. if ( p === RGBFormat ) return gl.RGB;
  50906. if ( p === RGBAFormat ) return gl.RGBA;
  50907. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50908. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50909. // WebGL2 formats.
  50910. if ( p === RedFormat ) return gl.RED;
  50911. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50912. if ( p === RGFormat ) return gl.RG;
  50913. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50914. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50915. // S3TC
  50916. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50917. if ( transfer === SRGBTransfer ) {
  50918. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50919. if ( extension !== null ) {
  50920. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50921. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50922. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50923. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50924. } else {
  50925. return null;
  50926. }
  50927. } else {
  50928. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50929. if ( extension !== null ) {
  50930. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50931. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50932. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50933. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50934. } else {
  50935. return null;
  50936. }
  50937. }
  50938. }
  50939. // PVRTC
  50940. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50941. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50942. if ( extension !== null ) {
  50943. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50944. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50945. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50946. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50947. } else {
  50948. return null;
  50949. }
  50950. }
  50951. // ETC
  50952. 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 ) {
  50953. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50954. if ( extension !== null ) {
  50955. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50956. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50957. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  50958. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  50959. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  50960. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  50961. } else {
  50962. return null;
  50963. }
  50964. }
  50965. // ASTC
  50966. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50967. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50968. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50969. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50970. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50971. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50972. if ( extension !== null ) {
  50973. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50974. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50975. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50976. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50977. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50978. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50979. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50980. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50981. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50982. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50983. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50984. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50985. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50986. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50987. } else {
  50988. return null;
  50989. }
  50990. }
  50991. // BPTC
  50992. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50993. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50994. if ( extension !== null ) {
  50995. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50996. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50997. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50998. } else {
  50999. return null;
  51000. }
  51001. }
  51002. // RGTC
  51003. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  51004. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  51005. if ( extension !== null ) {
  51006. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  51007. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  51008. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  51009. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  51010. } else {
  51011. return null;
  51012. }
  51013. }
  51014. //
  51015. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  51016. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  51017. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  51018. }
  51019. return { convert: convert };
  51020. }
  51021. const _occlusion_vertex = `
  51022. void main() {
  51023. gl_Position = vec4( position, 1.0 );
  51024. }`;
  51025. const _occlusion_fragment = `
  51026. uniform sampler2DArray depthColor;
  51027. uniform float depthWidth;
  51028. uniform float depthHeight;
  51029. void main() {
  51030. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  51031. if ( coord.x >= 1.0 ) {
  51032. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  51033. } else {
  51034. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  51035. }
  51036. }`;
  51037. /**
  51038. * A XR module that manages the access to the Depth Sensing API.
  51039. */
  51040. class WebXRDepthSensing {
  51041. /**
  51042. * Constructs a new depth sensing module.
  51043. */
  51044. constructor() {
  51045. /**
  51046. * An opaque texture representing the depth of the user's environment.
  51047. *
  51048. * @type {?ExternalTexture}
  51049. */
  51050. this.texture = null;
  51051. /**
  51052. * A plane mesh for visualizing the depth texture.
  51053. *
  51054. * @type {?Mesh}
  51055. */
  51056. this.mesh = null;
  51057. /**
  51058. * The depth near value.
  51059. *
  51060. * @type {number}
  51061. */
  51062. this.depthNear = 0;
  51063. /**
  51064. * The depth near far.
  51065. *
  51066. * @type {number}
  51067. */
  51068. this.depthFar = 0;
  51069. }
  51070. /**
  51071. * Inits the depth sensing module
  51072. *
  51073. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  51074. * @param {XRRenderState} renderState - The XR render state.
  51075. */
  51076. init( depthData, renderState ) {
  51077. if ( this.texture === null ) {
  51078. const texture = new ExternalTexture( depthData.texture );
  51079. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  51080. this.depthNear = depthData.depthNear;
  51081. this.depthFar = depthData.depthFar;
  51082. }
  51083. this.texture = texture;
  51084. }
  51085. }
  51086. /**
  51087. * Returns a plane mesh that visualizes the depth texture.
  51088. *
  51089. * @param {ArrayCamera} cameraXR - The XR camera.
  51090. * @return {?Mesh} The plane mesh.
  51091. */
  51092. getMesh( cameraXR ) {
  51093. if ( this.texture !== null ) {
  51094. if ( this.mesh === null ) {
  51095. const viewport = cameraXR.cameras[ 0 ].viewport;
  51096. const material = new ShaderMaterial( {
  51097. vertexShader: _occlusion_vertex,
  51098. fragmentShader: _occlusion_fragment,
  51099. uniforms: {
  51100. depthColor: { value: this.texture },
  51101. depthWidth: { value: viewport.z },
  51102. depthHeight: { value: viewport.w }
  51103. }
  51104. } );
  51105. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  51106. }
  51107. }
  51108. return this.mesh;
  51109. }
  51110. /**
  51111. * Resets the module
  51112. */
  51113. reset() {
  51114. this.texture = null;
  51115. this.mesh = null;
  51116. }
  51117. /**
  51118. * Returns a texture representing the depth of the user's environment.
  51119. *
  51120. * @return {?ExternalTexture} The depth texture.
  51121. */
  51122. getDepthTexture() {
  51123. return this.texture;
  51124. }
  51125. }
  51126. /**
  51127. * This class represents an abstraction of the WebXR Device API and is
  51128. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  51129. * interface that allows users to enable/disable XR and perform XR related
  51130. * tasks like for instance retrieving controllers.
  51131. *
  51132. * @augments EventDispatcher
  51133. * @hideconstructor
  51134. */
  51135. class WebXRManager extends EventDispatcher {
  51136. /**
  51137. * Constructs a new WebGL renderer.
  51138. *
  51139. * @param {WebGLRenderer} renderer - The renderer.
  51140. * @param {WebGL2RenderingContext} gl - The rendering context.
  51141. */
  51142. constructor( renderer, gl ) {
  51143. super();
  51144. const scope = this;
  51145. let session = null;
  51146. let framebufferScaleFactor = 1.0;
  51147. let referenceSpace = null;
  51148. let referenceSpaceType = 'local-floor';
  51149. // Set default foveation to maximum.
  51150. let foveation = 1.0;
  51151. let customReferenceSpace = null;
  51152. let pose = null;
  51153. let glBinding = null;
  51154. let glProjLayer = null;
  51155. let glBaseLayer = null;
  51156. let xrFrame = null;
  51157. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  51158. const depthSensing = new WebXRDepthSensing();
  51159. const cameraAccessTextures = {};
  51160. const attributes = gl.getContextAttributes();
  51161. let initialRenderTarget = null;
  51162. let newRenderTarget = null;
  51163. const controllers = [];
  51164. const controllerInputSources = [];
  51165. const currentSize = new Vector2();
  51166. let currentPixelRatio = null;
  51167. //
  51168. const cameraL = new PerspectiveCamera();
  51169. cameraL.viewport = new Vector4();
  51170. const cameraR = new PerspectiveCamera();
  51171. cameraR.viewport = new Vector4();
  51172. const cameras = [ cameraL, cameraR ];
  51173. const cameraXR = new ArrayCamera();
  51174. let _currentDepthNear = null;
  51175. let _currentDepthFar = null;
  51176. //
  51177. /**
  51178. * Whether the manager's XR camera should be automatically updated or not.
  51179. *
  51180. * @type {boolean}
  51181. * @default true
  51182. */
  51183. this.cameraAutoUpdate = true;
  51184. /**
  51185. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  51186. * if you are going to use XR in your app.
  51187. *
  51188. * @type {boolean}
  51189. * @default false
  51190. */
  51191. this.enabled = false;
  51192. /**
  51193. * Whether XR presentation is active or not.
  51194. *
  51195. * @type {boolean}
  51196. * @readonly
  51197. * @default false
  51198. */
  51199. this.isPresenting = false;
  51200. /**
  51201. * Returns a group representing the `target ray` space of the XR controller.
  51202. * Use this space for visualizing 3D objects that support the user in pointing
  51203. * tasks like UI interaction.
  51204. *
  51205. * @param {number} index - The index of the controller.
  51206. * @return {Group} A group representing the `target ray` space.
  51207. */
  51208. this.getController = function ( index ) {
  51209. let controller = controllers[ index ];
  51210. if ( controller === undefined ) {
  51211. controller = new WebXRController();
  51212. controllers[ index ] = controller;
  51213. }
  51214. return controller.getTargetRaySpace();
  51215. };
  51216. /**
  51217. * Returns a group representing the `grip` space of the XR controller.
  51218. * Use this space for visualizing 3D objects that support the user in pointing
  51219. * tasks like UI interaction.
  51220. *
  51221. * Note: If you want to show something in the user's hand AND offer a
  51222. * pointing ray at the same time, you'll want to attached the handheld object
  51223. * to the group returned by `getControllerGrip()` and the ray to the
  51224. * group returned by `getController()`. The idea is to have two
  51225. * different groups in two different coordinate spaces for the same WebXR
  51226. * controller.
  51227. *
  51228. * @param {number} index - The index of the controller.
  51229. * @return {Group} A group representing the `grip` space.
  51230. */
  51231. this.getControllerGrip = function ( index ) {
  51232. let controller = controllers[ index ];
  51233. if ( controller === undefined ) {
  51234. controller = new WebXRController();
  51235. controllers[ index ] = controller;
  51236. }
  51237. return controller.getGripSpace();
  51238. };
  51239. /**
  51240. * Returns a group representing the `hand` space of the XR controller.
  51241. * Use this space for visualizing 3D objects that support the user in pointing
  51242. * tasks like UI interaction.
  51243. *
  51244. * @param {number} index - The index of the controller.
  51245. * @return {Group} A group representing the `hand` space.
  51246. */
  51247. this.getHand = function ( index ) {
  51248. let controller = controllers[ index ];
  51249. if ( controller === undefined ) {
  51250. controller = new WebXRController();
  51251. controllers[ index ] = controller;
  51252. }
  51253. return controller.getHandSpace();
  51254. };
  51255. //
  51256. function onSessionEvent( event ) {
  51257. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  51258. if ( controllerIndex === -1 ) {
  51259. return;
  51260. }
  51261. const controller = controllers[ controllerIndex ];
  51262. if ( controller !== undefined ) {
  51263. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  51264. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  51265. }
  51266. }
  51267. function onSessionEnd() {
  51268. session.removeEventListener( 'select', onSessionEvent );
  51269. session.removeEventListener( 'selectstart', onSessionEvent );
  51270. session.removeEventListener( 'selectend', onSessionEvent );
  51271. session.removeEventListener( 'squeeze', onSessionEvent );
  51272. session.removeEventListener( 'squeezestart', onSessionEvent );
  51273. session.removeEventListener( 'squeezeend', onSessionEvent );
  51274. session.removeEventListener( 'end', onSessionEnd );
  51275. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  51276. for ( let i = 0; i < controllers.length; i ++ ) {
  51277. const inputSource = controllerInputSources[ i ];
  51278. if ( inputSource === null ) continue;
  51279. controllerInputSources[ i ] = null;
  51280. controllers[ i ].disconnect( inputSource );
  51281. }
  51282. _currentDepthNear = null;
  51283. _currentDepthFar = null;
  51284. depthSensing.reset();
  51285. for ( const key in cameraAccessTextures ) {
  51286. delete cameraAccessTextures[ key ];
  51287. }
  51288. // restore framebuffer/rendering state
  51289. renderer.setRenderTarget( initialRenderTarget );
  51290. glBaseLayer = null;
  51291. glProjLayer = null;
  51292. glBinding = null;
  51293. session = null;
  51294. newRenderTarget = null;
  51295. //
  51296. animation.stop();
  51297. scope.isPresenting = false;
  51298. renderer.setPixelRatio( currentPixelRatio );
  51299. renderer.setSize( currentSize.width, currentSize.height, false );
  51300. scope.dispatchEvent( { type: 'sessionend' } );
  51301. }
  51302. /**
  51303. * Sets the framebuffer scale factor.
  51304. *
  51305. * This method can not be used during a XR session.
  51306. *
  51307. * @param {number} value - The framebuffer scale factor.
  51308. */
  51309. this.setFramebufferScaleFactor = function ( value ) {
  51310. framebufferScaleFactor = value;
  51311. if ( scope.isPresenting === true ) {
  51312. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51313. }
  51314. };
  51315. /**
  51316. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51317. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51318. * improve tracking. Default is `local-floor`. Valid values can be found here
  51319. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51320. *
  51321. * This method can not be used during a XR session.
  51322. *
  51323. * @param {string} value - The reference space type.
  51324. */
  51325. this.setReferenceSpaceType = function ( value ) {
  51326. referenceSpaceType = value;
  51327. if ( scope.isPresenting === true ) {
  51328. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51329. }
  51330. };
  51331. /**
  51332. * Returns the XR reference space.
  51333. *
  51334. * @return {XRReferenceSpace} The XR reference space.
  51335. */
  51336. this.getReferenceSpace = function () {
  51337. return customReferenceSpace || referenceSpace;
  51338. };
  51339. /**
  51340. * Sets a custom XR reference space.
  51341. *
  51342. * @param {XRReferenceSpace} space - The XR reference space.
  51343. */
  51344. this.setReferenceSpace = function ( space ) {
  51345. customReferenceSpace = space;
  51346. };
  51347. /**
  51348. * Returns the current base layer.
  51349. *
  51350. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51351. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51352. *
  51353. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51354. */
  51355. this.getBaseLayer = function () {
  51356. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51357. };
  51358. /**
  51359. * Returns the current XR binding.
  51360. *
  51361. * Creates a new binding if needed and the browser is
  51362. * capable of doing so.
  51363. *
  51364. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51365. */
  51366. this.getBinding = function () {
  51367. if ( glBinding === null && supportsGlBinding ) {
  51368. glBinding = new XRWebGLBinding( session, gl );
  51369. }
  51370. return glBinding;
  51371. };
  51372. /**
  51373. * Returns the current XR frame.
  51374. *
  51375. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51376. */
  51377. this.getFrame = function () {
  51378. return xrFrame;
  51379. };
  51380. /**
  51381. * Returns the current XR session.
  51382. *
  51383. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51384. */
  51385. this.getSession = function () {
  51386. return session;
  51387. };
  51388. /**
  51389. * After a XR session has been requested usually with one of the `*Button` modules, it
  51390. * is injected into the renderer with this method. This method triggers the start of
  51391. * the actual XR rendering.
  51392. *
  51393. * @async
  51394. * @param {XRSession} value - The XR session to set.
  51395. * @return {Promise} A Promise that resolves when the session has been set.
  51396. */
  51397. this.setSession = async function ( value ) {
  51398. session = value;
  51399. if ( session !== null ) {
  51400. initialRenderTarget = renderer.getRenderTarget();
  51401. session.addEventListener( 'select', onSessionEvent );
  51402. session.addEventListener( 'selectstart', onSessionEvent );
  51403. session.addEventListener( 'selectend', onSessionEvent );
  51404. session.addEventListener( 'squeeze', onSessionEvent );
  51405. session.addEventListener( 'squeezestart', onSessionEvent );
  51406. session.addEventListener( 'squeezeend', onSessionEvent );
  51407. session.addEventListener( 'end', onSessionEnd );
  51408. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51409. if ( attributes.xrCompatible !== true ) {
  51410. await gl.makeXRCompatible();
  51411. }
  51412. currentPixelRatio = renderer.getPixelRatio();
  51413. renderer.getSize( currentSize );
  51414. // Check that the browser implements the necessary APIs to use an
  51415. // XRProjectionLayer rather than an XRWebGLLayer
  51416. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51417. if ( ! supportsLayers ) {
  51418. const layerInit = {
  51419. antialias: attributes.antialias,
  51420. alpha: true,
  51421. depth: attributes.depth,
  51422. stencil: attributes.stencil,
  51423. framebufferScaleFactor: framebufferScaleFactor
  51424. };
  51425. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51426. session.updateRenderState( { baseLayer: glBaseLayer } );
  51427. renderer.setPixelRatio( 1 );
  51428. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51429. newRenderTarget = new WebGLRenderTarget(
  51430. glBaseLayer.framebufferWidth,
  51431. glBaseLayer.framebufferHeight,
  51432. {
  51433. format: RGBAFormat,
  51434. type: UnsignedByteType,
  51435. colorSpace: renderer.outputColorSpace,
  51436. stencilBuffer: attributes.stencil,
  51437. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51438. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51439. }
  51440. );
  51441. } else {
  51442. let depthFormat = null;
  51443. let depthType = null;
  51444. let glDepthFormat = null;
  51445. if ( attributes.depth ) {
  51446. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51447. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51448. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51449. }
  51450. const projectionlayerInit = {
  51451. colorFormat: gl.RGBA8,
  51452. depthFormat: glDepthFormat,
  51453. scaleFactor: framebufferScaleFactor
  51454. };
  51455. glBinding = this.getBinding();
  51456. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51457. session.updateRenderState( { layers: [ glProjLayer ] } );
  51458. renderer.setPixelRatio( 1 );
  51459. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51460. newRenderTarget = new WebGLRenderTarget(
  51461. glProjLayer.textureWidth,
  51462. glProjLayer.textureHeight,
  51463. {
  51464. format: RGBAFormat,
  51465. type: UnsignedByteType,
  51466. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51467. stencilBuffer: attributes.stencil,
  51468. colorSpace: renderer.outputColorSpace,
  51469. samples: attributes.antialias ? 4 : 0,
  51470. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51471. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51472. } );
  51473. }
  51474. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51475. this.setFoveation( foveation );
  51476. customReferenceSpace = null;
  51477. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51478. animation.setContext( session );
  51479. animation.start();
  51480. scope.isPresenting = true;
  51481. scope.dispatchEvent( { type: 'sessionstart' } );
  51482. }
  51483. };
  51484. /**
  51485. * Returns the environment blend mode from the current XR session.
  51486. *
  51487. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51488. */
  51489. this.getEnvironmentBlendMode = function () {
  51490. if ( session !== null ) {
  51491. return session.environmentBlendMode;
  51492. }
  51493. };
  51494. /**
  51495. * Returns the current depth texture computed via depth sensing.
  51496. *
  51497. * See {@link WebXRDepthSensing#getDepthTexture}.
  51498. *
  51499. * @return {?Texture} The depth texture.
  51500. */
  51501. this.getDepthTexture = function () {
  51502. return depthSensing.getDepthTexture();
  51503. };
  51504. function onInputSourcesChange( event ) {
  51505. // Notify disconnected
  51506. for ( let i = 0; i < event.removed.length; i ++ ) {
  51507. const inputSource = event.removed[ i ];
  51508. const index = controllerInputSources.indexOf( inputSource );
  51509. if ( index >= 0 ) {
  51510. controllerInputSources[ index ] = null;
  51511. controllers[ index ].disconnect( inputSource );
  51512. }
  51513. }
  51514. // Notify connected
  51515. for ( let i = 0; i < event.added.length; i ++ ) {
  51516. const inputSource = event.added[ i ];
  51517. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51518. if ( controllerIndex === -1 ) {
  51519. // Assign input source a controller that currently has no input source
  51520. for ( let i = 0; i < controllers.length; i ++ ) {
  51521. if ( i >= controllerInputSources.length ) {
  51522. controllerInputSources.push( inputSource );
  51523. controllerIndex = i;
  51524. break;
  51525. } else if ( controllerInputSources[ i ] === null ) {
  51526. controllerInputSources[ i ] = inputSource;
  51527. controllerIndex = i;
  51528. break;
  51529. }
  51530. }
  51531. // If all controllers do currently receive input we ignore new ones
  51532. if ( controllerIndex === -1 ) break;
  51533. }
  51534. const controller = controllers[ controllerIndex ];
  51535. if ( controller ) {
  51536. controller.connect( inputSource );
  51537. }
  51538. }
  51539. }
  51540. //
  51541. const cameraLPos = new Vector3();
  51542. const cameraRPos = new Vector3();
  51543. /**
  51544. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51545. * the cameras' projection and world matrices have already been set.
  51546. * And that near and far planes are identical for both cameras.
  51547. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51548. *
  51549. * @param {ArrayCamera} camera - The camera to update.
  51550. * @param {PerspectiveCamera} cameraL - The left camera.
  51551. * @param {PerspectiveCamera} cameraR - The right camera.
  51552. */
  51553. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51554. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51555. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51556. const ipd = cameraLPos.distanceTo( cameraRPos );
  51557. const projL = cameraL.projectionMatrix.elements;
  51558. const projR = cameraR.projectionMatrix.elements;
  51559. // VR systems will have identical far and near planes, and
  51560. // most likely identical top and bottom frustum extents.
  51561. // Use the left camera for these values.
  51562. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51563. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51564. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51565. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51566. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51567. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51568. const left = near * leftFov;
  51569. const right = near * rightFov;
  51570. // Calculate the new camera's position offset from the
  51571. // left camera. xOffset should be roughly half `ipd`.
  51572. const zOffset = ipd / ( - leftFov + rightFov );
  51573. const xOffset = zOffset * - leftFov;
  51574. // TODO: Better way to apply this offset?
  51575. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51576. camera.translateX( xOffset );
  51577. camera.translateZ( zOffset );
  51578. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51579. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51580. // Check if the projection uses an infinite far plane.
  51581. if ( projL[ 10 ] === -1 ) {
  51582. // Use the projection matrix from the left eye.
  51583. // The camera offset is sufficient to include the view volumes
  51584. // of both eyes (assuming symmetric projections).
  51585. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51586. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51587. } else {
  51588. // Find the union of the frustum values of the cameras and scale
  51589. // the values so that the near plane's position does not change in world space,
  51590. // although must now be relative to the new union camera.
  51591. const near2 = near + zOffset;
  51592. const far2 = far + zOffset;
  51593. const left2 = left - xOffset;
  51594. const right2 = right + ( ipd - xOffset );
  51595. const top2 = topFov * far / far2 * near2;
  51596. const bottom2 = bottomFov * far / far2 * near2;
  51597. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51598. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51599. }
  51600. }
  51601. function updateCamera( camera, parent ) {
  51602. if ( parent === null ) {
  51603. camera.matrixWorld.copy( camera.matrix );
  51604. } else {
  51605. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51606. }
  51607. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51608. }
  51609. /**
  51610. * Updates the state of the XR camera. Use this method on app level if you
  51611. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51612. * camera of the scene as a parameter. The passed in camera's transformation
  51613. * is automatically adjusted to the position of the XR camera when calling
  51614. * this method.
  51615. *
  51616. * @param {Camera} camera - The camera.
  51617. */
  51618. this.updateCamera = function ( camera ) {
  51619. if ( session === null ) return;
  51620. let depthNear = camera.near;
  51621. let depthFar = camera.far;
  51622. if ( depthSensing.texture !== null ) {
  51623. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51624. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51625. }
  51626. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  51627. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  51628. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  51629. // Note that the new renderState won't apply until the next frame. See #18320
  51630. session.updateRenderState( {
  51631. depthNear: cameraXR.near,
  51632. depthFar: cameraXR.far
  51633. } );
  51634. _currentDepthNear = cameraXR.near;
  51635. _currentDepthFar = cameraXR.far;
  51636. }
  51637. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  51638. cameraXR.layers.mask = camera.layers.mask | 0b110;
  51639. cameraL.layers.mask = cameraXR.layers.mask & -5;
  51640. cameraR.layers.mask = cameraXR.layers.mask & -3;
  51641. const parent = camera.parent;
  51642. const cameras = cameraXR.cameras;
  51643. updateCamera( cameraXR, parent );
  51644. for ( let i = 0; i < cameras.length; i ++ ) {
  51645. updateCamera( cameras[ i ], parent );
  51646. }
  51647. // update projection matrix for proper view frustum culling
  51648. if ( cameras.length === 2 ) {
  51649. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  51650. } else {
  51651. // assume single camera setup (AR)
  51652. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  51653. }
  51654. // update user camera and its children
  51655. updateUserCamera( camera, cameraXR, parent );
  51656. };
  51657. function updateUserCamera( camera, cameraXR, parent ) {
  51658. if ( parent === null ) {
  51659. camera.matrix.copy( cameraXR.matrixWorld );
  51660. } else {
  51661. camera.matrix.copy( parent.matrixWorld );
  51662. camera.matrix.invert();
  51663. camera.matrix.multiply( cameraXR.matrixWorld );
  51664. }
  51665. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51666. camera.updateMatrixWorld( true );
  51667. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  51668. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  51669. if ( camera.isPerspectiveCamera ) {
  51670. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  51671. camera.zoom = 1;
  51672. }
  51673. }
  51674. /**
  51675. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  51676. * of the active XR session. For each view it holds a separate camera object.
  51677. *
  51678. * The camera's `fov` is currently not used and does not reflect the fov of
  51679. * the XR camera. If you need the fov on app level, you have to compute in
  51680. * manually from the XR camera's projection matrices.
  51681. *
  51682. * @return {ArrayCamera} The XR camera.
  51683. */
  51684. this.getCamera = function () {
  51685. return cameraXR;
  51686. };
  51687. /**
  51688. * Returns the amount of foveation used by the XR compositor for the projection layer.
  51689. *
  51690. * @return {number|undefined} The amount of foveation.
  51691. */
  51692. this.getFoveation = function () {
  51693. if ( glProjLayer === null && glBaseLayer === null ) {
  51694. return undefined;
  51695. }
  51696. return foveation;
  51697. };
  51698. /**
  51699. * Sets the foveation value.
  51700. *
  51701. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  51702. * and `1` means maximum foveation (the edges render at lower resolution).
  51703. */
  51704. this.setFoveation = function ( value ) {
  51705. // 0 = no foveation = full resolution
  51706. // 1 = maximum foveation = the edges render at lower resolution
  51707. foveation = value;
  51708. if ( glProjLayer !== null ) {
  51709. glProjLayer.fixedFoveation = value;
  51710. }
  51711. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  51712. glBaseLayer.fixedFoveation = value;
  51713. }
  51714. };
  51715. /**
  51716. * Returns `true` if depth sensing is supported.
  51717. *
  51718. * @return {boolean} Whether depth sensing is supported or not.
  51719. */
  51720. this.hasDepthSensing = function () {
  51721. return depthSensing.texture !== null;
  51722. };
  51723. /**
  51724. * Returns the depth sensing mesh.
  51725. *
  51726. * See {@link WebXRDepthSensing#getMesh}.
  51727. *
  51728. * @return {Mesh} The depth sensing mesh.
  51729. */
  51730. this.getDepthSensingMesh = function () {
  51731. return depthSensing.getMesh( cameraXR );
  51732. };
  51733. /**
  51734. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  51735. * Only available during the current animation loop.
  51736. *
  51737. * @param {XRCamera} xrCamera - The camera to query.
  51738. * @return {?Texture} An opaque texture representing the current raw camera frame.
  51739. */
  51740. this.getCameraTexture = function ( xrCamera ) {
  51741. return cameraAccessTextures[ xrCamera ];
  51742. };
  51743. // Animation Loop
  51744. let onAnimationFrameCallback = null;
  51745. function onAnimationFrame( time, frame ) {
  51746. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  51747. xrFrame = frame;
  51748. if ( pose !== null ) {
  51749. const views = pose.views;
  51750. if ( glBaseLayer !== null ) {
  51751. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  51752. renderer.setRenderTarget( newRenderTarget );
  51753. }
  51754. let cameraXRNeedsUpdate = false;
  51755. // check if it's necessary to rebuild cameraXR's camera list
  51756. if ( views.length !== cameraXR.cameras.length ) {
  51757. cameraXR.cameras.length = 0;
  51758. cameraXRNeedsUpdate = true;
  51759. }
  51760. for ( let i = 0; i < views.length; i ++ ) {
  51761. const view = views[ i ];
  51762. let viewport = null;
  51763. if ( glBaseLayer !== null ) {
  51764. viewport = glBaseLayer.getViewport( view );
  51765. } else {
  51766. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51767. viewport = glSubImage.viewport;
  51768. // For side-by-side projection, we only produce a single texture for both eyes.
  51769. if ( i === 0 ) {
  51770. renderer.setRenderTargetTextures(
  51771. newRenderTarget,
  51772. glSubImage.colorTexture,
  51773. glSubImage.depthStencilTexture );
  51774. renderer.setRenderTarget( newRenderTarget );
  51775. }
  51776. }
  51777. let camera = cameras[ i ];
  51778. if ( camera === undefined ) {
  51779. camera = new PerspectiveCamera();
  51780. camera.layers.enable( i );
  51781. camera.viewport = new Vector4();
  51782. cameras[ i ] = camera;
  51783. }
  51784. camera.matrix.fromArray( view.transform.matrix );
  51785. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51786. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51787. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51788. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51789. if ( i === 0 ) {
  51790. cameraXR.matrix.copy( camera.matrix );
  51791. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51792. }
  51793. if ( cameraXRNeedsUpdate === true ) {
  51794. cameraXR.cameras.push( camera );
  51795. }
  51796. }
  51797. //
  51798. const enabledFeatures = session.enabledFeatures;
  51799. const gpuDepthSensingEnabled = enabledFeatures &&
  51800. enabledFeatures.includes( 'depth-sensing' ) &&
  51801. session.depthUsage == 'gpu-optimized';
  51802. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51803. glBinding = scope.getBinding();
  51804. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51805. if ( depthData && depthData.isValid && depthData.texture ) {
  51806. depthSensing.init( depthData, session.renderState );
  51807. }
  51808. }
  51809. const cameraAccessEnabled = enabledFeatures &&
  51810. enabledFeatures.includes( 'camera-access' );
  51811. if ( cameraAccessEnabled && supportsGlBinding ) {
  51812. renderer.state.unbindTexture();
  51813. glBinding = scope.getBinding();
  51814. for ( let i = 0; i < views.length; i ++ ) {
  51815. const camera = views[ i ].camera;
  51816. if ( camera ) {
  51817. let cameraTex = cameraAccessTextures[ camera ];
  51818. if ( ! cameraTex ) {
  51819. cameraTex = new ExternalTexture();
  51820. cameraAccessTextures[ camera ] = cameraTex;
  51821. }
  51822. const glTexture = glBinding.getCameraImage( camera );
  51823. cameraTex.sourceTexture = glTexture;
  51824. }
  51825. }
  51826. }
  51827. }
  51828. //
  51829. for ( let i = 0; i < controllers.length; i ++ ) {
  51830. const inputSource = controllerInputSources[ i ];
  51831. const controller = controllers[ i ];
  51832. if ( inputSource !== null && controller !== undefined ) {
  51833. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51834. }
  51835. }
  51836. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51837. if ( frame.detectedPlanes ) {
  51838. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51839. }
  51840. xrFrame = null;
  51841. }
  51842. const animation = new WebGLAnimation();
  51843. animation.setAnimationLoop( onAnimationFrame );
  51844. this.setAnimationLoop = function ( callback ) {
  51845. onAnimationFrameCallback = callback;
  51846. };
  51847. this.dispose = function () {};
  51848. }
  51849. }
  51850. const _e1 = /*@__PURE__*/ new Euler();
  51851. const _m1 = /*@__PURE__*/ new Matrix4();
  51852. function WebGLMaterials( renderer, properties ) {
  51853. function refreshTransformUniform( map, uniform ) {
  51854. if ( map.matrixAutoUpdate === true ) {
  51855. map.updateMatrix();
  51856. }
  51857. uniform.value.copy( map.matrix );
  51858. }
  51859. function refreshFogUniforms( uniforms, fog ) {
  51860. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51861. if ( fog.isFog ) {
  51862. uniforms.fogNear.value = fog.near;
  51863. uniforms.fogFar.value = fog.far;
  51864. } else if ( fog.isFogExp2 ) {
  51865. uniforms.fogDensity.value = fog.density;
  51866. }
  51867. }
  51868. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51869. if ( material.isMeshBasicMaterial ) {
  51870. refreshUniformsCommon( uniforms, material );
  51871. } else if ( material.isMeshLambertMaterial ) {
  51872. refreshUniformsCommon( uniforms, material );
  51873. } else if ( material.isMeshToonMaterial ) {
  51874. refreshUniformsCommon( uniforms, material );
  51875. refreshUniformsToon( uniforms, material );
  51876. } else if ( material.isMeshPhongMaterial ) {
  51877. refreshUniformsCommon( uniforms, material );
  51878. refreshUniformsPhong( uniforms, material );
  51879. } else if ( material.isMeshStandardMaterial ) {
  51880. refreshUniformsCommon( uniforms, material );
  51881. refreshUniformsStandard( uniforms, material );
  51882. if ( material.isMeshPhysicalMaterial ) {
  51883. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51884. }
  51885. } else if ( material.isMeshMatcapMaterial ) {
  51886. refreshUniformsCommon( uniforms, material );
  51887. refreshUniformsMatcap( uniforms, material );
  51888. } else if ( material.isMeshDepthMaterial ) {
  51889. refreshUniformsCommon( uniforms, material );
  51890. } else if ( material.isMeshDistanceMaterial ) {
  51891. refreshUniformsCommon( uniforms, material );
  51892. refreshUniformsDistance( uniforms, material );
  51893. } else if ( material.isMeshNormalMaterial ) {
  51894. refreshUniformsCommon( uniforms, material );
  51895. } else if ( material.isLineBasicMaterial ) {
  51896. refreshUniformsLine( uniforms, material );
  51897. if ( material.isLineDashedMaterial ) {
  51898. refreshUniformsDash( uniforms, material );
  51899. }
  51900. } else if ( material.isPointsMaterial ) {
  51901. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51902. } else if ( material.isSpriteMaterial ) {
  51903. refreshUniformsSprites( uniforms, material );
  51904. } else if ( material.isShadowMaterial ) {
  51905. uniforms.color.value.copy( material.color );
  51906. uniforms.opacity.value = material.opacity;
  51907. } else if ( material.isShaderMaterial ) {
  51908. material.uniformsNeedUpdate = false; // #15581
  51909. }
  51910. }
  51911. function refreshUniformsCommon( uniforms, material ) {
  51912. uniforms.opacity.value = material.opacity;
  51913. if ( material.color ) {
  51914. uniforms.diffuse.value.copy( material.color );
  51915. }
  51916. if ( material.emissive ) {
  51917. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51918. }
  51919. if ( material.map ) {
  51920. uniforms.map.value = material.map;
  51921. refreshTransformUniform( material.map, uniforms.mapTransform );
  51922. }
  51923. if ( material.alphaMap ) {
  51924. uniforms.alphaMap.value = material.alphaMap;
  51925. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51926. }
  51927. if ( material.bumpMap ) {
  51928. uniforms.bumpMap.value = material.bumpMap;
  51929. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51930. uniforms.bumpScale.value = material.bumpScale;
  51931. if ( material.side === BackSide ) {
  51932. uniforms.bumpScale.value *= -1;
  51933. }
  51934. }
  51935. if ( material.normalMap ) {
  51936. uniforms.normalMap.value = material.normalMap;
  51937. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51938. uniforms.normalScale.value.copy( material.normalScale );
  51939. if ( material.side === BackSide ) {
  51940. uniforms.normalScale.value.negate();
  51941. }
  51942. }
  51943. if ( material.displacementMap ) {
  51944. uniforms.displacementMap.value = material.displacementMap;
  51945. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51946. uniforms.displacementScale.value = material.displacementScale;
  51947. uniforms.displacementBias.value = material.displacementBias;
  51948. }
  51949. if ( material.emissiveMap ) {
  51950. uniforms.emissiveMap.value = material.emissiveMap;
  51951. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51952. }
  51953. if ( material.specularMap ) {
  51954. uniforms.specularMap.value = material.specularMap;
  51955. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51956. }
  51957. if ( material.alphaTest > 0 ) {
  51958. uniforms.alphaTest.value = material.alphaTest;
  51959. }
  51960. const materialProperties = properties.get( material );
  51961. const envMap = materialProperties.envMap;
  51962. const envMapRotation = materialProperties.envMapRotation;
  51963. if ( envMap ) {
  51964. uniforms.envMap.value = envMap;
  51965. _e1.copy( envMapRotation );
  51966. // accommodate left-handed frame
  51967. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51968. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51969. // environment maps which are not cube render targets or PMREMs follow a different convention
  51970. _e1.y *= -1;
  51971. _e1.z *= -1;
  51972. }
  51973. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51974. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51975. uniforms.reflectivity.value = material.reflectivity;
  51976. uniforms.ior.value = material.ior;
  51977. uniforms.refractionRatio.value = material.refractionRatio;
  51978. }
  51979. if ( material.lightMap ) {
  51980. uniforms.lightMap.value = material.lightMap;
  51981. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51982. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51983. }
  51984. if ( material.aoMap ) {
  51985. uniforms.aoMap.value = material.aoMap;
  51986. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51987. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51988. }
  51989. }
  51990. function refreshUniformsLine( uniforms, material ) {
  51991. uniforms.diffuse.value.copy( material.color );
  51992. uniforms.opacity.value = material.opacity;
  51993. if ( material.map ) {
  51994. uniforms.map.value = material.map;
  51995. refreshTransformUniform( material.map, uniforms.mapTransform );
  51996. }
  51997. }
  51998. function refreshUniformsDash( uniforms, material ) {
  51999. uniforms.dashSize.value = material.dashSize;
  52000. uniforms.totalSize.value = material.dashSize + material.gapSize;
  52001. uniforms.scale.value = material.scale;
  52002. }
  52003. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  52004. uniforms.diffuse.value.copy( material.color );
  52005. uniforms.opacity.value = material.opacity;
  52006. uniforms.size.value = material.size * pixelRatio;
  52007. uniforms.scale.value = height * 0.5;
  52008. if ( material.map ) {
  52009. uniforms.map.value = material.map;
  52010. refreshTransformUniform( material.map, uniforms.uvTransform );
  52011. }
  52012. if ( material.alphaMap ) {
  52013. uniforms.alphaMap.value = material.alphaMap;
  52014. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52015. }
  52016. if ( material.alphaTest > 0 ) {
  52017. uniforms.alphaTest.value = material.alphaTest;
  52018. }
  52019. }
  52020. function refreshUniformsSprites( uniforms, material ) {
  52021. uniforms.diffuse.value.copy( material.color );
  52022. uniforms.opacity.value = material.opacity;
  52023. uniforms.rotation.value = material.rotation;
  52024. if ( material.map ) {
  52025. uniforms.map.value = material.map;
  52026. refreshTransformUniform( material.map, uniforms.mapTransform );
  52027. }
  52028. if ( material.alphaMap ) {
  52029. uniforms.alphaMap.value = material.alphaMap;
  52030. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52031. }
  52032. if ( material.alphaTest > 0 ) {
  52033. uniforms.alphaTest.value = material.alphaTest;
  52034. }
  52035. }
  52036. function refreshUniformsPhong( uniforms, material ) {
  52037. uniforms.specular.value.copy( material.specular );
  52038. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  52039. }
  52040. function refreshUniformsToon( uniforms, material ) {
  52041. if ( material.gradientMap ) {
  52042. uniforms.gradientMap.value = material.gradientMap;
  52043. }
  52044. }
  52045. function refreshUniformsStandard( uniforms, material ) {
  52046. uniforms.metalness.value = material.metalness;
  52047. if ( material.metalnessMap ) {
  52048. uniforms.metalnessMap.value = material.metalnessMap;
  52049. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  52050. }
  52051. uniforms.roughness.value = material.roughness;
  52052. if ( material.roughnessMap ) {
  52053. uniforms.roughnessMap.value = material.roughnessMap;
  52054. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  52055. }
  52056. if ( material.envMap ) {
  52057. //uniforms.envMap.value = material.envMap; // part of uniforms common
  52058. uniforms.envMapIntensity.value = material.envMapIntensity;
  52059. }
  52060. }
  52061. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  52062. uniforms.ior.value = material.ior; // also part of uniforms common
  52063. if ( material.sheen > 0 ) {
  52064. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  52065. uniforms.sheenRoughness.value = material.sheenRoughness;
  52066. if ( material.sheenColorMap ) {
  52067. uniforms.sheenColorMap.value = material.sheenColorMap;
  52068. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  52069. }
  52070. if ( material.sheenRoughnessMap ) {
  52071. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  52072. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  52073. }
  52074. }
  52075. if ( material.clearcoat > 0 ) {
  52076. uniforms.clearcoat.value = material.clearcoat;
  52077. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  52078. if ( material.clearcoatMap ) {
  52079. uniforms.clearcoatMap.value = material.clearcoatMap;
  52080. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  52081. }
  52082. if ( material.clearcoatRoughnessMap ) {
  52083. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  52084. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  52085. }
  52086. if ( material.clearcoatNormalMap ) {
  52087. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  52088. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  52089. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  52090. if ( material.side === BackSide ) {
  52091. uniforms.clearcoatNormalScale.value.negate();
  52092. }
  52093. }
  52094. }
  52095. if ( material.dispersion > 0 ) {
  52096. uniforms.dispersion.value = material.dispersion;
  52097. }
  52098. if ( material.iridescence > 0 ) {
  52099. uniforms.iridescence.value = material.iridescence;
  52100. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  52101. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  52102. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  52103. if ( material.iridescenceMap ) {
  52104. uniforms.iridescenceMap.value = material.iridescenceMap;
  52105. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  52106. }
  52107. if ( material.iridescenceThicknessMap ) {
  52108. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  52109. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  52110. }
  52111. }
  52112. if ( material.transmission > 0 ) {
  52113. uniforms.transmission.value = material.transmission;
  52114. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  52115. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  52116. if ( material.transmissionMap ) {
  52117. uniforms.transmissionMap.value = material.transmissionMap;
  52118. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  52119. }
  52120. uniforms.thickness.value = material.thickness;
  52121. if ( material.thicknessMap ) {
  52122. uniforms.thicknessMap.value = material.thicknessMap;
  52123. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  52124. }
  52125. uniforms.attenuationDistance.value = material.attenuationDistance;
  52126. uniforms.attenuationColor.value.copy( material.attenuationColor );
  52127. }
  52128. if ( material.anisotropy > 0 ) {
  52129. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  52130. if ( material.anisotropyMap ) {
  52131. uniforms.anisotropyMap.value = material.anisotropyMap;
  52132. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  52133. }
  52134. }
  52135. uniforms.specularIntensity.value = material.specularIntensity;
  52136. uniforms.specularColor.value.copy( material.specularColor );
  52137. if ( material.specularColorMap ) {
  52138. uniforms.specularColorMap.value = material.specularColorMap;
  52139. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  52140. }
  52141. if ( material.specularIntensityMap ) {
  52142. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  52143. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  52144. }
  52145. }
  52146. function refreshUniformsMatcap( uniforms, material ) {
  52147. if ( material.matcap ) {
  52148. uniforms.matcap.value = material.matcap;
  52149. }
  52150. }
  52151. function refreshUniformsDistance( uniforms, material ) {
  52152. const light = properties.get( material ).light;
  52153. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  52154. uniforms.nearDistance.value = light.shadow.camera.near;
  52155. uniforms.farDistance.value = light.shadow.camera.far;
  52156. }
  52157. return {
  52158. refreshFogUniforms: refreshFogUniforms,
  52159. refreshMaterialUniforms: refreshMaterialUniforms
  52160. };
  52161. }
  52162. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  52163. let buffers = {};
  52164. let updateList = {};
  52165. let allocatedBindingPoints = [];
  52166. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  52167. function bind( uniformsGroup, program ) {
  52168. const webglProgram = program.program;
  52169. state.uniformBlockBinding( uniformsGroup, webglProgram );
  52170. }
  52171. function update( uniformsGroup, program ) {
  52172. let buffer = buffers[ uniformsGroup.id ];
  52173. if ( buffer === undefined ) {
  52174. prepareUniformsGroup( uniformsGroup );
  52175. buffer = createBuffer( uniformsGroup );
  52176. buffers[ uniformsGroup.id ] = buffer;
  52177. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  52178. }
  52179. // ensure to update the binding points/block indices mapping for this program
  52180. const webglProgram = program.program;
  52181. state.updateUBOMapping( uniformsGroup, webglProgram );
  52182. // update UBO once per frame
  52183. const frame = info.render.frame;
  52184. if ( updateList[ uniformsGroup.id ] !== frame ) {
  52185. updateBufferData( uniformsGroup );
  52186. updateList[ uniformsGroup.id ] = frame;
  52187. }
  52188. }
  52189. function createBuffer( uniformsGroup ) {
  52190. // the setup of an UBO is independent of a particular shader program but global
  52191. const bindingPointIndex = allocateBindingPointIndex();
  52192. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  52193. const buffer = gl.createBuffer();
  52194. const size = uniformsGroup.__size;
  52195. const usage = uniformsGroup.usage;
  52196. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52197. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  52198. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52199. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  52200. return buffer;
  52201. }
  52202. function allocateBindingPointIndex() {
  52203. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  52204. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  52205. allocatedBindingPoints.push( i );
  52206. return i;
  52207. }
  52208. }
  52209. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  52210. return 0;
  52211. }
  52212. function updateBufferData( uniformsGroup ) {
  52213. const buffer = buffers[ uniformsGroup.id ];
  52214. const uniforms = uniformsGroup.uniforms;
  52215. const cache = uniformsGroup.__cache;
  52216. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52217. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  52218. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52219. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52220. const uniform = uniformArray[ j ];
  52221. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  52222. const offset = uniform.__offset;
  52223. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52224. let arrayOffset = 0;
  52225. for ( let k = 0; k < values.length; k ++ ) {
  52226. const value = values[ k ];
  52227. const info = getUniformSize( value );
  52228. // TODO add integer and struct support
  52229. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52230. uniform.__data[ 0 ] = value;
  52231. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  52232. } else if ( value.isMatrix3 ) {
  52233. // manually converting 3x3 to 3x4
  52234. uniform.__data[ 0 ] = value.elements[ 0 ];
  52235. uniform.__data[ 1 ] = value.elements[ 1 ];
  52236. uniform.__data[ 2 ] = value.elements[ 2 ];
  52237. uniform.__data[ 3 ] = 0;
  52238. uniform.__data[ 4 ] = value.elements[ 3 ];
  52239. uniform.__data[ 5 ] = value.elements[ 4 ];
  52240. uniform.__data[ 6 ] = value.elements[ 5 ];
  52241. uniform.__data[ 7 ] = 0;
  52242. uniform.__data[ 8 ] = value.elements[ 6 ];
  52243. uniform.__data[ 9 ] = value.elements[ 7 ];
  52244. uniform.__data[ 10 ] = value.elements[ 8 ];
  52245. uniform.__data[ 11 ] = 0;
  52246. } else {
  52247. value.toArray( uniform.__data, arrayOffset );
  52248. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  52249. }
  52250. }
  52251. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  52252. }
  52253. }
  52254. }
  52255. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52256. }
  52257. function hasUniformChanged( uniform, index, indexArray, cache ) {
  52258. const value = uniform.value;
  52259. const indexString = index + '_' + indexArray;
  52260. if ( cache[ indexString ] === undefined ) {
  52261. // cache entry does not exist so far
  52262. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52263. cache[ indexString ] = value;
  52264. } else {
  52265. cache[ indexString ] = value.clone();
  52266. }
  52267. return true;
  52268. } else {
  52269. const cachedObject = cache[ indexString ];
  52270. // compare current value with cached entry
  52271. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52272. if ( cachedObject !== value ) {
  52273. cache[ indexString ] = value;
  52274. return true;
  52275. }
  52276. } else {
  52277. if ( cachedObject.equals( value ) === false ) {
  52278. cachedObject.copy( value );
  52279. return true;
  52280. }
  52281. }
  52282. }
  52283. return false;
  52284. }
  52285. function prepareUniformsGroup( uniformsGroup ) {
  52286. // determine total buffer size according to the STD140 layout
  52287. // Hint: STD140 is the only supported layout in WebGL 2
  52288. const uniforms = uniformsGroup.uniforms;
  52289. let offset = 0; // global buffer offset in bytes
  52290. const chunkSize = 16; // size of a chunk in bytes
  52291. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52292. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52293. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52294. const uniform = uniformArray[ j ];
  52295. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52296. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52297. const value = values[ k ];
  52298. const info = getUniformSize( value );
  52299. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52300. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52301. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52302. offset += chunkPadding;
  52303. // Check for chunk overflow
  52304. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52305. // Add padding and adjust offset
  52306. offset += ( chunkSize - chunkStart );
  52307. }
  52308. // the following two properties will be used for partial buffer updates
  52309. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52310. uniform.__offset = offset;
  52311. // Update the global offset
  52312. offset += info.storage;
  52313. }
  52314. }
  52315. }
  52316. // ensure correct final padding
  52317. const chunkOffset = offset % chunkSize;
  52318. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52319. //
  52320. uniformsGroup.__size = offset;
  52321. uniformsGroup.__cache = {};
  52322. return this;
  52323. }
  52324. function getUniformSize( value ) {
  52325. const info = {
  52326. boundary: 0, // bytes
  52327. storage: 0 // bytes
  52328. };
  52329. // determine sizes according to STD140
  52330. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52331. // float/int/bool
  52332. info.boundary = 4;
  52333. info.storage = 4;
  52334. } else if ( value.isVector2 ) {
  52335. // vec2
  52336. info.boundary = 8;
  52337. info.storage = 8;
  52338. } else if ( value.isVector3 || value.isColor ) {
  52339. // vec3
  52340. info.boundary = 16;
  52341. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52342. } else if ( value.isVector4 ) {
  52343. // vec4
  52344. info.boundary = 16;
  52345. info.storage = 16;
  52346. } else if ( value.isMatrix3 ) {
  52347. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52348. info.boundary = 48;
  52349. info.storage = 48;
  52350. } else if ( value.isMatrix4 ) {
  52351. // mat4
  52352. info.boundary = 64;
  52353. info.storage = 64;
  52354. } else if ( value.isTexture ) {
  52355. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52356. } else {
  52357. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52358. }
  52359. return info;
  52360. }
  52361. function onUniformsGroupsDispose( event ) {
  52362. const uniformsGroup = event.target;
  52363. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52364. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52365. allocatedBindingPoints.splice( index, 1 );
  52366. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52367. delete buffers[ uniformsGroup.id ];
  52368. delete updateList[ uniformsGroup.id ];
  52369. }
  52370. function dispose() {
  52371. for ( const id in buffers ) {
  52372. gl.deleteBuffer( buffers[ id ] );
  52373. }
  52374. allocatedBindingPoints = [];
  52375. buffers = {};
  52376. updateList = {};
  52377. }
  52378. return {
  52379. bind: bind,
  52380. update: update,
  52381. dispose: dispose
  52382. };
  52383. }
  52384. /**
  52385. * Precomputed DFG LUT for Image-Based Lighting
  52386. * Resolution: 16x16
  52387. * Samples: 4096 per texel
  52388. * Format: RG16F (2 half floats per texel: scale, bias)
  52389. */
  52390. const DATA = new Uint16Array( [
  52391. 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,
  52392. 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,
  52393. 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,
  52394. 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,
  52395. 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,
  52396. 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,
  52397. 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,
  52398. 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,
  52399. 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,
  52400. 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,
  52401. 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,
  52402. 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,
  52403. 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,
  52404. 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,
  52405. 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,
  52406. 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
  52407. ] );
  52408. let lut = null;
  52409. function getDFGLUT() {
  52410. if ( lut === null ) {
  52411. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  52412. lut.name = 'DFG_LUT';
  52413. lut.minFilter = LinearFilter;
  52414. lut.magFilter = LinearFilter;
  52415. lut.wrapS = ClampToEdgeWrapping;
  52416. lut.wrapT = ClampToEdgeWrapping;
  52417. lut.generateMipmaps = false;
  52418. lut.needsUpdate = true;
  52419. }
  52420. return lut;
  52421. }
  52422. /**
  52423. * This renderer uses WebGL 2 to display scenes.
  52424. *
  52425. * WebGL 1 is not supported since `r163`.
  52426. */
  52427. class WebGLRenderer {
  52428. /**
  52429. * Constructs a new WebGL renderer.
  52430. *
  52431. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52432. */
  52433. constructor( parameters = {} ) {
  52434. const {
  52435. canvas = createCanvasElement(),
  52436. context = null,
  52437. depth = true,
  52438. stencil = false,
  52439. alpha = false,
  52440. antialias = false,
  52441. premultipliedAlpha = true,
  52442. preserveDrawingBuffer = false,
  52443. powerPreference = 'default',
  52444. failIfMajorPerformanceCaveat = false,
  52445. reversedDepthBuffer = false,
  52446. outputBufferType = UnsignedByteType,
  52447. } = parameters;
  52448. /**
  52449. * This flag can be used for type testing.
  52450. *
  52451. * @type {boolean}
  52452. * @readonly
  52453. * @default true
  52454. */
  52455. this.isWebGLRenderer = true;
  52456. let _alpha;
  52457. if ( context !== null ) {
  52458. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52459. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52460. }
  52461. _alpha = context.getContextAttributes().alpha;
  52462. } else {
  52463. _alpha = alpha;
  52464. }
  52465. const _outputBufferType = outputBufferType;
  52466. const INTEGER_FORMATS = new Set( [
  52467. RGBAIntegerFormat,
  52468. RGIntegerFormat,
  52469. RedIntegerFormat
  52470. ] );
  52471. const UNSIGNED_TYPES = new Set( [
  52472. UnsignedByteType,
  52473. UnsignedIntType,
  52474. UnsignedShortType,
  52475. UnsignedInt248Type,
  52476. UnsignedShort4444Type,
  52477. UnsignedShort5551Type
  52478. ] );
  52479. const uintClearColor = new Uint32Array( 4 );
  52480. const intClearColor = new Int32Array( 4 );
  52481. let currentRenderList = null;
  52482. let currentRenderState = null;
  52483. // render() can be called from within a callback triggered by another render.
  52484. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52485. const renderListStack = [];
  52486. const renderStateStack = [];
  52487. // internal render target for non-UnsignedByteType color buffer
  52488. let output = null;
  52489. // public properties
  52490. /**
  52491. * A canvas where the renderer draws its output. This is automatically created by the renderer
  52492. * in the constructor (if not provided already); you just need to add it to your page like so:
  52493. * ```js
  52494. * document.body.appendChild( renderer.domElement );
  52495. * ```
  52496. *
  52497. * @type {HTMLCanvasElement|OffscreenCanvas}
  52498. */
  52499. this.domElement = canvas;
  52500. /**
  52501. * A object with debug configuration settings.
  52502. *
  52503. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52504. * checked for errors during compilation and linkage process. It may be useful to disable
  52505. * this check in production for performance gain. It is strongly recommended to keep these
  52506. * checks enabled during development. If the shader does not compile and link, it will not
  52507. * work and associated material will not render.
  52508. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52509. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52510. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52511. * Assigning a custom function disables the default error reporting.
  52512. *
  52513. * @type {Object}
  52514. */
  52515. this.debug = {
  52516. /**
  52517. * Enables error checking and reporting when shader programs are being compiled.
  52518. * @type {boolean}
  52519. */
  52520. checkShaderErrors: true,
  52521. /**
  52522. * Callback for custom error reporting.
  52523. * @type {?Function}
  52524. */
  52525. onShaderError: null
  52526. };
  52527. // clearing
  52528. /**
  52529. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52530. *
  52531. * @type {boolean}
  52532. * @default true
  52533. */
  52534. this.autoClear = true;
  52535. /**
  52536. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52537. * the color buffer or not.
  52538. *
  52539. * @type {boolean}
  52540. * @default true
  52541. */
  52542. this.autoClearColor = true;
  52543. /**
  52544. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52545. * the depth buffer or not.
  52546. *
  52547. * @type {boolean}
  52548. * @default true
  52549. */
  52550. this.autoClearDepth = true;
  52551. /**
  52552. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52553. * the stencil buffer or not.
  52554. *
  52555. * @type {boolean}
  52556. * @default true
  52557. */
  52558. this.autoClearStencil = true;
  52559. // scene graph
  52560. /**
  52561. * Whether the renderer should sort objects or not.
  52562. *
  52563. * Note: Sorting is used to attempt to properly render objects that have some
  52564. * degree of transparency. By definition, sorting objects may not work in all
  52565. * cases. Depending on the needs of application, it may be necessary to turn
  52566. * off sorting and use other methods to deal with transparency rendering e.g.
  52567. * manually determining each object's rendering order.
  52568. *
  52569. * @type {boolean}
  52570. * @default true
  52571. */
  52572. this.sortObjects = true;
  52573. // user-defined clipping
  52574. /**
  52575. * User-defined clipping planes specified in world space. These planes apply globally.
  52576. * Points in space whose dot product with the plane is negative are cut away.
  52577. *
  52578. * @type {Array<Plane>}
  52579. */
  52580. this.clippingPlanes = [];
  52581. /**
  52582. * Whether the renderer respects object-level clipping planes or not.
  52583. *
  52584. * @type {boolean}
  52585. * @default false
  52586. */
  52587. this.localClippingEnabled = false;
  52588. // tone mapping
  52589. /**
  52590. * The tone mapping technique of the renderer.
  52591. *
  52592. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52593. * @default NoToneMapping
  52594. */
  52595. this.toneMapping = NoToneMapping;
  52596. /**
  52597. * Exposure level of tone mapping.
  52598. *
  52599. * @type {number}
  52600. * @default 1
  52601. */
  52602. this.toneMappingExposure = 1.0;
  52603. // transmission
  52604. /**
  52605. * The normalized resolution scale for the transmission render target, measured in percentage
  52606. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52607. * when using {@link MeshPhysicalMaterial#transmission}.
  52608. *
  52609. * @type {number}
  52610. * @default 1
  52611. */
  52612. this.transmissionResolutionScale = 1.0;
  52613. // internal properties
  52614. const _this = this;
  52615. let _isContextLost = false;
  52616. // internal state cache
  52617. this._outputColorSpace = SRGBColorSpace;
  52618. let _currentActiveCubeFace = 0;
  52619. let _currentActiveMipmapLevel = 0;
  52620. let _currentRenderTarget = null;
  52621. let _currentMaterialId = -1;
  52622. let _currentCamera = null;
  52623. const _currentViewport = new Vector4();
  52624. const _currentScissor = new Vector4();
  52625. let _currentScissorTest = null;
  52626. const _currentClearColor = new Color( 0x000000 );
  52627. let _currentClearAlpha = 0;
  52628. //
  52629. let _width = canvas.width;
  52630. let _height = canvas.height;
  52631. let _pixelRatio = 1;
  52632. let _opaqueSort = null;
  52633. let _transparentSort = null;
  52634. const _viewport = new Vector4( 0, 0, _width, _height );
  52635. const _scissor = new Vector4( 0, 0, _width, _height );
  52636. let _scissorTest = false;
  52637. // frustum
  52638. const _frustum = new Frustum();
  52639. // clipping
  52640. let _clippingEnabled = false;
  52641. let _localClippingEnabled = false;
  52642. // camera matrices cache
  52643. const _projScreenMatrix = new Matrix4();
  52644. const _vector3 = new Vector3();
  52645. const _vector4 = new Vector4();
  52646. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  52647. let _renderBackground = false;
  52648. function getTargetPixelRatio() {
  52649. return _currentRenderTarget === null ? _pixelRatio : 1;
  52650. }
  52651. // initialize
  52652. let _gl = context;
  52653. function getContext( contextName, contextAttributes ) {
  52654. return canvas.getContext( contextName, contextAttributes );
  52655. }
  52656. try {
  52657. const contextAttributes = {
  52658. alpha: true,
  52659. depth,
  52660. stencil,
  52661. antialias,
  52662. premultipliedAlpha,
  52663. preserveDrawingBuffer,
  52664. powerPreference,
  52665. failIfMajorPerformanceCaveat,
  52666. };
  52667. // OffscreenCanvas does not have setAttribute, see #22811
  52668. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  52669. // event listeners must be registered before WebGL context is created, see #12753
  52670. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  52671. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  52672. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52673. if ( _gl === null ) {
  52674. const contextName = 'webgl2';
  52675. _gl = getContext( contextName, contextAttributes );
  52676. if ( _gl === null ) {
  52677. if ( getContext( contextName ) ) {
  52678. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  52679. } else {
  52680. throw new Error( 'Error creating WebGL context.' );
  52681. }
  52682. }
  52683. }
  52684. } catch ( e ) {
  52685. error( 'WebGLRenderer: ' + e.message );
  52686. throw e;
  52687. }
  52688. let extensions, capabilities, state, info;
  52689. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  52690. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  52691. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  52692. let utils, bindingStates, uniformsGroups;
  52693. function initGLContext() {
  52694. extensions = new WebGLExtensions( _gl );
  52695. extensions.init();
  52696. utils = new WebGLUtils( _gl, extensions );
  52697. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  52698. state = new WebGLState( _gl, extensions );
  52699. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  52700. state.buffers.depth.setReversed( true );
  52701. }
  52702. info = new WebGLInfo( _gl );
  52703. properties = new WebGLProperties();
  52704. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  52705. cubemaps = new WebGLCubeMaps( _this );
  52706. cubeuvmaps = new WebGLCubeUVMaps( _this );
  52707. attributes = new WebGLAttributes( _gl );
  52708. bindingStates = new WebGLBindingStates( _gl, attributes );
  52709. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  52710. objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info );
  52711. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  52712. clipping = new WebGLClipping( properties );
  52713. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  52714. materials = new WebGLMaterials( _this, properties );
  52715. renderLists = new WebGLRenderLists();
  52716. renderStates = new WebGLRenderStates( extensions );
  52717. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  52718. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  52719. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  52720. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  52721. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  52722. info.programs = programCache.programs;
  52723. /**
  52724. * Holds details about the capabilities of the current rendering context.
  52725. *
  52726. * @name WebGLRenderer#capabilities
  52727. * @type {WebGLRenderer~Capabilities}
  52728. */
  52729. _this.capabilities = capabilities;
  52730. /**
  52731. * Provides methods for retrieving and testing WebGL extensions.
  52732. *
  52733. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  52734. * and return the extension object if available.
  52735. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  52736. *
  52737. * @name WebGLRenderer#extensions
  52738. * @type {Object}
  52739. */
  52740. _this.extensions = extensions;
  52741. /**
  52742. * Used to track properties of other objects like native WebGL objects.
  52743. *
  52744. * @name WebGLRenderer#properties
  52745. * @type {Object}
  52746. */
  52747. _this.properties = properties;
  52748. /**
  52749. * Manages the render lists of the renderer.
  52750. *
  52751. * @name WebGLRenderer#renderLists
  52752. * @type {Object}
  52753. */
  52754. _this.renderLists = renderLists;
  52755. /**
  52756. * Interface for managing shadows.
  52757. *
  52758. * @name WebGLRenderer#shadowMap
  52759. * @type {WebGLRenderer~ShadowMap}
  52760. */
  52761. _this.shadowMap = shadowMap;
  52762. /**
  52763. * Interface for managing the WebGL state.
  52764. *
  52765. * @name WebGLRenderer#state
  52766. * @type {Object}
  52767. */
  52768. _this.state = state;
  52769. /**
  52770. * Holds a series of statistical information about the GPU memory
  52771. * and the rendering process. Useful for debugging and monitoring.
  52772. *
  52773. * By default these data are reset at each render call but when having
  52774. * multiple render passes per frame (e.g. when using post processing) it can
  52775. * be preferred to reset with a custom pattern. First, set `autoReset` to
  52776. * `false`.
  52777. * ```js
  52778. * renderer.info.autoReset = false;
  52779. * ```
  52780. * Call `reset()` whenever you have finished to render a single frame.
  52781. * ```js
  52782. * renderer.info.reset();
  52783. * ```
  52784. *
  52785. * @name WebGLRenderer#info
  52786. * @type {WebGLRenderer~Info}
  52787. */
  52788. _this.info = info;
  52789. }
  52790. initGLContext();
  52791. // initialize internal render target for non-UnsignedByteType color buffer
  52792. if ( _outputBufferType !== UnsignedByteType ) {
  52793. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  52794. }
  52795. // xr
  52796. const xr = new WebXRManager( _this, _gl );
  52797. /**
  52798. * A reference to the XR manager.
  52799. *
  52800. * @type {WebXRManager}
  52801. */
  52802. this.xr = xr;
  52803. /**
  52804. * Returns the rendering context.
  52805. *
  52806. * @return {WebGL2RenderingContext} The rendering context.
  52807. */
  52808. this.getContext = function () {
  52809. return _gl;
  52810. };
  52811. /**
  52812. * Returns the rendering context attributes.
  52813. *
  52814. * @return {WebGLContextAttributes} The rendering context attributes.
  52815. */
  52816. this.getContextAttributes = function () {
  52817. return _gl.getContextAttributes();
  52818. };
  52819. /**
  52820. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52821. */
  52822. this.forceContextLoss = function () {
  52823. const extension = extensions.get( 'WEBGL_lose_context' );
  52824. if ( extension ) extension.loseContext();
  52825. };
  52826. /**
  52827. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52828. */
  52829. this.forceContextRestore = function () {
  52830. const extension = extensions.get( 'WEBGL_lose_context' );
  52831. if ( extension ) extension.restoreContext();
  52832. };
  52833. /**
  52834. * Returns the pixel ratio.
  52835. *
  52836. * @return {number} The pixel ratio.
  52837. */
  52838. this.getPixelRatio = function () {
  52839. return _pixelRatio;
  52840. };
  52841. /**
  52842. * Sets the given pixel ratio and resizes the canvas if necessary.
  52843. *
  52844. * @param {number} value - The pixel ratio.
  52845. */
  52846. this.setPixelRatio = function ( value ) {
  52847. if ( value === undefined ) return;
  52848. _pixelRatio = value;
  52849. this.setSize( _width, _height, false );
  52850. };
  52851. /**
  52852. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52853. *
  52854. * @param {Vector2} target - The method writes the result in this target object.
  52855. * @return {Vector2} The renderer's size in logical pixels.
  52856. */
  52857. this.getSize = function ( target ) {
  52858. return target.set( _width, _height );
  52859. };
  52860. /**
  52861. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52862. * into account, and also sets the viewport to fit that size, starting in (0,
  52863. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52864. *
  52865. * @param {number} width - The width in logical pixels.
  52866. * @param {number} height - The height in logical pixels.
  52867. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52868. */
  52869. this.setSize = function ( width, height, updateStyle = true ) {
  52870. if ( xr.isPresenting ) {
  52871. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52872. return;
  52873. }
  52874. _width = width;
  52875. _height = height;
  52876. canvas.width = Math.floor( width * _pixelRatio );
  52877. canvas.height = Math.floor( height * _pixelRatio );
  52878. if ( updateStyle === true ) {
  52879. canvas.style.width = width + 'px';
  52880. canvas.style.height = height + 'px';
  52881. }
  52882. if ( output !== null ) {
  52883. output.setSize( canvas.width, canvas.height );
  52884. }
  52885. this.setViewport( 0, 0, width, height );
  52886. };
  52887. /**
  52888. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52889. *
  52890. * @param {Vector2} target - The method writes the result in this target object.
  52891. * @return {Vector2} The drawing buffer size.
  52892. */
  52893. this.getDrawingBufferSize = function ( target ) {
  52894. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52895. };
  52896. /**
  52897. * This method allows to define the drawing buffer size by specifying
  52898. * width, height and pixel ratio all at once. The size of the drawing
  52899. * buffer is computed with this formula:
  52900. * ```js
  52901. * size.x = width * pixelRatio;
  52902. * size.y = height * pixelRatio;
  52903. * ```
  52904. *
  52905. * @param {number} width - The width in logical pixels.
  52906. * @param {number} height - The height in logical pixels.
  52907. * @param {number} pixelRatio - The pixel ratio.
  52908. */
  52909. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52910. _width = width;
  52911. _height = height;
  52912. _pixelRatio = pixelRatio;
  52913. canvas.width = Math.floor( width * pixelRatio );
  52914. canvas.height = Math.floor( height * pixelRatio );
  52915. this.setViewport( 0, 0, width, height );
  52916. };
  52917. /**
  52918. * Sets the post-processing effects to be applied after rendering.
  52919. *
  52920. * @param {Array} effects - An array of post-processing effects.
  52921. */
  52922. this.setEffects = function ( effects ) {
  52923. if ( _outputBufferType === UnsignedByteType ) {
  52924. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  52925. return;
  52926. }
  52927. if ( effects ) {
  52928. for ( let i = 0; i < effects.length; i ++ ) {
  52929. if ( effects[ i ].isOutputPass === true ) {
  52930. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  52931. break;
  52932. }
  52933. }
  52934. }
  52935. output.setEffects( effects || [] );
  52936. };
  52937. /**
  52938. * Returns the current viewport definition.
  52939. *
  52940. * @param {Vector2} target - The method writes the result in this target object.
  52941. * @return {Vector2} The current viewport definition.
  52942. */
  52943. this.getCurrentViewport = function ( target ) {
  52944. return target.copy( _currentViewport );
  52945. };
  52946. /**
  52947. * Returns the viewport definition.
  52948. *
  52949. * @param {Vector4} target - The method writes the result in this target object.
  52950. * @return {Vector4} The viewport definition.
  52951. */
  52952. this.getViewport = function ( target ) {
  52953. return target.copy( _viewport );
  52954. };
  52955. /**
  52956. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52957. *
  52958. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52959. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52960. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52961. * @param {number} width - The width of the viewport in logical pixel unit.
  52962. * @param {number} height - The height of the viewport in logical pixel unit.
  52963. */
  52964. this.setViewport = function ( x, y, width, height ) {
  52965. if ( x.isVector4 ) {
  52966. _viewport.set( x.x, x.y, x.z, x.w );
  52967. } else {
  52968. _viewport.set( x, y, width, height );
  52969. }
  52970. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52971. };
  52972. /**
  52973. * Returns the scissor region.
  52974. *
  52975. * @param {Vector4} target - The method writes the result in this target object.
  52976. * @return {Vector4} The scissor region.
  52977. */
  52978. this.getScissor = function ( target ) {
  52979. return target.copy( _scissor );
  52980. };
  52981. /**
  52982. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52983. *
  52984. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52985. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52986. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52987. * @param {number} width - The width of the scissor region in logical pixel unit.
  52988. * @param {number} height - The height of the scissor region in logical pixel unit.
  52989. */
  52990. this.setScissor = function ( x, y, width, height ) {
  52991. if ( x.isVector4 ) {
  52992. _scissor.set( x.x, x.y, x.z, x.w );
  52993. } else {
  52994. _scissor.set( x, y, width, height );
  52995. }
  52996. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52997. };
  52998. /**
  52999. * Returns `true` if the scissor test is enabled.
  53000. *
  53001. * @return {boolean} Whether the scissor test is enabled or not.
  53002. */
  53003. this.getScissorTest = function () {
  53004. return _scissorTest;
  53005. };
  53006. /**
  53007. * Enable or disable the scissor test. When this is enabled, only the pixels
  53008. * within the defined scissor area will be affected by further renderer
  53009. * actions.
  53010. *
  53011. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  53012. */
  53013. this.setScissorTest = function ( boolean ) {
  53014. state.setScissorTest( _scissorTest = boolean );
  53015. };
  53016. /**
  53017. * Sets a custom opaque sort function for the render lists. Pass `null`
  53018. * to use the default `painterSortStable` function.
  53019. *
  53020. * @param {?Function} method - The opaque sort function.
  53021. */
  53022. this.setOpaqueSort = function ( method ) {
  53023. _opaqueSort = method;
  53024. };
  53025. /**
  53026. * Sets a custom transparent sort function for the render lists. Pass `null`
  53027. * to use the default `reversePainterSortStable` function.
  53028. *
  53029. * @param {?Function} method - The opaque sort function.
  53030. */
  53031. this.setTransparentSort = function ( method ) {
  53032. _transparentSort = method;
  53033. };
  53034. // Clearing
  53035. /**
  53036. * Returns the clear color.
  53037. *
  53038. * @param {Color} target - The method writes the result in this target object.
  53039. * @return {Color} The clear color.
  53040. */
  53041. this.getClearColor = function ( target ) {
  53042. return target.copy( background.getClearColor() );
  53043. };
  53044. /**
  53045. * Sets the clear color and alpha.
  53046. *
  53047. * @param {Color} color - The clear color.
  53048. * @param {number} [alpha=1] - The clear alpha.
  53049. */
  53050. this.setClearColor = function () {
  53051. background.setClearColor( ...arguments );
  53052. };
  53053. /**
  53054. * Returns the clear alpha. Ranges within `[0,1]`.
  53055. *
  53056. * @return {number} The clear alpha.
  53057. */
  53058. this.getClearAlpha = function () {
  53059. return background.getClearAlpha();
  53060. };
  53061. /**
  53062. * Sets the clear alpha.
  53063. *
  53064. * @param {number} alpha - The clear alpha.
  53065. */
  53066. this.setClearAlpha = function () {
  53067. background.setClearAlpha( ...arguments );
  53068. };
  53069. /**
  53070. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  53071. * This method initializes the buffers to the current clear color values.
  53072. *
  53073. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  53074. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  53075. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  53076. */
  53077. this.clear = function ( color = true, depth = true, stencil = true ) {
  53078. let bits = 0;
  53079. if ( color ) {
  53080. // check if we're trying to clear an integer target
  53081. let isIntegerFormat = false;
  53082. if ( _currentRenderTarget !== null ) {
  53083. const targetFormat = _currentRenderTarget.texture.format;
  53084. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  53085. }
  53086. // use the appropriate clear functions to clear the target if it's a signed
  53087. // or unsigned integer target
  53088. if ( isIntegerFormat ) {
  53089. const targetType = _currentRenderTarget.texture.type;
  53090. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  53091. const clearColor = background.getClearColor();
  53092. const a = background.getClearAlpha();
  53093. const r = clearColor.r;
  53094. const g = clearColor.g;
  53095. const b = clearColor.b;
  53096. if ( isUnsignedType ) {
  53097. uintClearColor[ 0 ] = r;
  53098. uintClearColor[ 1 ] = g;
  53099. uintClearColor[ 2 ] = b;
  53100. uintClearColor[ 3 ] = a;
  53101. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  53102. } else {
  53103. intClearColor[ 0 ] = r;
  53104. intClearColor[ 1 ] = g;
  53105. intClearColor[ 2 ] = b;
  53106. intClearColor[ 3 ] = a;
  53107. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  53108. }
  53109. } else {
  53110. bits |= _gl.COLOR_BUFFER_BIT;
  53111. }
  53112. }
  53113. if ( depth ) {
  53114. bits |= _gl.DEPTH_BUFFER_BIT;
  53115. }
  53116. if ( stencil ) {
  53117. bits |= _gl.STENCIL_BUFFER_BIT;
  53118. this.state.buffers.stencil.setMask( 0xffffffff );
  53119. }
  53120. _gl.clear( bits );
  53121. };
  53122. /**
  53123. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  53124. */
  53125. this.clearColor = function () {
  53126. this.clear( true, false, false );
  53127. };
  53128. /**
  53129. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  53130. */
  53131. this.clearDepth = function () {
  53132. this.clear( false, true, false );
  53133. };
  53134. /**
  53135. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  53136. */
  53137. this.clearStencil = function () {
  53138. this.clear( false, false, true );
  53139. };
  53140. /**
  53141. * Frees the GPU-related resources allocated by this instance. Call this
  53142. * method whenever this instance is no longer used in your app.
  53143. */
  53144. this.dispose = function () {
  53145. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  53146. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  53147. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53148. background.dispose();
  53149. renderLists.dispose();
  53150. renderStates.dispose();
  53151. properties.dispose();
  53152. cubemaps.dispose();
  53153. cubeuvmaps.dispose();
  53154. objects.dispose();
  53155. bindingStates.dispose();
  53156. uniformsGroups.dispose();
  53157. programCache.dispose();
  53158. xr.dispose();
  53159. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  53160. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  53161. animation.stop();
  53162. };
  53163. // Events
  53164. function onContextLost( event ) {
  53165. event.preventDefault();
  53166. log( 'WebGLRenderer: Context Lost.' );
  53167. _isContextLost = true;
  53168. }
  53169. function onContextRestore( /* event */ ) {
  53170. log( 'WebGLRenderer: Context Restored.' );
  53171. _isContextLost = false;
  53172. const infoAutoReset = info.autoReset;
  53173. const shadowMapEnabled = shadowMap.enabled;
  53174. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  53175. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  53176. const shadowMapType = shadowMap.type;
  53177. initGLContext();
  53178. info.autoReset = infoAutoReset;
  53179. shadowMap.enabled = shadowMapEnabled;
  53180. shadowMap.autoUpdate = shadowMapAutoUpdate;
  53181. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  53182. shadowMap.type = shadowMapType;
  53183. }
  53184. function onContextCreationError( event ) {
  53185. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  53186. }
  53187. function onMaterialDispose( event ) {
  53188. const material = event.target;
  53189. material.removeEventListener( 'dispose', onMaterialDispose );
  53190. deallocateMaterial( material );
  53191. }
  53192. // Buffer deallocation
  53193. function deallocateMaterial( material ) {
  53194. releaseMaterialProgramReferences( material );
  53195. properties.remove( material );
  53196. }
  53197. function releaseMaterialProgramReferences( material ) {
  53198. const programs = properties.get( material ).programs;
  53199. if ( programs !== undefined ) {
  53200. programs.forEach( function ( program ) {
  53201. programCache.releaseProgram( program );
  53202. } );
  53203. if ( material.isShaderMaterial ) {
  53204. programCache.releaseShaderCache( material );
  53205. }
  53206. }
  53207. }
  53208. // Buffer rendering
  53209. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  53210. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  53211. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53212. const program = setProgram( camera, scene, geometry, material, object );
  53213. state.setMaterial( material, frontFaceCW );
  53214. //
  53215. let index = geometry.index;
  53216. let rangeFactor = 1;
  53217. if ( material.wireframe === true ) {
  53218. index = geometries.getWireframeAttribute( geometry );
  53219. if ( index === undefined ) return;
  53220. rangeFactor = 2;
  53221. }
  53222. //
  53223. const drawRange = geometry.drawRange;
  53224. const position = geometry.attributes.position;
  53225. let drawStart = drawRange.start * rangeFactor;
  53226. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  53227. if ( group !== null ) {
  53228. drawStart = Math.max( drawStart, group.start * rangeFactor );
  53229. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  53230. }
  53231. if ( index !== null ) {
  53232. drawStart = Math.max( drawStart, 0 );
  53233. drawEnd = Math.min( drawEnd, index.count );
  53234. } else if ( position !== undefined && position !== null ) {
  53235. drawStart = Math.max( drawStart, 0 );
  53236. drawEnd = Math.min( drawEnd, position.count );
  53237. }
  53238. const drawCount = drawEnd - drawStart;
  53239. if ( drawCount < 0 || drawCount === Infinity ) return;
  53240. //
  53241. bindingStates.setup( object, material, program, geometry, index );
  53242. let attribute;
  53243. let renderer = bufferRenderer;
  53244. if ( index !== null ) {
  53245. attribute = attributes.get( index );
  53246. renderer = indexedBufferRenderer;
  53247. renderer.setIndex( attribute );
  53248. }
  53249. //
  53250. if ( object.isMesh ) {
  53251. if ( material.wireframe === true ) {
  53252. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  53253. renderer.setMode( _gl.LINES );
  53254. } else {
  53255. renderer.setMode( _gl.TRIANGLES );
  53256. }
  53257. } else if ( object.isLine ) {
  53258. let lineWidth = material.linewidth;
  53259. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  53260. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  53261. if ( object.isLineSegments ) {
  53262. renderer.setMode( _gl.LINES );
  53263. } else if ( object.isLineLoop ) {
  53264. renderer.setMode( _gl.LINE_LOOP );
  53265. } else {
  53266. renderer.setMode( _gl.LINE_STRIP );
  53267. }
  53268. } else if ( object.isPoints ) {
  53269. renderer.setMode( _gl.POINTS );
  53270. } else if ( object.isSprite ) {
  53271. renderer.setMode( _gl.TRIANGLES );
  53272. }
  53273. if ( object.isBatchedMesh ) {
  53274. if ( object._multiDrawInstances !== null ) {
  53275. // @deprecated, r174
  53276. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53277. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  53278. } else {
  53279. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  53280. const starts = object._multiDrawStarts;
  53281. const counts = object._multiDrawCounts;
  53282. const drawCount = object._multiDrawCount;
  53283. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  53284. const uniforms = properties.get( material ).currentProgram.getUniforms();
  53285. for ( let i = 0; i < drawCount; i ++ ) {
  53286. uniforms.setValue( _gl, '_gl_DrawID', i );
  53287. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  53288. }
  53289. } else {
  53290. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  53291. }
  53292. }
  53293. } else if ( object.isInstancedMesh ) {
  53294. renderer.renderInstances( drawStart, drawCount, object.count );
  53295. } else if ( geometry.isInstancedBufferGeometry ) {
  53296. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  53297. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  53298. renderer.renderInstances( drawStart, drawCount, instanceCount );
  53299. } else {
  53300. renderer.render( drawStart, drawCount );
  53301. }
  53302. };
  53303. // Compile
  53304. function prepareMaterial( material, scene, object ) {
  53305. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53306. material.side = BackSide;
  53307. material.needsUpdate = true;
  53308. getProgram( material, scene, object );
  53309. material.side = FrontSide;
  53310. material.needsUpdate = true;
  53311. getProgram( material, scene, object );
  53312. material.side = DoubleSide;
  53313. } else {
  53314. getProgram( material, scene, object );
  53315. }
  53316. }
  53317. /**
  53318. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53319. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53320. * optional parameter for applying the target scene.
  53321. *
  53322. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53323. *
  53324. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53325. * @param {Camera} camera - The camera.
  53326. * @param {?Scene} [targetScene=null] - The target scene.
  53327. * @return {Set<Material>} The precompiled materials.
  53328. */
  53329. this.compile = function ( scene, camera, targetScene = null ) {
  53330. if ( targetScene === null ) targetScene = scene;
  53331. currentRenderState = renderStates.get( targetScene );
  53332. currentRenderState.init( camera );
  53333. renderStateStack.push( currentRenderState );
  53334. // gather lights from both the target scene and the new object that will be added to the scene.
  53335. targetScene.traverseVisible( function ( object ) {
  53336. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53337. currentRenderState.pushLight( object );
  53338. if ( object.castShadow ) {
  53339. currentRenderState.pushShadow( object );
  53340. }
  53341. }
  53342. } );
  53343. if ( scene !== targetScene ) {
  53344. scene.traverseVisible( function ( object ) {
  53345. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53346. currentRenderState.pushLight( object );
  53347. if ( object.castShadow ) {
  53348. currentRenderState.pushShadow( object );
  53349. }
  53350. }
  53351. } );
  53352. }
  53353. currentRenderState.setupLights();
  53354. // Only initialize materials in the new scene, not the targetScene.
  53355. const materials = new Set();
  53356. scene.traverse( function ( object ) {
  53357. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53358. return;
  53359. }
  53360. const material = object.material;
  53361. if ( material ) {
  53362. if ( Array.isArray( material ) ) {
  53363. for ( let i = 0; i < material.length; i ++ ) {
  53364. const material2 = material[ i ];
  53365. prepareMaterial( material2, targetScene, object );
  53366. materials.add( material2 );
  53367. }
  53368. } else {
  53369. prepareMaterial( material, targetScene, object );
  53370. materials.add( material );
  53371. }
  53372. }
  53373. } );
  53374. currentRenderState = renderStateStack.pop();
  53375. return materials;
  53376. };
  53377. // compileAsync
  53378. /**
  53379. * Asynchronous version of {@link WebGLRenderer#compile}.
  53380. *
  53381. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53382. * it is recommended to use this version of `compile()` whenever possible.
  53383. *
  53384. * @async
  53385. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53386. * @param {Camera} camera - The camera.
  53387. * @param {?Scene} [targetScene=null] - The target scene.
  53388. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53389. */
  53390. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53391. const materials = this.compile( scene, camera, targetScene );
  53392. // Wait for all the materials in the new object to indicate that they're
  53393. // ready to be used before resolving the promise.
  53394. return new Promise( ( resolve ) => {
  53395. function checkMaterialsReady() {
  53396. materials.forEach( function ( material ) {
  53397. const materialProperties = properties.get( material );
  53398. const program = materialProperties.currentProgram;
  53399. if ( program.isReady() ) {
  53400. // remove any programs that report they're ready to use from the list
  53401. materials.delete( material );
  53402. }
  53403. } );
  53404. // once the list of compiling materials is empty, call the callback
  53405. if ( materials.size === 0 ) {
  53406. resolve( scene );
  53407. return;
  53408. }
  53409. // if some materials are still not ready, wait a bit and check again
  53410. setTimeout( checkMaterialsReady, 10 );
  53411. }
  53412. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53413. // If we can check the compilation status of the materials without
  53414. // blocking then do so right away.
  53415. checkMaterialsReady();
  53416. } else {
  53417. // Otherwise start by waiting a bit to give the materials we just
  53418. // initialized a chance to finish.
  53419. setTimeout( checkMaterialsReady, 10 );
  53420. }
  53421. } );
  53422. };
  53423. // Animation Loop
  53424. let onAnimationFrameCallback = null;
  53425. function onAnimationFrame( time ) {
  53426. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53427. }
  53428. function onXRSessionStart() {
  53429. animation.stop();
  53430. }
  53431. function onXRSessionEnd() {
  53432. animation.start();
  53433. }
  53434. const animation = new WebGLAnimation();
  53435. animation.setAnimationLoop( onAnimationFrame );
  53436. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53437. /**
  53438. * Applications are advised to always define the animation loop
  53439. * with this method and not manually with `requestAnimationFrame()`
  53440. * for best compatibility.
  53441. *
  53442. * @param {?onAnimationCallback} callback - The application's animation loop.
  53443. */
  53444. this.setAnimationLoop = function ( callback ) {
  53445. onAnimationFrameCallback = callback;
  53446. xr.setAnimationLoop( callback );
  53447. ( callback === null ) ? animation.stop() : animation.start();
  53448. };
  53449. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53450. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53451. // Rendering
  53452. /**
  53453. * Renders the given scene (or other type of 3D object) using the given camera.
  53454. *
  53455. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53456. * or to the canvas as usual.
  53457. *
  53458. * By default render buffers are cleared before rendering but you can prevent
  53459. * this by setting the property `autoClear` to `false`. If you want to prevent
  53460. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53461. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53462. *
  53463. * @param {Object3D} scene - The scene to render.
  53464. * @param {Camera} camera - The camera.
  53465. */
  53466. this.render = function ( scene, camera ) {
  53467. if ( camera !== undefined && camera.isCamera !== true ) {
  53468. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53469. return;
  53470. }
  53471. if ( _isContextLost === true ) return;
  53472. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  53473. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  53474. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  53475. // update scene graph
  53476. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53477. // update camera matrices and frustum
  53478. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53479. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  53480. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53481. camera = xr.getCamera(); // use XR camera for rendering
  53482. }
  53483. //
  53484. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53485. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53486. currentRenderState.init( camera );
  53487. renderStateStack.push( currentRenderState );
  53488. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53489. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53490. _localClippingEnabled = this.localClippingEnabled;
  53491. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53492. currentRenderList = renderLists.get( scene, renderListStack.length );
  53493. currentRenderList.init();
  53494. renderListStack.push( currentRenderList );
  53495. if ( xr.enabled === true && xr.isPresenting === true ) {
  53496. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53497. if ( depthSensingMesh !== null ) {
  53498. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53499. }
  53500. }
  53501. projectObject( scene, camera, 0, _this.sortObjects );
  53502. currentRenderList.finish();
  53503. if ( _this.sortObjects === true ) {
  53504. currentRenderList.sort( _opaqueSort, _transparentSort );
  53505. }
  53506. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53507. if ( _renderBackground ) {
  53508. background.addToRenderList( currentRenderList, scene );
  53509. }
  53510. //
  53511. this.info.render.frame ++;
  53512. if ( _clippingEnabled === true ) clipping.beginShadows();
  53513. const shadowsArray = currentRenderState.state.shadowsArray;
  53514. shadowMap.render( shadowsArray, scene, camera );
  53515. if ( _clippingEnabled === true ) clipping.endShadows();
  53516. //
  53517. if ( this.info.autoReset === true ) this.info.reset();
  53518. // render scene (skip if first effect is a render pass - it will render the scene itself)
  53519. const skipSceneRender = useOutput && output.hasRenderPass();
  53520. if ( skipSceneRender === false ) {
  53521. const opaqueObjects = currentRenderList.opaque;
  53522. const transmissiveObjects = currentRenderList.transmissive;
  53523. currentRenderState.setupLights();
  53524. if ( camera.isArrayCamera ) {
  53525. const cameras = camera.cameras;
  53526. if ( transmissiveObjects.length > 0 ) {
  53527. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53528. const camera2 = cameras[ i ];
  53529. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53530. }
  53531. }
  53532. if ( _renderBackground ) background.render( scene );
  53533. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53534. const camera2 = cameras[ i ];
  53535. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53536. }
  53537. } else {
  53538. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53539. if ( _renderBackground ) background.render( scene );
  53540. renderScene( currentRenderList, scene, camera );
  53541. }
  53542. }
  53543. //
  53544. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53545. // resolve multisample renderbuffers to a single-sample texture if necessary
  53546. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53547. // Generate mipmap if we're using any kind of mipmap filtering
  53548. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53549. }
  53550. // copy from internal render target to canvas using fullscreen quad
  53551. if ( useOutput ) {
  53552. output.end( _this );
  53553. }
  53554. //
  53555. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53556. // _gl.finish();
  53557. bindingStates.resetDefaultState();
  53558. _currentMaterialId = -1;
  53559. _currentCamera = null;
  53560. renderStateStack.pop();
  53561. if ( renderStateStack.length > 0 ) {
  53562. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53563. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53564. } else {
  53565. currentRenderState = null;
  53566. }
  53567. renderListStack.pop();
  53568. if ( renderListStack.length > 0 ) {
  53569. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53570. } else {
  53571. currentRenderList = null;
  53572. }
  53573. };
  53574. function projectObject( object, camera, groupOrder, sortObjects ) {
  53575. if ( object.visible === false ) return;
  53576. const visible = object.layers.test( camera.layers );
  53577. if ( visible ) {
  53578. if ( object.isGroup ) {
  53579. groupOrder = object.renderOrder;
  53580. } else if ( object.isLOD ) {
  53581. if ( object.autoUpdate === true ) object.update( camera );
  53582. } else if ( object.isLight ) {
  53583. currentRenderState.pushLight( object );
  53584. if ( object.castShadow ) {
  53585. currentRenderState.pushShadow( object );
  53586. }
  53587. } else if ( object.isSprite ) {
  53588. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53589. if ( sortObjects ) {
  53590. _vector4.setFromMatrixPosition( object.matrixWorld )
  53591. .applyMatrix4( _projScreenMatrix );
  53592. }
  53593. const geometry = objects.update( object );
  53594. const material = object.material;
  53595. if ( material.visible ) {
  53596. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53597. }
  53598. }
  53599. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53600. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53601. const geometry = objects.update( object );
  53602. const material = object.material;
  53603. if ( sortObjects ) {
  53604. if ( object.boundingSphere !== undefined ) {
  53605. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53606. _vector4.copy( object.boundingSphere.center );
  53607. } else {
  53608. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53609. _vector4.copy( geometry.boundingSphere.center );
  53610. }
  53611. _vector4
  53612. .applyMatrix4( object.matrixWorld )
  53613. .applyMatrix4( _projScreenMatrix );
  53614. }
  53615. if ( Array.isArray( material ) ) {
  53616. const groups = geometry.groups;
  53617. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53618. const group = groups[ i ];
  53619. const groupMaterial = material[ group.materialIndex ];
  53620. if ( groupMaterial && groupMaterial.visible ) {
  53621. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  53622. }
  53623. }
  53624. } else if ( material.visible ) {
  53625. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53626. }
  53627. }
  53628. }
  53629. }
  53630. const children = object.children;
  53631. for ( let i = 0, l = children.length; i < l; i ++ ) {
  53632. projectObject( children[ i ], camera, groupOrder, sortObjects );
  53633. }
  53634. }
  53635. function renderScene( currentRenderList, scene, camera, viewport ) {
  53636. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  53637. currentRenderState.setupLightsView( camera );
  53638. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53639. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  53640. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  53641. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  53642. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  53643. // Ensure depth buffer writing is enabled so it can be cleared on next render
  53644. state.buffers.depth.setTest( true );
  53645. state.buffers.depth.setMask( true );
  53646. state.buffers.color.setMask( true );
  53647. state.setPolygonOffset( false );
  53648. }
  53649. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  53650. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53651. if ( overrideMaterial !== null ) {
  53652. return;
  53653. }
  53654. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  53655. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  53656. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  53657. generateMipmaps: true,
  53658. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  53659. minFilter: LinearMipmapLinearFilter,
  53660. samples: capabilities.samples,
  53661. stencilBuffer: stencil,
  53662. resolveDepthBuffer: false,
  53663. resolveStencilBuffer: false,
  53664. colorSpace: ColorManagement.workingColorSpace,
  53665. } );
  53666. // debug
  53667. /*
  53668. const geometry = new PlaneGeometry();
  53669. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  53670. const mesh = new Mesh( geometry, material );
  53671. scene.add( mesh );
  53672. */
  53673. }
  53674. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  53675. const activeViewport = camera.viewport || _currentViewport;
  53676. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  53677. //
  53678. const currentRenderTarget = _this.getRenderTarget();
  53679. const currentActiveCubeFace = _this.getActiveCubeFace();
  53680. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  53681. _this.setRenderTarget( transmissionRenderTarget );
  53682. _this.getClearColor( _currentClearColor );
  53683. _currentClearAlpha = _this.getClearAlpha();
  53684. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  53685. _this.clear();
  53686. if ( _renderBackground ) background.render( scene );
  53687. // Turn off the features which can affect the frag color for opaque objects pass.
  53688. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  53689. const currentToneMapping = _this.toneMapping;
  53690. _this.toneMapping = NoToneMapping;
  53691. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  53692. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  53693. const currentCameraViewport = camera.viewport;
  53694. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  53695. currentRenderState.setupLightsView( camera );
  53696. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53697. renderObjects( opaqueObjects, scene, camera );
  53698. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53699. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53700. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  53701. let renderTargetNeedsUpdate = false;
  53702. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  53703. const renderItem = transmissiveObjects[ i ];
  53704. const { object, geometry, material, group } = renderItem;
  53705. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  53706. const currentSide = material.side;
  53707. material.side = BackSide;
  53708. material.needsUpdate = true;
  53709. renderObject( object, scene, camera, geometry, material, group );
  53710. material.side = currentSide;
  53711. material.needsUpdate = true;
  53712. renderTargetNeedsUpdate = true;
  53713. }
  53714. }
  53715. if ( renderTargetNeedsUpdate === true ) {
  53716. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53717. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53718. }
  53719. }
  53720. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  53721. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  53722. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  53723. _this.toneMapping = currentToneMapping;
  53724. }
  53725. function renderObjects( renderList, scene, camera ) {
  53726. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53727. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  53728. const renderItem = renderList[ i ];
  53729. const { object, geometry, group } = renderItem;
  53730. let material = renderItem.material;
  53731. if ( material.allowOverride === true && overrideMaterial !== null ) {
  53732. material = overrideMaterial;
  53733. }
  53734. if ( object.layers.test( camera.layers ) ) {
  53735. renderObject( object, scene, camera, geometry, material, group );
  53736. }
  53737. }
  53738. }
  53739. function renderObject( object, scene, camera, geometry, material, group ) {
  53740. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  53741. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  53742. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  53743. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  53744. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53745. material.side = BackSide;
  53746. material.needsUpdate = true;
  53747. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53748. material.side = FrontSide;
  53749. material.needsUpdate = true;
  53750. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53751. material.side = DoubleSide;
  53752. } else {
  53753. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53754. }
  53755. object.onAfterRender( _this, scene, camera, geometry, material, group );
  53756. }
  53757. function getProgram( material, scene, object ) {
  53758. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53759. const materialProperties = properties.get( material );
  53760. const lights = currentRenderState.state.lights;
  53761. const shadowsArray = currentRenderState.state.shadowsArray;
  53762. const lightsStateVersion = lights.state.version;
  53763. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  53764. const programCacheKey = programCache.getProgramCacheKey( parameters );
  53765. let programs = materialProperties.programs;
  53766. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  53767. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  53768. materialProperties.fog = scene.fog;
  53769. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  53770. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  53771. if ( programs === undefined ) {
  53772. // new material
  53773. material.addEventListener( 'dispose', onMaterialDispose );
  53774. programs = new Map();
  53775. materialProperties.programs = programs;
  53776. }
  53777. let program = programs.get( programCacheKey );
  53778. if ( program !== undefined ) {
  53779. // early out if program and light state is identical
  53780. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  53781. updateCommonMaterialProperties( material, parameters );
  53782. return program;
  53783. }
  53784. } else {
  53785. parameters.uniforms = programCache.getUniforms( material );
  53786. material.onBeforeCompile( parameters, _this );
  53787. program = programCache.acquireProgram( parameters, programCacheKey );
  53788. programs.set( programCacheKey, program );
  53789. materialProperties.uniforms = parameters.uniforms;
  53790. }
  53791. const uniforms = materialProperties.uniforms;
  53792. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  53793. uniforms.clippingPlanes = clipping.uniform;
  53794. }
  53795. updateCommonMaterialProperties( material, parameters );
  53796. // store the light setup it was created for
  53797. materialProperties.needsLights = materialNeedsLights( material );
  53798. materialProperties.lightsStateVersion = lightsStateVersion;
  53799. if ( materialProperties.needsLights ) {
  53800. // wire up the material to this renderer's lighting state
  53801. uniforms.ambientLightColor.value = lights.state.ambient;
  53802. uniforms.lightProbe.value = lights.state.probe;
  53803. uniforms.directionalLights.value = lights.state.directional;
  53804. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  53805. uniforms.spotLights.value = lights.state.spot;
  53806. uniforms.spotLightShadows.value = lights.state.spotShadow;
  53807. uniforms.rectAreaLights.value = lights.state.rectArea;
  53808. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  53809. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  53810. uniforms.pointLights.value = lights.state.point;
  53811. uniforms.pointLightShadows.value = lights.state.pointShadow;
  53812. uniforms.hemisphereLights.value = lights.state.hemi;
  53813. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  53814. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  53815. uniforms.spotLightMap.value = lights.state.spotLightMap;
  53816. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  53817. // TODO (abelnation): add area lights shadow info to uniforms
  53818. }
  53819. materialProperties.currentProgram = program;
  53820. materialProperties.uniformsList = null;
  53821. return program;
  53822. }
  53823. function getUniformList( materialProperties ) {
  53824. if ( materialProperties.uniformsList === null ) {
  53825. const progUniforms = materialProperties.currentProgram.getUniforms();
  53826. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  53827. }
  53828. return materialProperties.uniformsList;
  53829. }
  53830. function updateCommonMaterialProperties( material, parameters ) {
  53831. const materialProperties = properties.get( material );
  53832. materialProperties.outputColorSpace = parameters.outputColorSpace;
  53833. materialProperties.batching = parameters.batching;
  53834. materialProperties.batchingColor = parameters.batchingColor;
  53835. materialProperties.instancing = parameters.instancing;
  53836. materialProperties.instancingColor = parameters.instancingColor;
  53837. materialProperties.instancingMorph = parameters.instancingMorph;
  53838. materialProperties.skinning = parameters.skinning;
  53839. materialProperties.morphTargets = parameters.morphTargets;
  53840. materialProperties.morphNormals = parameters.morphNormals;
  53841. materialProperties.morphColors = parameters.morphColors;
  53842. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  53843. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  53844. materialProperties.numIntersection = parameters.numClipIntersection;
  53845. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53846. materialProperties.vertexTangents = parameters.vertexTangents;
  53847. materialProperties.toneMapping = parameters.toneMapping;
  53848. }
  53849. function setProgram( camera, scene, geometry, material, object ) {
  53850. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53851. textures.resetTextureUnits();
  53852. const fog = scene.fog;
  53853. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53854. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53855. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53856. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53857. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53858. const morphTargets = !! geometry.morphAttributes.position;
  53859. const morphNormals = !! geometry.morphAttributes.normal;
  53860. const morphColors = !! geometry.morphAttributes.color;
  53861. let toneMapping = NoToneMapping;
  53862. if ( material.toneMapped ) {
  53863. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  53864. toneMapping = _this.toneMapping;
  53865. }
  53866. }
  53867. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  53868. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  53869. const materialProperties = properties.get( material );
  53870. const lights = currentRenderState.state.lights;
  53871. if ( _clippingEnabled === true ) {
  53872. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  53873. const useCache =
  53874. camera === _currentCamera &&
  53875. material.id === _currentMaterialId;
  53876. // we might want to call this function with some ClippingGroup
  53877. // object instead of the material, once it becomes feasible
  53878. // (#8465, #8379)
  53879. clipping.setState( material, camera, useCache );
  53880. }
  53881. }
  53882. //
  53883. let needsProgramChange = false;
  53884. if ( material.version === materialProperties.__version ) {
  53885. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53886. needsProgramChange = true;
  53887. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53888. needsProgramChange = true;
  53889. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53890. needsProgramChange = true;
  53891. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53892. needsProgramChange = true;
  53893. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53894. needsProgramChange = true;
  53895. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53896. needsProgramChange = true;
  53897. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53898. needsProgramChange = true;
  53899. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53900. needsProgramChange = true;
  53901. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53902. needsProgramChange = true;
  53903. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53904. needsProgramChange = true;
  53905. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53906. needsProgramChange = true;
  53907. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53908. needsProgramChange = true;
  53909. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53910. needsProgramChange = true;
  53911. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53912. needsProgramChange = true;
  53913. } else if ( materialProperties.envMap !== envMap ) {
  53914. needsProgramChange = true;
  53915. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53916. needsProgramChange = true;
  53917. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53918. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53919. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53920. needsProgramChange = true;
  53921. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53922. needsProgramChange = true;
  53923. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53924. needsProgramChange = true;
  53925. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53926. needsProgramChange = true;
  53927. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53928. needsProgramChange = true;
  53929. } else if ( materialProperties.morphColors !== morphColors ) {
  53930. needsProgramChange = true;
  53931. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53932. needsProgramChange = true;
  53933. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53934. needsProgramChange = true;
  53935. }
  53936. } else {
  53937. needsProgramChange = true;
  53938. materialProperties.__version = material.version;
  53939. }
  53940. //
  53941. let program = materialProperties.currentProgram;
  53942. if ( needsProgramChange === true ) {
  53943. program = getProgram( material, scene, object );
  53944. }
  53945. let refreshProgram = false;
  53946. let refreshMaterial = false;
  53947. let refreshLights = false;
  53948. const p_uniforms = program.getUniforms(),
  53949. m_uniforms = materialProperties.uniforms;
  53950. if ( state.useProgram( program.program ) ) {
  53951. refreshProgram = true;
  53952. refreshMaterial = true;
  53953. refreshLights = true;
  53954. }
  53955. if ( material.id !== _currentMaterialId ) {
  53956. _currentMaterialId = material.id;
  53957. refreshMaterial = true;
  53958. }
  53959. if ( refreshProgram || _currentCamera !== camera ) {
  53960. // common camera uniforms
  53961. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53962. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53963. camera._reversedDepth = true;
  53964. camera.updateProjectionMatrix();
  53965. }
  53966. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53967. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53968. const uCamPos = p_uniforms.map.cameraPosition;
  53969. if ( uCamPos !== undefined ) {
  53970. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53971. }
  53972. if ( capabilities.logarithmicDepthBuffer ) {
  53973. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53974. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53975. }
  53976. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53977. if ( material.isMeshPhongMaterial ||
  53978. material.isMeshToonMaterial ||
  53979. material.isMeshLambertMaterial ||
  53980. material.isMeshBasicMaterial ||
  53981. material.isMeshStandardMaterial ||
  53982. material.isShaderMaterial ) {
  53983. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53984. }
  53985. if ( _currentCamera !== camera ) {
  53986. _currentCamera = camera;
  53987. // lighting uniforms depend on the camera so enforce an update
  53988. // now, in case this material supports lights - or later, when
  53989. // the next material that does gets activated:
  53990. refreshMaterial = true; // set to true on material change
  53991. refreshLights = true; // remains set until update done
  53992. }
  53993. }
  53994. // Pre-allocate texture units for shadow samplers before setting data textures
  53995. if ( materialProperties.needsLights ) {
  53996. // Set shadow map uniforms first to ensure they get the first texture units
  53997. if ( lights.state.directionalShadowMap.length > 0 ) {
  53998. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  53999. }
  54000. if ( lights.state.spotShadowMap.length > 0 ) {
  54001. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  54002. }
  54003. if ( lights.state.pointShadowMap.length > 0 ) {
  54004. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  54005. }
  54006. }
  54007. // skinning and morph target uniforms must be set even if material didn't change
  54008. // auto-setting of texture unit for bone and morph texture must go before other textures
  54009. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  54010. if ( object.isSkinnedMesh ) {
  54011. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  54012. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  54013. const skeleton = object.skeleton;
  54014. if ( skeleton ) {
  54015. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  54016. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  54017. }
  54018. }
  54019. if ( object.isBatchedMesh ) {
  54020. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  54021. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  54022. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  54023. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  54024. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  54025. if ( object._colorsTexture !== null ) {
  54026. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  54027. }
  54028. }
  54029. const morphAttributes = geometry.morphAttributes;
  54030. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  54031. morphtargets.update( object, geometry, program );
  54032. }
  54033. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  54034. materialProperties.receiveShadow = object.receiveShadow;
  54035. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  54036. }
  54037. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  54038. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  54039. }
  54040. // Set DFG LUT for physically-based materials
  54041. if ( m_uniforms.dfgLUT !== undefined ) {
  54042. m_uniforms.dfgLUT.value = getDFGLUT();
  54043. }
  54044. if ( refreshMaterial ) {
  54045. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  54046. if ( materialProperties.needsLights ) {
  54047. // the current material requires lighting info
  54048. // note: all lighting uniforms are always set correctly
  54049. // they simply reference the renderer's state for their
  54050. // values
  54051. //
  54052. // use the current material's .needsUpdate flags to set
  54053. // the GL state when required
  54054. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  54055. }
  54056. // refresh uniforms common to several materials
  54057. if ( fog && material.fog === true ) {
  54058. materials.refreshFogUniforms( m_uniforms, fog );
  54059. }
  54060. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  54061. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54062. }
  54063. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  54064. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54065. material.uniformsNeedUpdate = false;
  54066. }
  54067. if ( material.isSpriteMaterial ) {
  54068. p_uniforms.setValue( _gl, 'center', object.center );
  54069. }
  54070. // common matrices
  54071. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  54072. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  54073. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  54074. // UBOs
  54075. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  54076. const groups = material.uniformsGroups;
  54077. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  54078. const group = groups[ i ];
  54079. uniformsGroups.update( group, program );
  54080. uniformsGroups.bind( group, program );
  54081. }
  54082. }
  54083. return program;
  54084. }
  54085. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  54086. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  54087. uniforms.ambientLightColor.needsUpdate = value;
  54088. uniforms.lightProbe.needsUpdate = value;
  54089. uniforms.directionalLights.needsUpdate = value;
  54090. uniforms.directionalLightShadows.needsUpdate = value;
  54091. uniforms.pointLights.needsUpdate = value;
  54092. uniforms.pointLightShadows.needsUpdate = value;
  54093. uniforms.spotLights.needsUpdate = value;
  54094. uniforms.spotLightShadows.needsUpdate = value;
  54095. uniforms.rectAreaLights.needsUpdate = value;
  54096. uniforms.hemisphereLights.needsUpdate = value;
  54097. }
  54098. function materialNeedsLights( material ) {
  54099. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  54100. material.isMeshStandardMaterial || material.isShadowMaterial ||
  54101. ( material.isShaderMaterial && material.lights === true );
  54102. }
  54103. /**
  54104. * Returns the active cube face.
  54105. *
  54106. * @return {number} The active cube face.
  54107. */
  54108. this.getActiveCubeFace = function () {
  54109. return _currentActiveCubeFace;
  54110. };
  54111. /**
  54112. * Returns the active mipmap level.
  54113. *
  54114. * @return {number} The active mipmap level.
  54115. */
  54116. this.getActiveMipmapLevel = function () {
  54117. return _currentActiveMipmapLevel;
  54118. };
  54119. /**
  54120. * Returns the active render target.
  54121. *
  54122. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  54123. * is currently set.
  54124. */
  54125. this.getRenderTarget = function () {
  54126. return _currentRenderTarget;
  54127. };
  54128. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  54129. const renderTargetProperties = properties.get( renderTarget );
  54130. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  54131. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  54132. // The multisample_render_to_texture extension doesn't work properly if there
  54133. // are midframe flushes and an external depth buffer. Disable use of the extension.
  54134. renderTargetProperties.__useRenderToTexture = false;
  54135. }
  54136. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  54137. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  54138. renderTargetProperties.__hasExternalTextures = true;
  54139. };
  54140. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  54141. const renderTargetProperties = properties.get( renderTarget );
  54142. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  54143. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  54144. };
  54145. const _scratchFrameBuffer = _gl.createFramebuffer();
  54146. /**
  54147. * Sets the active rendertarget.
  54148. *
  54149. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  54150. * the canvas is set as the active render target instead.
  54151. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  54152. * Indicates the z layer to render in to when using 3D or array render targets.
  54153. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  54154. */
  54155. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  54156. _currentRenderTarget = renderTarget;
  54157. _currentActiveCubeFace = activeCubeFace;
  54158. _currentActiveMipmapLevel = activeMipmapLevel;
  54159. let framebuffer = null;
  54160. let isCube = false;
  54161. let isRenderTarget3D = false;
  54162. if ( renderTarget ) {
  54163. const renderTargetProperties = properties.get( renderTarget );
  54164. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  54165. // Externally-managed framebuffer (e.g. XR)
  54166. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  54167. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  54168. _currentViewport.copy( renderTarget.viewport );
  54169. _currentScissor.copy( renderTarget.scissor );
  54170. _currentScissorTest = renderTarget.scissorTest;
  54171. state.viewport( _currentViewport );
  54172. state.scissor( _currentScissor );
  54173. state.setScissorTest( _currentScissorTest );
  54174. _currentMaterialId = -1;
  54175. return;
  54176. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  54177. textures.setupRenderTarget( renderTarget );
  54178. } else if ( renderTargetProperties.__hasExternalTextures ) {
  54179. // Color and depth texture must be rebound in order for the swapchain to update.
  54180. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  54181. } else if ( renderTarget.depthBuffer ) {
  54182. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  54183. const depthTexture = renderTarget.depthTexture;
  54184. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  54185. // check if the depth texture is compatible
  54186. if (
  54187. depthTexture !== null &&
  54188. properties.has( depthTexture ) &&
  54189. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  54190. ) {
  54191. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  54192. }
  54193. // Swap the depth buffer to the currently attached one
  54194. textures.setupDepthRenderbuffer( renderTarget );
  54195. }
  54196. }
  54197. const texture = renderTarget.texture;
  54198. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54199. isRenderTarget3D = true;
  54200. }
  54201. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54202. if ( renderTarget.isWebGLCubeRenderTarget ) {
  54203. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  54204. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  54205. } else {
  54206. framebuffer = __webglFramebuffer[ activeCubeFace ];
  54207. }
  54208. isCube = true;
  54209. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  54210. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  54211. } else {
  54212. if ( Array.isArray( __webglFramebuffer ) ) {
  54213. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  54214. } else {
  54215. framebuffer = __webglFramebuffer;
  54216. }
  54217. }
  54218. _currentViewport.copy( renderTarget.viewport );
  54219. _currentScissor.copy( renderTarget.scissor );
  54220. _currentScissorTest = renderTarget.scissorTest;
  54221. } else {
  54222. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  54223. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  54224. _currentScissorTest = _scissorTest;
  54225. }
  54226. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  54227. // being bound that are different sizes.
  54228. if ( activeMipmapLevel !== 0 ) {
  54229. framebuffer = _scratchFrameBuffer;
  54230. }
  54231. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54232. if ( framebufferBound ) {
  54233. state.drawBuffers( renderTarget, framebuffer );
  54234. }
  54235. state.viewport( _currentViewport );
  54236. state.scissor( _currentScissor );
  54237. state.setScissorTest( _currentScissorTest );
  54238. if ( isCube ) {
  54239. const textureProperties = properties.get( renderTarget.texture );
  54240. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  54241. } else if ( isRenderTarget3D ) {
  54242. const layer = activeCubeFace;
  54243. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  54244. const textureProperties = properties.get( renderTarget.textures[ i ] );
  54245. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  54246. }
  54247. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  54248. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  54249. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  54250. const textureProperties = properties.get( renderTarget.texture );
  54251. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  54252. }
  54253. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  54254. };
  54255. /**
  54256. * Reads the pixel data from the given render target into the given buffer.
  54257. *
  54258. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54259. * @param {number} x - The `x` coordinate of the copy region's origin.
  54260. * @param {number} y - The `y` coordinate of the copy region's origin.
  54261. * @param {number} width - The width of the copy region.
  54262. * @param {number} height - The height of the copy region.
  54263. * @param {TypedArray} buffer - The result buffer.
  54264. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54265. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54266. */
  54267. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54268. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54269. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54270. return;
  54271. }
  54272. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54273. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54274. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54275. }
  54276. if ( framebuffer ) {
  54277. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54278. try {
  54279. const texture = renderTarget.textures[ textureIndex ];
  54280. const textureFormat = texture.format;
  54281. const textureType = texture.type;
  54282. // when using MRT, select the correct color buffer for the subsequent read command
  54283. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54284. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54285. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  54286. return;
  54287. }
  54288. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54289. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54290. return;
  54291. }
  54292. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54293. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54294. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  54295. }
  54296. } finally {
  54297. // restore framebuffer of current render target if necessary
  54298. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54299. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54300. }
  54301. }
  54302. };
  54303. /**
  54304. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  54305. *
  54306. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  54307. *
  54308. * @async
  54309. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54310. * @param {number} x - The `x` coordinate of the copy region's origin.
  54311. * @param {number} y - The `y` coordinate of the copy region's origin.
  54312. * @param {number} width - The width of the copy region.
  54313. * @param {number} height - The height of the copy region.
  54314. * @param {TypedArray} buffer - The result buffer.
  54315. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54316. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54317. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54318. */
  54319. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54320. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54321. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54322. }
  54323. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54324. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54325. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54326. }
  54327. if ( framebuffer ) {
  54328. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54329. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54330. // set the active frame buffer to the one we want to read
  54331. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54332. const texture = renderTarget.textures[ textureIndex ];
  54333. const textureFormat = texture.format;
  54334. const textureType = texture.type;
  54335. // when using MRT, select the correct color buffer for the subsequent read command
  54336. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54337. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54338. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54339. }
  54340. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54341. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54342. }
  54343. const glBuffer = _gl.createBuffer();
  54344. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54345. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54346. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54347. // reset the frame buffer to the currently set buffer before waiting
  54348. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54349. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54350. // check if the commands have finished every 8 ms
  54351. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54352. _gl.flush();
  54353. await probeAsync( _gl, sync, 4 );
  54354. // read the data and delete the buffer
  54355. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54356. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54357. _gl.deleteBuffer( glBuffer );
  54358. _gl.deleteSync( sync );
  54359. return buffer;
  54360. } else {
  54361. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54362. }
  54363. }
  54364. };
  54365. /**
  54366. * Copies pixels from the current bound framebuffer into the given texture.
  54367. *
  54368. * @param {FramebufferTexture} texture - The texture.
  54369. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54370. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54371. */
  54372. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54373. const levelScale = Math.pow( 2, - level );
  54374. const width = Math.floor( texture.image.width * levelScale );
  54375. const height = Math.floor( texture.image.height * levelScale );
  54376. const x = position !== null ? position.x : 0;
  54377. const y = position !== null ? position.y : 0;
  54378. textures.setTexture2D( texture, 0 );
  54379. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54380. state.unbindTexture();
  54381. };
  54382. const _srcFramebuffer = _gl.createFramebuffer();
  54383. const _dstFramebuffer = _gl.createFramebuffer();
  54384. /**
  54385. * Copies data of the given source texture into a destination texture.
  54386. *
  54387. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54388. * {@link WebGLRenderer#initRenderTarget}.
  54389. *
  54390. * @param {Texture} srcTexture - The source texture.
  54391. * @param {Texture} dstTexture - The destination texture.
  54392. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54393. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54394. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54395. * @param {?number} [dstLevel=0] - The destination mipmap level.
  54396. */
  54397. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54398. // gather the necessary dimensions to copy
  54399. let width, height, depth, minX, minY, minZ;
  54400. let dstX, dstY, dstZ;
  54401. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54402. if ( srcRegion !== null ) {
  54403. width = srcRegion.max.x - srcRegion.min.x;
  54404. height = srcRegion.max.y - srcRegion.min.y;
  54405. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54406. minX = srcRegion.min.x;
  54407. minY = srcRegion.min.y;
  54408. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54409. } else {
  54410. const levelScale = Math.pow( 2, - srcLevel );
  54411. width = Math.floor( image.width * levelScale );
  54412. height = Math.floor( image.height * levelScale );
  54413. if ( srcTexture.isDataArrayTexture ) {
  54414. depth = image.depth;
  54415. } else if ( srcTexture.isData3DTexture ) {
  54416. depth = Math.floor( image.depth * levelScale );
  54417. } else {
  54418. depth = 1;
  54419. }
  54420. minX = 0;
  54421. minY = 0;
  54422. minZ = 0;
  54423. }
  54424. if ( dstPosition !== null ) {
  54425. dstX = dstPosition.x;
  54426. dstY = dstPosition.y;
  54427. dstZ = dstPosition.z;
  54428. } else {
  54429. dstX = 0;
  54430. dstY = 0;
  54431. dstZ = 0;
  54432. }
  54433. // Set up the destination target
  54434. const glFormat = utils.convert( dstTexture.format );
  54435. const glType = utils.convert( dstTexture.type );
  54436. let glTarget;
  54437. if ( dstTexture.isData3DTexture ) {
  54438. textures.setTexture3D( dstTexture, 0 );
  54439. glTarget = _gl.TEXTURE_3D;
  54440. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54441. textures.setTexture2DArray( dstTexture, 0 );
  54442. glTarget = _gl.TEXTURE_2D_ARRAY;
  54443. } else {
  54444. textures.setTexture2D( dstTexture, 0 );
  54445. glTarget = _gl.TEXTURE_2D;
  54446. }
  54447. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54448. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54449. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54450. // used for copying data from cpu
  54451. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54452. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54453. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54454. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54455. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54456. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54457. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54458. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54459. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54460. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54461. // set up the src texture
  54462. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54463. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54464. if ( srcTexture.isDepthTexture ) {
  54465. const srcTextureProperties = properties.get( srcTexture );
  54466. const dstTextureProperties = properties.get( dstTexture );
  54467. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54468. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54469. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54470. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54471. for ( let i = 0; i < depth; i ++ ) {
  54472. // if the source or destination are a 3d target then a layer needs to be bound
  54473. if ( isSrc3D ) {
  54474. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54475. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54476. }
  54477. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54478. }
  54479. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54480. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54481. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54482. // get the appropriate frame buffers
  54483. const srcTextureProperties = properties.get( srcTexture );
  54484. const dstTextureProperties = properties.get( dstTexture );
  54485. // bind the frame buffer targets
  54486. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54487. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54488. for ( let i = 0; i < depth; i ++ ) {
  54489. // assign the correct layers and mip maps to the frame buffers
  54490. if ( isSrc3D ) {
  54491. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54492. } else {
  54493. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54494. }
  54495. if ( isDst3D ) {
  54496. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54497. } else {
  54498. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54499. }
  54500. // copy the data using the fastest function that can achieve the copy
  54501. if ( srcLevel !== 0 ) {
  54502. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54503. } else if ( isDst3D ) {
  54504. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54505. } else {
  54506. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54507. }
  54508. }
  54509. // unbind read, draw buffers
  54510. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54511. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54512. } else {
  54513. if ( isDst3D ) {
  54514. // copy data into the 3d texture
  54515. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54516. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54517. } else if ( dstTexture.isCompressedArrayTexture ) {
  54518. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54519. } else {
  54520. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54521. }
  54522. } else {
  54523. // copy data into the 2d texture
  54524. if ( srcTexture.isDataTexture ) {
  54525. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54526. } else if ( srcTexture.isCompressedTexture ) {
  54527. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54528. } else {
  54529. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54530. }
  54531. }
  54532. }
  54533. // reset values
  54534. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54535. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54536. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54537. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54538. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54539. // Generate mipmaps only when copying level 0
  54540. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54541. _gl.generateMipmap( glTarget );
  54542. }
  54543. state.unbindTexture();
  54544. };
  54545. /**
  54546. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54547. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54548. * rendered to.
  54549. *
  54550. * @param {WebGLRenderTarget} target - The render target.
  54551. */
  54552. this.initRenderTarget = function ( target ) {
  54553. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54554. textures.setupRenderTarget( target );
  54555. }
  54556. };
  54557. /**
  54558. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54559. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54560. *
  54561. * @param {Texture} texture - The texture.
  54562. */
  54563. this.initTexture = function ( texture ) {
  54564. if ( texture.isCubeTexture ) {
  54565. textures.setTextureCube( texture, 0 );
  54566. } else if ( texture.isData3DTexture ) {
  54567. textures.setTexture3D( texture, 0 );
  54568. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54569. textures.setTexture2DArray( texture, 0 );
  54570. } else {
  54571. textures.setTexture2D( texture, 0 );
  54572. }
  54573. state.unbindTexture();
  54574. };
  54575. /**
  54576. * Can be used to reset the internal WebGL state. This method is mostly
  54577. * relevant for applications which share a single WebGL context across
  54578. * multiple WebGL libraries.
  54579. */
  54580. this.resetState = function () {
  54581. _currentActiveCubeFace = 0;
  54582. _currentActiveMipmapLevel = 0;
  54583. _currentRenderTarget = null;
  54584. state.reset();
  54585. bindingStates.reset();
  54586. };
  54587. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54588. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54589. }
  54590. }
  54591. /**
  54592. * Defines the coordinate system of the renderer.
  54593. *
  54594. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54595. *
  54596. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54597. * @default WebGLCoordinateSystem
  54598. * @readonly
  54599. */
  54600. get coordinateSystem() {
  54601. return WebGLCoordinateSystem;
  54602. }
  54603. /**
  54604. * Defines the output color space of the renderer.
  54605. *
  54606. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54607. * @default SRGBColorSpace
  54608. */
  54609. get outputColorSpace() {
  54610. return this._outputColorSpace;
  54611. }
  54612. set outputColorSpace( colorSpace ) {
  54613. this._outputColorSpace = colorSpace;
  54614. const gl = this.getContext();
  54615. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54616. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54617. }
  54618. }
  54619. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  54620. exports.AddEquation = AddEquation;
  54621. exports.AddOperation = AddOperation;
  54622. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  54623. exports.AdditiveBlending = AdditiveBlending;
  54624. exports.AgXToneMapping = AgXToneMapping;
  54625. exports.AlphaFormat = AlphaFormat;
  54626. exports.AlwaysCompare = AlwaysCompare;
  54627. exports.AlwaysDepth = AlwaysDepth;
  54628. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  54629. exports.AmbientLight = AmbientLight;
  54630. exports.AnimationAction = AnimationAction;
  54631. exports.AnimationClip = AnimationClip;
  54632. exports.AnimationLoader = AnimationLoader;
  54633. exports.AnimationMixer = AnimationMixer;
  54634. exports.AnimationObjectGroup = AnimationObjectGroup;
  54635. exports.AnimationUtils = AnimationUtils;
  54636. exports.ArcCurve = ArcCurve;
  54637. exports.ArrayCamera = ArrayCamera;
  54638. exports.ArrowHelper = ArrowHelper;
  54639. exports.AttachedBindMode = AttachedBindMode;
  54640. exports.Audio = Audio;
  54641. exports.AudioAnalyser = AudioAnalyser;
  54642. exports.AudioContext = AudioContext;
  54643. exports.AudioListener = AudioListener;
  54644. exports.AudioLoader = AudioLoader;
  54645. exports.AxesHelper = AxesHelper;
  54646. exports.BackSide = BackSide;
  54647. exports.BasicDepthPacking = BasicDepthPacking;
  54648. exports.BasicShadowMap = BasicShadowMap;
  54649. exports.BatchedMesh = BatchedMesh;
  54650. exports.Bone = Bone;
  54651. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  54652. exports.Box2 = Box2;
  54653. exports.Box3 = Box3;
  54654. exports.Box3Helper = Box3Helper;
  54655. exports.BoxGeometry = BoxGeometry;
  54656. exports.BoxHelper = BoxHelper;
  54657. exports.BufferAttribute = BufferAttribute;
  54658. exports.BufferGeometry = BufferGeometry;
  54659. exports.BufferGeometryLoader = BufferGeometryLoader;
  54660. exports.ByteType = ByteType;
  54661. exports.Cache = Cache;
  54662. exports.Camera = Camera;
  54663. exports.CameraHelper = CameraHelper;
  54664. exports.CanvasTexture = CanvasTexture;
  54665. exports.CapsuleGeometry = CapsuleGeometry;
  54666. exports.CatmullRomCurve3 = CatmullRomCurve3;
  54667. exports.CineonToneMapping = CineonToneMapping;
  54668. exports.CircleGeometry = CircleGeometry;
  54669. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  54670. exports.Clock = Clock;
  54671. exports.Color = Color;
  54672. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  54673. exports.ColorManagement = ColorManagement;
  54674. exports.Compatibility = Compatibility;
  54675. exports.CompressedArrayTexture = CompressedArrayTexture;
  54676. exports.CompressedCubeTexture = CompressedCubeTexture;
  54677. exports.CompressedTexture = CompressedTexture;
  54678. exports.CompressedTextureLoader = CompressedTextureLoader;
  54679. exports.ConeGeometry = ConeGeometry;
  54680. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  54681. exports.ConstantColorFactor = ConstantColorFactor;
  54682. exports.Controls = Controls;
  54683. exports.CubeCamera = CubeCamera;
  54684. exports.CubeDepthTexture = CubeDepthTexture;
  54685. exports.CubeReflectionMapping = CubeReflectionMapping;
  54686. exports.CubeRefractionMapping = CubeRefractionMapping;
  54687. exports.CubeTexture = CubeTexture;
  54688. exports.CubeTextureLoader = CubeTextureLoader;
  54689. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  54690. exports.CubicBezierCurve = CubicBezierCurve;
  54691. exports.CubicBezierCurve3 = CubicBezierCurve3;
  54692. exports.CubicInterpolant = CubicInterpolant;
  54693. exports.CullFaceBack = CullFaceBack;
  54694. exports.CullFaceFront = CullFaceFront;
  54695. exports.CullFaceFrontBack = CullFaceFrontBack;
  54696. exports.CullFaceNone = CullFaceNone;
  54697. exports.Curve = Curve;
  54698. exports.CurvePath = CurvePath;
  54699. exports.CustomBlending = CustomBlending;
  54700. exports.CustomToneMapping = CustomToneMapping;
  54701. exports.CylinderGeometry = CylinderGeometry;
  54702. exports.Cylindrical = Cylindrical;
  54703. exports.Data3DTexture = Data3DTexture;
  54704. exports.DataArrayTexture = DataArrayTexture;
  54705. exports.DataTexture = DataTexture;
  54706. exports.DataTextureLoader = DataTextureLoader;
  54707. exports.DataUtils = DataUtils;
  54708. exports.DecrementStencilOp = DecrementStencilOp;
  54709. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  54710. exports.DefaultLoadingManager = DefaultLoadingManager;
  54711. exports.DepthFormat = DepthFormat;
  54712. exports.DepthStencilFormat = DepthStencilFormat;
  54713. exports.DepthTexture = DepthTexture;
  54714. exports.DetachedBindMode = DetachedBindMode;
  54715. exports.DirectionalLight = DirectionalLight;
  54716. exports.DirectionalLightHelper = DirectionalLightHelper;
  54717. exports.DiscreteInterpolant = DiscreteInterpolant;
  54718. exports.DodecahedronGeometry = DodecahedronGeometry;
  54719. exports.DoubleSide = DoubleSide;
  54720. exports.DstAlphaFactor = DstAlphaFactor;
  54721. exports.DstColorFactor = DstColorFactor;
  54722. exports.DynamicCopyUsage = DynamicCopyUsage;
  54723. exports.DynamicDrawUsage = DynamicDrawUsage;
  54724. exports.DynamicReadUsage = DynamicReadUsage;
  54725. exports.EdgesGeometry = EdgesGeometry;
  54726. exports.EllipseCurve = EllipseCurve;
  54727. exports.EqualCompare = EqualCompare;
  54728. exports.EqualDepth = EqualDepth;
  54729. exports.EqualStencilFunc = EqualStencilFunc;
  54730. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  54731. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  54732. exports.Euler = Euler;
  54733. exports.EventDispatcher = EventDispatcher;
  54734. exports.ExternalTexture = ExternalTexture;
  54735. exports.ExtrudeGeometry = ExtrudeGeometry;
  54736. exports.FileLoader = FileLoader;
  54737. exports.Float16BufferAttribute = Float16BufferAttribute;
  54738. exports.Float32BufferAttribute = Float32BufferAttribute;
  54739. exports.FloatType = FloatType;
  54740. exports.Fog = Fog;
  54741. exports.FogExp2 = FogExp2;
  54742. exports.FramebufferTexture = FramebufferTexture;
  54743. exports.FrontSide = FrontSide;
  54744. exports.Frustum = Frustum;
  54745. exports.FrustumArray = FrustumArray;
  54746. exports.GLBufferAttribute = GLBufferAttribute;
  54747. exports.GLSL1 = GLSL1;
  54748. exports.GLSL3 = GLSL3;
  54749. exports.GreaterCompare = GreaterCompare;
  54750. exports.GreaterDepth = GreaterDepth;
  54751. exports.GreaterEqualCompare = GreaterEqualCompare;
  54752. exports.GreaterEqualDepth = GreaterEqualDepth;
  54753. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  54754. exports.GreaterStencilFunc = GreaterStencilFunc;
  54755. exports.GridHelper = GridHelper;
  54756. exports.Group = Group;
  54757. exports.HalfFloatType = HalfFloatType;
  54758. exports.HemisphereLight = HemisphereLight;
  54759. exports.HemisphereLightHelper = HemisphereLightHelper;
  54760. exports.IcosahedronGeometry = IcosahedronGeometry;
  54761. exports.ImageBitmapLoader = ImageBitmapLoader;
  54762. exports.ImageLoader = ImageLoader;
  54763. exports.ImageUtils = ImageUtils;
  54764. exports.IncrementStencilOp = IncrementStencilOp;
  54765. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  54766. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  54767. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  54768. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  54769. exports.InstancedMesh = InstancedMesh;
  54770. exports.Int16BufferAttribute = Int16BufferAttribute;
  54771. exports.Int32BufferAttribute = Int32BufferAttribute;
  54772. exports.Int8BufferAttribute = Int8BufferAttribute;
  54773. exports.IntType = IntType;
  54774. exports.InterleavedBuffer = InterleavedBuffer;
  54775. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  54776. exports.Interpolant = Interpolant;
  54777. exports.InterpolateDiscrete = InterpolateDiscrete;
  54778. exports.InterpolateLinear = InterpolateLinear;
  54779. exports.InterpolateSmooth = InterpolateSmooth;
  54780. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  54781. exports.InterpolationSamplingType = InterpolationSamplingType;
  54782. exports.InvertStencilOp = InvertStencilOp;
  54783. exports.KeepStencilOp = KeepStencilOp;
  54784. exports.KeyframeTrack = KeyframeTrack;
  54785. exports.LOD = LOD;
  54786. exports.LatheGeometry = LatheGeometry;
  54787. exports.Layers = Layers;
  54788. exports.LessCompare = LessCompare;
  54789. exports.LessDepth = LessDepth;
  54790. exports.LessEqualCompare = LessEqualCompare;
  54791. exports.LessEqualDepth = LessEqualDepth;
  54792. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  54793. exports.LessStencilFunc = LessStencilFunc;
  54794. exports.Light = Light;
  54795. exports.LightProbe = LightProbe;
  54796. exports.Line = Line;
  54797. exports.Line3 = Line3;
  54798. exports.LineBasicMaterial = LineBasicMaterial;
  54799. exports.LineCurve = LineCurve;
  54800. exports.LineCurve3 = LineCurve3;
  54801. exports.LineDashedMaterial = LineDashedMaterial;
  54802. exports.LineLoop = LineLoop;
  54803. exports.LineSegments = LineSegments;
  54804. exports.LinearFilter = LinearFilter;
  54805. exports.LinearInterpolant = LinearInterpolant;
  54806. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  54807. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  54808. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  54809. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  54810. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  54811. exports.LinearToneMapping = LinearToneMapping;
  54812. exports.LinearTransfer = LinearTransfer;
  54813. exports.Loader = Loader;
  54814. exports.LoaderUtils = LoaderUtils;
  54815. exports.LoadingManager = LoadingManager;
  54816. exports.LoopOnce = LoopOnce;
  54817. exports.LoopPingPong = LoopPingPong;
  54818. exports.LoopRepeat = LoopRepeat;
  54819. exports.MOUSE = MOUSE;
  54820. exports.Material = Material;
  54821. exports.MaterialBlending = MaterialBlending;
  54822. exports.MaterialLoader = MaterialLoader;
  54823. exports.MathUtils = MathUtils;
  54824. exports.Matrix2 = Matrix2;
  54825. exports.Matrix3 = Matrix3;
  54826. exports.Matrix4 = Matrix4;
  54827. exports.MaxEquation = MaxEquation;
  54828. exports.Mesh = Mesh;
  54829. exports.MeshBasicMaterial = MeshBasicMaterial;
  54830. exports.MeshDepthMaterial = MeshDepthMaterial;
  54831. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  54832. exports.MeshLambertMaterial = MeshLambertMaterial;
  54833. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  54834. exports.MeshNormalMaterial = MeshNormalMaterial;
  54835. exports.MeshPhongMaterial = MeshPhongMaterial;
  54836. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  54837. exports.MeshStandardMaterial = MeshStandardMaterial;
  54838. exports.MeshToonMaterial = MeshToonMaterial;
  54839. exports.MinEquation = MinEquation;
  54840. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  54841. exports.MixOperation = MixOperation;
  54842. exports.MultiplyBlending = MultiplyBlending;
  54843. exports.MultiplyOperation = MultiplyOperation;
  54844. exports.NearestFilter = NearestFilter;
  54845. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  54846. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  54847. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  54848. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  54849. exports.NeutralToneMapping = NeutralToneMapping;
  54850. exports.NeverCompare = NeverCompare;
  54851. exports.NeverDepth = NeverDepth;
  54852. exports.NeverStencilFunc = NeverStencilFunc;
  54853. exports.NoBlending = NoBlending;
  54854. exports.NoColorSpace = NoColorSpace;
  54855. exports.NoNormalPacking = NoNormalPacking;
  54856. exports.NoToneMapping = NoToneMapping;
  54857. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54858. exports.NormalBlending = NormalBlending;
  54859. exports.NormalGAPacking = NormalGAPacking;
  54860. exports.NormalRGPacking = NormalRGPacking;
  54861. exports.NotEqualCompare = NotEqualCompare;
  54862. exports.NotEqualDepth = NotEqualDepth;
  54863. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  54864. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  54865. exports.Object3D = Object3D;
  54866. exports.ObjectLoader = ObjectLoader;
  54867. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  54868. exports.OctahedronGeometry = OctahedronGeometry;
  54869. exports.OneFactor = OneFactor;
  54870. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  54871. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  54872. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  54873. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  54874. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  54875. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  54876. exports.OrthographicCamera = OrthographicCamera;
  54877. exports.PCFShadowMap = PCFShadowMap;
  54878. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  54879. exports.PMREMGenerator = PMREMGenerator;
  54880. exports.Path = Path;
  54881. exports.PerspectiveCamera = PerspectiveCamera;
  54882. exports.Plane = Plane;
  54883. exports.PlaneGeometry = PlaneGeometry;
  54884. exports.PlaneHelper = PlaneHelper;
  54885. exports.PointLight = PointLight;
  54886. exports.PointLightHelper = PointLightHelper;
  54887. exports.Points = Points;
  54888. exports.PointsMaterial = PointsMaterial;
  54889. exports.PolarGridHelper = PolarGridHelper;
  54890. exports.PolyhedronGeometry = PolyhedronGeometry;
  54891. exports.PositionalAudio = PositionalAudio;
  54892. exports.PropertyBinding = PropertyBinding;
  54893. exports.PropertyMixer = PropertyMixer;
  54894. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  54895. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54896. exports.Quaternion = Quaternion;
  54897. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54898. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54899. exports.R11_EAC_Format = R11_EAC_Format;
  54900. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54901. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54902. exports.REVISION = REVISION;
  54903. exports.RG11_EAC_Format = RG11_EAC_Format;
  54904. exports.RGBADepthPacking = RGBADepthPacking;
  54905. exports.RGBAFormat = RGBAFormat;
  54906. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54907. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54908. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54909. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54910. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54911. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54912. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54913. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54914. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54915. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54916. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54917. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54918. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54919. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54920. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54921. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54922. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54923. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54924. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54925. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54926. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54927. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54928. exports.RGBDepthPacking = RGBDepthPacking;
  54929. exports.RGBFormat = RGBFormat;
  54930. exports.RGBIntegerFormat = RGBIntegerFormat;
  54931. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54932. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54933. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54934. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54935. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54936. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54937. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54938. exports.RGDepthPacking = RGDepthPacking;
  54939. exports.RGFormat = RGFormat;
  54940. exports.RGIntegerFormat = RGIntegerFormat;
  54941. exports.RawShaderMaterial = RawShaderMaterial;
  54942. exports.Ray = Ray;
  54943. exports.Raycaster = Raycaster;
  54944. exports.RectAreaLight = RectAreaLight;
  54945. exports.RedFormat = RedFormat;
  54946. exports.RedIntegerFormat = RedIntegerFormat;
  54947. exports.ReinhardToneMapping = ReinhardToneMapping;
  54948. exports.RenderTarget = RenderTarget;
  54949. exports.RenderTarget3D = RenderTarget3D;
  54950. exports.RepeatWrapping = RepeatWrapping;
  54951. exports.ReplaceStencilOp = ReplaceStencilOp;
  54952. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54953. exports.RingGeometry = RingGeometry;
  54954. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  54955. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54956. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54957. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  54958. exports.SRGBColorSpace = SRGBColorSpace;
  54959. exports.SRGBTransfer = SRGBTransfer;
  54960. exports.Scene = Scene;
  54961. exports.ShaderChunk = ShaderChunk;
  54962. exports.ShaderLib = ShaderLib;
  54963. exports.ShaderMaterial = ShaderMaterial;
  54964. exports.ShadowMaterial = ShadowMaterial;
  54965. exports.Shape = Shape;
  54966. exports.ShapeGeometry = ShapeGeometry;
  54967. exports.ShapePath = ShapePath;
  54968. exports.ShapeUtils = ShapeUtils;
  54969. exports.ShortType = ShortType;
  54970. exports.Skeleton = Skeleton;
  54971. exports.SkeletonHelper = SkeletonHelper;
  54972. exports.SkinnedMesh = SkinnedMesh;
  54973. exports.Source = Source;
  54974. exports.Sphere = Sphere;
  54975. exports.SphereGeometry = SphereGeometry;
  54976. exports.Spherical = Spherical;
  54977. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54978. exports.SplineCurve = SplineCurve;
  54979. exports.SpotLight = SpotLight;
  54980. exports.SpotLightHelper = SpotLightHelper;
  54981. exports.Sprite = Sprite;
  54982. exports.SpriteMaterial = SpriteMaterial;
  54983. exports.SrcAlphaFactor = SrcAlphaFactor;
  54984. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54985. exports.SrcColorFactor = SrcColorFactor;
  54986. exports.StaticCopyUsage = StaticCopyUsage;
  54987. exports.StaticDrawUsage = StaticDrawUsage;
  54988. exports.StaticReadUsage = StaticReadUsage;
  54989. exports.StereoCamera = StereoCamera;
  54990. exports.StreamCopyUsage = StreamCopyUsage;
  54991. exports.StreamDrawUsage = StreamDrawUsage;
  54992. exports.StreamReadUsage = StreamReadUsage;
  54993. exports.StringKeyframeTrack = StringKeyframeTrack;
  54994. exports.SubtractEquation = SubtractEquation;
  54995. exports.SubtractiveBlending = SubtractiveBlending;
  54996. exports.TOUCH = TOUCH;
  54997. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54998. exports.TetrahedronGeometry = TetrahedronGeometry;
  54999. exports.Texture = Texture;
  55000. exports.TextureLoader = TextureLoader;
  55001. exports.TextureUtils = TextureUtils;
  55002. exports.Timer = Timer;
  55003. exports.TimestampQuery = TimestampQuery;
  55004. exports.TorusGeometry = TorusGeometry;
  55005. exports.TorusKnotGeometry = TorusKnotGeometry;
  55006. exports.Triangle = Triangle;
  55007. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  55008. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  55009. exports.TrianglesDrawMode = TrianglesDrawMode;
  55010. exports.TubeGeometry = TubeGeometry;
  55011. exports.UVMapping = UVMapping;
  55012. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  55013. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  55014. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  55015. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  55016. exports.Uniform = Uniform;
  55017. exports.UniformsGroup = UniformsGroup;
  55018. exports.UniformsLib = UniformsLib;
  55019. exports.UniformsUtils = UniformsUtils;
  55020. exports.UnsignedByteType = UnsignedByteType;
  55021. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  55022. exports.UnsignedInt248Type = UnsignedInt248Type;
  55023. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  55024. exports.UnsignedIntType = UnsignedIntType;
  55025. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  55026. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  55027. exports.UnsignedShortType = UnsignedShortType;
  55028. exports.VSMShadowMap = VSMShadowMap;
  55029. exports.Vector2 = Vector2;
  55030. exports.Vector3 = Vector3;
  55031. exports.Vector4 = Vector4;
  55032. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  55033. exports.VideoFrameTexture = VideoFrameTexture;
  55034. exports.VideoTexture = VideoTexture;
  55035. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  55036. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  55037. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  55038. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  55039. exports.WebGLRenderTarget = WebGLRenderTarget;
  55040. exports.WebGLRenderer = WebGLRenderer;
  55041. exports.WebGLUtils = WebGLUtils;
  55042. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  55043. exports.WebXRController = WebXRController;
  55044. exports.WireframeGeometry = WireframeGeometry;
  55045. exports.WrapAroundEnding = WrapAroundEnding;
  55046. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  55047. exports.ZeroFactor = ZeroFactor;
  55048. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  55049. exports.ZeroStencilOp = ZeroStencilOp;
  55050. exports.createCanvasElement = createCanvasElement;
  55051. exports.error = error;
  55052. exports.getConsoleFunction = getConsoleFunction;
  55053. exports.log = log;
  55054. exports.setConsoleFunction = setConsoleFunction;
  55055. exports.warn = warn;
  55056. exports.warnOnce = warnOnce;
粤ICP备19079148号